blob: 131c463bad9e694dc5b5a21e9e5e35faf3de9c2f [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;
dalyk7301aa42018-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;
Hugo Benichib577d652017-06-27 15:13:20 +090063import 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;
Robert Greenwalt434203a2010-10-11 16:00:27 -070077import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040078import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070079import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040080import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040081import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060082import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090083import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090084import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090085import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080087import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070088import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040089import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070091import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070092import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070093import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.os.Looper;
95import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070096import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070097import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090098import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070099import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700100import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700101import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800102import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900103import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900104import android.os.ServiceSpecificException;
mswest462b24f8c2018-03-12 10:34:34 -0700105import android.os.ShellCallback;
106import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900107import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700108import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400109import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700111import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700112import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700113import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700114import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900115import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700116import android.util.LocalLog;
117import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600118import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800119import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700120import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500121import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700122import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700123import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
Wink Savilleab9321d2013-06-29 21:10:57 -0700125import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400126import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400127import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700128import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700129import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700130import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800131import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700132import com.android.internal.net.VpnProfile;
Erik Klinec172c7d2018-05-01 16:51:44 +0900133import com.android.internal.util.ArrayUtils;
Robert Greenwalte049c232014-04-11 15:53:27 -0700134import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600135import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700136import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900137import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900138import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700139import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700140import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400141import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900142import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900143import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
dalyk7301aa42018-03-05 12:42:22 -0500144import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900145import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900146import com.android.server.connectivity.KeepaliveTracker;
Charles Hea0a87e82017-05-15 17:07:18 +0100147import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700148import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700149import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600150import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400151import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900152import com.android.server.connectivity.NetworkNotificationManager;
153import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400154import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700155import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800156import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700157import com.android.server.connectivity.Vpn;
Hugo Benichib577d652017-06-27 15:13:20 +0900158import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500159import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700160import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700161import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900162import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600163
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700164import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700165
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700166import org.xmlpull.v1.XmlPullParser;
167import org.xmlpull.v1.XmlPullParserException;
168
169import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700171import java.io.FileNotFoundException;
172import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700173import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700175import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700176import java.net.InetAddress;
177import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700178import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700179import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700180import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700181import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700182import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700183import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700184import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700185import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700186import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900187import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600188import java.util.SortedSet;
189import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190
191/**
192 * @hide
193 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800194public class ConnectivityService extends IConnectivityManager.Stub
195 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900196 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
Chalard Jean4133a122018-06-04 13:33:12 +0900198 private static final String DIAG_ARG = "--diag";
Erik Kline7747fd42017-05-12 16:52:48 +0900199 public static final String SHORT_ARG = "--short";
Chalard Jean4133a122018-06-04 13:33:12 +0900200 private static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900201
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900202 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700203 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900205 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700206
Jeff Sharkey899223b2012-08-04 15:24:58 -0700207 // TODO: create better separation between radio types and network types
208
Robert Greenwalt42acef32009-08-12 16:08:25 -0700209 // how long to wait before switching back to a radio's default network
210 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
211 // system property that can override the above value
212 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
213 "android.telephony.apn-restore";
214
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900215 // How long to wait before putting up a "This network doesn't have an Internet connection,
216 // connect anyway?" dialog after the user selects a network that doesn't validate.
217 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
218
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900219 // Default to 30s linger time-out. Modifiable only for testing.
220 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
221 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
222 @VisibleForTesting
223 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
224
Jeremy Joslin79294842014-12-03 17:15:28 -0800225 // How long to delay to removal of a pending intent based request.
226 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
227 private final int mReleasePendingIntentDelayMs;
228
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900229 private MockableSystemProperties mSystemProperties;
230
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800231 private Tethering mTethering;
232
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700233 private final PermissionMonitor mPermissionMonitor;
234
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700235 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700236
Chalard Jean3e2fb662018-04-18 19:18:58 +0900237 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700238 @GuardedBy("mVpns")
Chalard Jean4133a122018-06-04 13:33:12 +0900239 protected final SparseArray<Vpn> mVpns = new SparseArray<>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700240
Hugo Benichi69744342017-11-27 10:57:16 +0900241 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
242 // a direct call to LockdownVpnTracker.isEnabled().
243 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700244 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900245 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700246 private LockdownVpnTracker mLockdownTracker;
247
Erik Klineda4bfa82015-04-30 12:58:40 +0900248 final private Context mContext;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700249 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700250 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700252 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800253 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700254 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900255 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700256
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700257 private String mCurrentTcpBufferSizes;
258
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900259 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900260 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
261 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900262
Paul Jensenb10e37f2014-11-25 12:33:08 -0500263 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400264 // Tear down networks that have no chance (e.g. even if validated) of becoming
265 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500266 // all networks have been rematched against all NetworkRequests.
267 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400268 // Don't reap networks. This should be passed when some networks have not yet been
269 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500270 DONT_REAP
Chalard Jean4133a122018-06-04 13:33:12 +0900271 }
Paul Jensenb10e37f2014-11-25 12:33:08 -0500272
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900273 private enum UnneededFor {
274 LINGER, // Determine whether this network is unneeded and should be lingered.
275 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
276 }
277
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700278 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700279 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700280 * from one net to another. Clear happens when we get a new
281 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
282 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700283 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700284 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700285
Robert Greenwalt434203a2010-10-11 16:00:27 -0700286 /**
287 * used internally to reload global proxy settings
288 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700289 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700290
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700291 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400292 * PAC manager has received new port.
293 */
294 private static final int EVENT_PROXY_HAS_CHANGED = 16;
295
Robert Greenwalte049c232014-04-11 15:53:27 -0700296 /**
297 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700298 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700299 */
300 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
301
Robert Greenwalt7b816022014-04-18 15:25:25 -0700302 /**
303 * used internally when registering NetworkAgents
304 * obj = Messenger
305 */
306 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
307
Robert Greenwalt9258c642014-03-26 16:47:06 -0700308 /**
309 * used to add a network request
310 * includes a NetworkRequestInfo
311 */
312 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
313
314 /**
315 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900316 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700317 * cancel it.
318 * includes a NetworkRequestInfo
319 */
320 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
321
322 /**
323 * used to add a network listener - no request
324 * includes a NetworkRequestInfo
325 */
326 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
327
328 /**
329 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400330 * arg1 = UID of caller
331 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700332 */
333 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
334
Robert Greenwalta67be032014-05-16 15:49:14 -0700335 /**
336 * used internally when registering NetworkFactories
337 * obj = Messenger
338 */
339 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
340
Robert Greenwalt27711812014-06-25 16:45:57 -0700341 /**
342 * used internally to expire a wakelock when transitioning
343 * from one net to another. Expire happens when we fail to find
344 * a new network (typically after 1 minute) -
345 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
346 * a replacement network.
347 */
348 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
349
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700350 /**
351 * Used internally to indicate the system is ready.
352 */
353 private static final int EVENT_SYSTEM_READY = 25;
354
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800355 /**
356 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400357 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800358 */
359 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
360
361 /**
362 * used to remove a pending intent and its associated network request.
363 * arg1 = UID of caller
364 * obj = PendingIntent
365 */
366 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
367
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900368 /**
369 * used to specify whether a network should be used even if unvalidated.
370 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
371 * arg2 = whether to remember this choice in the future (1 or 0)
372 * obj = network
373 */
374 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
375
376 /**
377 * used to ask the user to confirm a connection to an unvalidated network.
378 * obj = network
379 */
380 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700381
Erik Klineda4bfa82015-04-30 12:58:40 +0900382 /**
383 * used internally to (re)configure mobile data always-on settings.
384 */
385 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
386
Paul Jensen694f2b82015-06-17 14:15:39 -0400387 /**
388 * used to add a network listener with a pending intent
389 * obj = NetworkRequestInfo
390 */
391 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
392
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900393 /**
394 * used to specify whether a network should not be penalized when it becomes unvalidated.
395 */
396 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
397
398 /**
399 * used to trigger revalidation of a network.
400 */
401 private static final int EVENT_REVALIDATE_NETWORK = 36;
402
Erik Klinea24d4592018-01-11 21:07:29 +0900403 // Handle changes in Private DNS settings.
404 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
405
dalyk7301aa42018-03-05 12:42:22 -0500406 // Handle private DNS validation status updates.
407 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
408
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900409 private static String eventName(int what) {
410 return sMagicDecoderRing.get(what, Integer.toString(what));
411 }
412
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900413 /** Handler thread used for both of the handlers below. */
414 @VisibleForTesting
415 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700416 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700417 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700418 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700419 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900420 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700421
Mike Lockwood0f79b542009-08-14 14:18:49 -0400422 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800423 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400424
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700425 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700426 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800427 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700428
Robert Greenwalt434203a2010-10-11 16:00:27 -0700429 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400430 private volatile ProxyInfo mDefaultProxy = null;
Chalard Jean4133a122018-06-04 13:33:12 +0900431 private final Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700432 private boolean mDefaultProxyDisabled = false;
433
Robert Greenwalt434203a2010-10-11 16:00:27 -0700434 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400435 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700436
Jason Monk602b2322013-07-03 17:04:33 -0400437 private PacManager mPacManager = null;
438
Erik Klineda4bfa82015-04-30 12:58:40 +0900439 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700440
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400441 private UserManager mUserManager;
442
Chalard Jean4133a122018-06-04 13:33:12 +0900443 private NetworkConfig[] mNetConfigs;
444 private int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700445
Robert Greenwalt50393202011-06-21 17:26:14 -0700446 // the set of network types that can only be enabled by system/sig apps
Chalard Jean4133a122018-06-04 13:33:12 +0900447 private List mProtectedNetworks;
Robert Greenwalt50393202011-06-21 17:26:14 -0700448
Chalard Jean4133a122018-06-04 13:33:12 +0900449 private TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400450
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900451 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900452 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900453 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900454
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700455 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800456 private static final int MIN_NET_ID = 100; // some reserved marks
457 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700458 private int mNextNetId = MIN_NET_ID;
459
Robert Greenwalt34524f02014-05-18 16:22:10 -0700460 // sequence number of NetworkRequests
461 private int mNextNetworkRequestId = 1;
462
Erik Kline7523eb32015-07-09 18:24:03 +0900463 // NetworkRequest activity String log entries.
464 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
465 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
466
Hugo Benichic2ae2872016-07-11 11:05:12 +0900467 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900468 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900469 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
470
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900471 private static final int MAX_WAKELOCK_LOGS = 20;
472 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichic3318aa2017-09-05 13:25:07 +0900473 private int mTotalWakelockAcquisitions = 0;
474 private int mTotalWakelockReleases = 0;
475 private long mTotalWakelockDurationMs = 0;
476 private long mMaxWakelockDurationMs = 0;
477 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900478
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700479 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
480 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400481 private static class ValidationLog {
482 final Network mNetwork;
Chalard Jeanfdd9e2f2018-04-26 16:16:10 +0900483 final String mName;
Paul Jensen0808eb82016-06-03 13:51:21 -0400484 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700485
Chalard Jeanfdd9e2f2018-04-26 16:16:10 +0900486 ValidationLog(Network network, String name, ReadOnlyLocalLog log) {
Paul Jensen0808eb82016-06-03 13:51:21 -0400487 mNetwork = network;
Chalard Jeanfdd9e2f2018-04-26 16:16:10 +0900488 mName = name;
Paul Jensen0808eb82016-06-03 13:51:21 -0400489 mLog = log;
490 }
491 }
Chalard Jean4133a122018-06-04 13:33:12 +0900492 private final ArrayDeque<ValidationLog> mValidationLogs = new ArrayDeque<>(MAX_VALIDATION_LOGS);
Paul Jensen0808eb82016-06-03 13:51:21 -0400493
Chalard Jeanfdd9e2f2018-04-26 16:16:10 +0900494 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String name) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900495 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700496 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
497 mValidationLogs.removeLast();
498 }
Chalard Jeanfdd9e2f2018-04-26 16:16:10 +0900499 mValidationLogs.addFirst(new ValidationLog(network, name, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700500 }
501 }
502
Hugo Benichif9fdf872016-07-28 17:53:06 +0900503 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900504
Erik Kline065ab6e2016-10-02 18:02:14 +0900505 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900506 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900507
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700508 /**
509 * Implements support for the legacy "one network per network type" model.
510 *
511 * We used to have a static array of NetworkStateTrackers, one for each
512 * network type, but that doesn't work any more now that we can have,
513 * for example, more that one wifi network. This class stores all the
514 * NetworkAgentInfo objects that support a given type, but the legacy
515 * API will only see the first one.
516 *
517 * It serves two main purposes:
518 *
519 * 1. Provide information about "the network for a given type" (since this
520 * API only supports one).
521 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
522 * the first network for a given type changes, or if the default network
523 * changes.
524 */
525 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900526
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900527 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900528 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900529
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700530 /**
531 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
532 * Each list holds references to all NetworkAgentInfos that are used to
533 * satisfy requests for that network type.
534 *
535 * This array is built out at startup such that an unsupported network
536 * doesn't get an ArrayList instance, making this a tristate:
537 * unsupported, supported but not active and active.
538 *
539 * The actual lists are populated when we scan the network types that
540 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900541 *
542 * Threading model:
543 * - addSupportedType() is only called in the constructor
544 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
545 * They are therefore not thread-safe with respect to each other.
546 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
547 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
548 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700549 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900550 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700551
552 public LegacyTypeTracker() {
553 mTypeLists = (ArrayList<NetworkAgentInfo>[])
554 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
555 }
556
557 public void addSupportedType(int type) {
558 if (mTypeLists[type] != null) {
559 throw new IllegalStateException(
560 "legacy list for type " + type + "already initialized");
561 }
Chalard Jean4133a122018-06-04 13:33:12 +0900562 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563 }
564
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700565 public boolean isTypeSupported(int type) {
566 return isNetworkTypeValid(type) && mTypeLists[type] != null;
567 }
568
569 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900570 synchronized (mTypeLists) {
571 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
572 return mTypeLists[type].get(0);
573 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700574 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900575 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700576 }
577
Robert Greenwalt8d482522015-06-24 13:23:42 -0700578 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900579 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700581 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900582 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900583 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900584 }
585 }
586
587 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700588 public void add(int type, NetworkAgentInfo nai) {
589 if (!isTypeSupported(type)) {
590 return; // Invalid network type.
591 }
592 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
593
594 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
595 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 return;
597 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900598 synchronized (mTypeLists) {
599 list.add(nai);
600 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900601
602 // 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 +0900603 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900604 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700605 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
606 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700607 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700608 }
609
Lorenzo Colittia793a672014-07-31 23:20:17 +0900610 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900611 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900612 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
613 if (list == null || list.isEmpty()) {
614 return;
615 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900616 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900617
Hugo Benichi78caa2582016-06-21 09:48:07 +0900618 synchronized (mTypeLists) {
619 if (!list.remove(nai)) {
620 return;
621 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900622 }
623
Robert Greenwalt8d482522015-06-24 13:23:42 -0700624 final DetailedState state = DetailedState.DISCONNECTED;
625
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900626 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700627 maybeLogBroadcast(nai, state, type, wasDefault);
628 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900629 }
630
631 if (!list.isEmpty() && wasFirstNetwork) {
632 if (DBG) log("Other network available for type " + type +
633 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900634 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700635 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
636 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900637 }
638 }
639
640 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900641 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
642 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700643 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900644 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700645 }
646 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700647
Robert Greenwalt8d482522015-06-24 13:23:42 -0700648 // send out another legacy broadcast - currently only used for suspend/unsuspend
649 // toggle
650 public void update(NetworkAgentInfo nai) {
651 final boolean isDefault = isDefaultNetwork(nai);
652 final DetailedState state = nai.networkInfo.getDetailedState();
653 for (int type = 0; type < mTypeLists.length; type++) {
654 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700655 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900656 final boolean isFirst = contains && (nai == list.get(0));
657 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700658 maybeLogBroadcast(nai, state, type, isDefault);
659 sendLegacyNetworkBroadcast(nai, state, type);
660 }
661 }
662 }
663
Lorenzo Colittia793a672014-07-31 23:20:17 +0900664 private String naiToString(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +0900665 String name = nai.name();
Lorenzo Colittia793a672014-07-31 23:20:17 +0900666 String state = (nai.networkInfo != null) ?
667 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
668 "???/???";
669 return name + " " + state;
670 }
671
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700672 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900673 pw.println("mLegacyTypeTracker:");
674 pw.increaseIndent();
675 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700676 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900677 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700678 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900679 pw.println();
680 pw.println("Current state:");
681 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900682 synchronized (mTypeLists) {
683 for (int type = 0; type < mTypeLists.length; type++) {
684 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
685 for (NetworkAgentInfo nai : mTypeLists[type]) {
686 pw.println(type + " " + naiToString(nai));
687 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900688 }
689 }
690 pw.decreaseIndent();
691 pw.decreaseIndent();
692 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700693 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700694 }
695 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
696
Jeff Sharkey899223b2012-08-04 15:24:58 -0700697 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700698 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900699 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
700 }
701
702 @VisibleForTesting
703 protected ConnectivityService(Context context, INetworkManagementService netManager,
704 INetworkStatsService statsService, INetworkPolicyManager policyManager,
705 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800706 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800707
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900708 mSystemProperties = getSystemProperties();
709
Hugo Benichif9fdf872016-07-28 17:53:06 +0900710 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900711 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900712 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900713 mNetworkRequests.put(mDefaultRequest, defaultNRI);
714 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900715
Chalard Jeandda156a2018-01-10 21:19:32 +0900716 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900717 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700718
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900719 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900720 mHandlerThread.start();
721 mHandler = new InternalHandler(mHandlerThread.getLooper());
722 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700723
Jeremy Joslin79294842014-12-03 17:15:28 -0800724 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
725 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
726
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900727 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900728
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700729 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700730 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800731 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700732 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900733 mPolicyManagerInternal = checkNotNull(
734 LocalServices.getService(NetworkPolicyManagerInternal.class),
735 "missing NetworkPolicyManagerInternal");
736
Jeff Sharkey82f85212012-08-24 11:17:25 -0700737 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700738 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700739
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700740 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900741 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700742 } catch (RemoteException e) {
743 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700744 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700745 }
746
747 final PowerManager powerManager = (PowerManager) context.getSystemService(
748 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700749 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
750 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
751 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800752 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700753
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700754 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700755
Wink Saville51f456f2013-04-23 14:26:51 -0700756 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900757 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700758 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700759 String[] naStrings = context.getResources().getStringArray(
760 com.android.internal.R.array.networkAttributes);
761 for (String naString : naStrings) {
762 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700763 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700764 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700765 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800766 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700767 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700768 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700769 }
Wink Saville51f456f2013-04-23 14:26:51 -0700770 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
771 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
772 n.type);
773 continue;
774 }
Wink Saville975c8482011-04-07 14:23:45 -0700775 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800776 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700777 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700778 continue;
779 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700780 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700781
Wink Saville975c8482011-04-07 14:23:45 -0700782 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700783 mNetworksDefined++;
784 } catch(Exception e) {
785 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700786 }
787 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700788
789 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
790 if (mNetConfigs[TYPE_VPN] == null) {
791 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
792 // don't need to add TYPE_VPN to mNetConfigs.
793 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
794 mNetworksDefined++; // used only in the log() statement below.
795 }
796
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900797 // Do the same for Ethernet, since it's often not specified in the configs, although many
798 // devices can use it via USB host adapters.
799 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
800 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
801 mNetworksDefined++;
802 }
803
Wink Saville5e56bc52013-07-29 15:00:57 -0700804 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700805
Robert Greenwalt50393202011-06-21 17:26:14 -0700806 mProtectedNetworks = new ArrayList<Integer>();
807 int[] protectedNetworks = context.getResources().getIntArray(
808 com.android.internal.R.array.config_protectedNetworks);
809 for (int p : protectedNetworks) {
810 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
811 mProtectedNetworks.add(p);
812 } else {
813 if (DBG) loge("Ignoring protectedNetwork " + p);
814 }
815 }
816
Erik Kline47222fc2017-04-30 19:36:15 +0900817 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800818
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700819 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
820
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700821 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700822 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100823 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700824 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700825 intentFilter.addAction(Intent.ACTION_USER_ADDED);
826 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000827 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700828 mContext.registerReceiverAsUser(
829 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000830 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
831 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900832
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700833 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700834 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700835 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700836 } catch (RemoteException e) {
837 loge("Error registering observer :" + e);
838 }
839
Erik Klineda4bfa82015-04-30 12:58:40 +0900840 mSettingsObserver = new SettingsObserver(mContext, mHandler);
841 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800842
Chalard Jean4133a122018-06-04 13:33:12 +0900843 final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext);
844 dataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400845
Jason Monkdecd2952013-10-10 14:02:51 -0400846 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700847
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400848 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900849
850 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900851 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
852 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900853
854 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
855 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
856 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
857 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
858 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
859 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
860 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900861
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900862 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900863 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900864 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900865
866 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900867 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700869
Erik Kline47222fc2017-04-30 19:36:15 +0900870 private Tethering makeTethering() {
871 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900872 final TetheringDependencies deps = new TetheringDependencies() {
873 @Override
874 public boolean isTetheringSupported() {
875 return ConnectivityService.this.isTetheringSupported();
876 }
877 };
Erik Kline47222fc2017-04-30 19:36:15 +0900878 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
879 IoThread.get().getLooper(), new MockableSystemProperties(),
880 deps);
881 }
882
Chalard Jeanff8710a2018-04-18 20:18:38 +0900883 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
884 final NetworkCapabilities netCap = new NetworkCapabilities();
885 netCap.addCapability(NET_CAPABILITY_INTERNET);
886 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
887 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
888 netCap.setSingleUid(uid);
889 return netCap;
890 }
891
Chalard Jeandda156a2018-01-10 21:19:32 +0900892 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900893 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900894 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900895 netCap.addCapability(NET_CAPABILITY_INTERNET);
896 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900897 if (transportType > -1) {
898 netCap.addTransportType(transportType);
899 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900900 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900901 }
902
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900903 // Used only for testing.
904 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -0700905 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900906 // changing ContentResolver to make registerContentObserver non-final).
907 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
908 // by subclassing SettingsObserver.
909 @VisibleForTesting
910 void updateMobileDataAlwaysOn() {
911 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
912 }
913
Erik Kline736353a2018-03-21 07:18:33 -0700914 // See FakeSettingsProvider comment above.
915 @VisibleForTesting
916 void updatePrivateDnsSettings() {
917 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
918 }
919
Erik Klineda4bfa82015-04-30 12:58:40 +0900920 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900921 final boolean enable = toBool(Settings.Global.getInt(
922 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900923 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
924 if (enable == isEnabled) {
925 return; // Nothing to do.
926 }
927
928 if (enable) {
929 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900930 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900931 } else {
932 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
933 }
934 }
935
936 private void registerSettingsCallbacks() {
937 // Watch for global HTTP proxy changes.
938 mSettingsObserver.observe(
939 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
940 EVENT_APPLY_GLOBAL_HTTP_PROXY);
941
942 // Watch for whether or not to keep mobile data always on.
943 mSettingsObserver.observe(
944 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
945 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
946 }
947
Erik Klinea24d4592018-01-11 21:07:29 +0900948 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -0700949 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
950 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +0900951 }
952 }
953
Robert Greenwalt34524f02014-05-18 16:22:10 -0700954 private synchronized int nextNetworkRequestId() {
955 return mNextNetworkRequestId++;
956 }
957
Paul Jensen67b0b072015-06-10 11:22:17 -0400958 @VisibleForTesting
959 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400960 synchronized (mNetworkForNetId) {
961 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
962 int netId = mNextNetId;
963 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
964 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500965 if (!mNetIdInUse.get(netId)) {
966 mNetIdInUse.put(netId, true);
967 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400968 }
969 }
970 }
971 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700972 }
973
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600974 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800975 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600976 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
977 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800978 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600979 state = nai.getNetworkState();
980 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800981 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600982 final NetworkInfo info = new NetworkInfo(networkType, 0,
983 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800984 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
985 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700986 final NetworkCapabilities capabilities = new NetworkCapabilities();
987 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
988 !info.isRoaming());
989 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600990 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800991 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600992 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600993 return state;
994 } else {
995 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800996 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400997 }
998
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800999 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1000 if (network == null) {
1001 return null;
1002 }
Erik Kline736353a2018-03-21 07:18:33 -07001003 return getNetworkAgentInfoForNetId(network.netId);
1004 }
1005
1006 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001007 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001008 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001009 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001010 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001011
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001012 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001013 synchronized (mVpns) {
1014 if (!mLockdownEnabled) {
1015 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001016 Vpn vpn = mVpns.get(user);
1017 if (vpn != null && vpn.appliesToUid(uid)) {
1018 return vpn.getUnderlyingNetworks();
1019 }
1020 }
1021 }
1022 return null;
1023 }
1024
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001025 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001026 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001027
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001028 final Network[] networks = getVpnUnderlyingNetworks(uid);
1029 if (networks != null) {
1030 // getUnderlyingNetworks() returns:
1031 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1032 // empty array => the VPN explicitly said "no default network".
1033 // non-empty array => the VPN specified one or more default networks; we use the
1034 // first one.
1035 if (networks.length > 0) {
1036 nai = getNetworkAgentInfoForNetwork(networks[0]);
1037 } else {
1038 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001039 }
1040 }
1041
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001042 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001043 return nai.getNetworkState();
1044 } else {
1045 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001046 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001047 }
1048
1049 /**
1050 * Check if UID should be blocked from using the network with the given LinkProperties.
1051 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001052 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1053 boolean ignoreBlocked) {
1054 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001055 if (ignoreBlocked) {
1056 return false;
1057 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001058 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001059 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1060 if (isSystem(uid)) {
1061 return false;
1062 }
Robin Lee17e61832016-05-09 13:46:28 +01001063 synchronized (mVpns) {
1064 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1065 if (vpn != null && vpn.isBlockingUid(uid)) {
1066 return true;
1067 }
1068 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001069 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001070 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001071 }
1072
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001073 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001074 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1075 return;
1076 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001077 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001078 synchronized (mBlockedAppUids) {
1079 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001080 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001081 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001082 blocked = false;
1083 } else {
1084 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001085 }
1086 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001087 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1088 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1089 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001090 }
1091
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001092 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001093 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1094 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001095 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001096 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001097 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001098 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1099
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001100 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001101 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001102 }
Hugo Benichi69744342017-11-27 10:57:16 +09001103 synchronized (mVpns) {
1104 if (mLockdownTracker != null) {
1105 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1106 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001107 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001108 }
1109
1110 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 * Return NetworkInfo for the active (i.e., connected) network interface.
1112 * It is assumed that at most one network is active at a time. If more
1113 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001114 * @return the info for the active network, or {@code null} if none is
1115 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001117 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001119 enforceAccessPermission();
1120 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001121 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001123 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1124 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 }
1126
Paul Jensen31a94f42015-02-13 14:18:39 -05001127 @Override
1128 public Network getActiveNetwork() {
1129 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001130 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001131 }
1132
1133 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001134 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001135 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001136 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001137 }
1138
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001139 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001140 final int user = UserHandle.getUserId(uid);
1141 int vpnNetId = NETID_UNSET;
1142 synchronized (mVpns) {
1143 final Vpn vpn = mVpns.get(user);
Chalard Jeanff8710a2018-04-18 20:18:38 +09001144 // TODO : now that capabilities contain the UID, the appliesToUid test should
1145 // be removed as the satisfying test below should be enough.
Paul Jensen31a94f42015-02-13 14:18:39 -05001146 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1147 }
1148 NetworkAgentInfo nai;
1149 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001150 nai = getNetworkAgentInfoForNetId(vpnNetId);
Chalard Jeanff8710a2018-04-18 20:18:38 +09001151 if (nai != null) {
1152 final NetworkCapabilities requiredCaps =
1153 createDefaultNetworkCapabilitiesForUid(uid);
1154 if (requiredCaps.satisfiedByNetworkCapabilities(nai.networkCapabilities)) {
1155 return nai.network;
1156 }
1157 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001158 }
1159 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001160 if (nai != null
1161 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1162 nai = null;
1163 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001164 return nai != null ? nai.network : null;
1165 }
1166
Lorenzo Colitti18660282016-07-04 12:55:44 +09001167 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001168 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1169 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001170 final int uid = Binder.getCallingUid();
1171 NetworkState state = getUnfilteredActiveNetworkState(uid);
1172 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001173 }
1174
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001175 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001176 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001177 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001178 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001179 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001180 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001181 }
1182
1183 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 public NetworkInfo getNetworkInfo(int networkType) {
1185 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001186 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001187 if (getVpnUnderlyingNetworks(uid) != null) {
1188 // A VPN is active, so we may need to return one of its underlying networks. This
1189 // information is not available in LegacyTypeTracker, so we have to get it from
1190 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001191 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001192 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001193 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001194 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001195 }
1196 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001197 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001198 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 }
1200
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001201 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001202 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001203 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001204 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001205 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001206 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001207 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001208 return state.networkInfo;
1209 } else {
1210 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001211 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001212 }
1213
1214 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 public NetworkInfo[] getAllNetworkInfo() {
1216 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001217 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001218 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1219 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001220 NetworkInfo info = getNetworkInfo(networkType);
1221 if (info != null) {
1222 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001225 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 }
1227
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001228 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001229 public Network getNetworkForType(int networkType) {
1230 enforceAccessPermission();
1231 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001232 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1233 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001234 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001235 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001237 }
1238
1239 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001240 public Network[] getAllNetworks() {
1241 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001242 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001243 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001244 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001245 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001246 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001247 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001248 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001249 }
1250
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001251 @Override
1252 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1253 // The basic principle is: if an app's traffic could possibly go over a
1254 // network, without the app doing anything multinetwork-specific,
1255 // (hence, by "default"), then include that network's capabilities in
1256 // the array.
1257 //
1258 // In the normal case, app traffic only goes over the system's default
1259 // network connection, so that's the only network returned.
1260 //
1261 // With a VPN in force, some app traffic may go into the VPN, and thus
1262 // over whatever underlying networks the VPN specifies, while other app
1263 // traffic may go over the system default network (e.g.: a split-tunnel
1264 // VPN, or an app disallowed by the VPN), so the set of networks
1265 // returned includes the VPN's underlying networks and the system
1266 // default.
1267 enforceAccessPermission();
1268
Chalard Jean4133a122018-06-04 13:33:12 +09001269 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001270
1271 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001272 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001273 if (nc != null) {
1274 result.put(nai.network, nc);
1275 }
1276
Hugo Benichi69744342017-11-27 10:57:16 +09001277 synchronized (mVpns) {
1278 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001279 Vpn vpn = mVpns.get(userId);
1280 if (vpn != null) {
1281 Network[] networks = vpn.getUnderlyingNetworks();
1282 if (networks != null) {
1283 for (Network network : networks) {
1284 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001285 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001286 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001287 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001288 }
1289 }
1290 }
1291 }
1292 }
1293 }
1294
1295 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1296 out = result.values().toArray(out);
1297 return out;
1298 }
1299
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001300 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001301 public boolean isNetworkSupported(int networkType) {
1302 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001303 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001304 }
1305
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001306 /**
1307 * Return LinkProperties for the active (i.e., connected) default
1308 * network interface. It is assumed that at most one default network
1309 * is active at a time. If more than one is active, it is indeterminate
1310 * which will be returned.
1311 * @return the ip properties for the active network, or {@code null} if
1312 * none is active
1313 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001314 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001315 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001316 enforceAccessPermission();
1317 final int uid = Binder.getCallingUid();
1318 NetworkState state = getUnfilteredActiveNetworkState(uid);
1319 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001320 }
1321
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001322 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001323 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001324 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001325 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1326 if (nai != null) {
1327 synchronized (nai) {
1328 return new LinkProperties(nai.linkProperties);
1329 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001330 }
1331 return null;
1332 }
1333
Robert Greenwalt12e67352014-05-13 21:41:06 -07001334 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001335 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001336 public LinkProperties getLinkProperties(Network network) {
1337 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001338 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1339 }
1340
1341 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1342 if (nai == null) {
1343 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001344 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001345 synchronized (nai) {
1346 return new LinkProperties(nai.linkProperties);
1347 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001348 }
1349
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001350 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001351 if (nai != null) {
1352 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001353 if (nai.networkCapabilities != null) {
Chalard Jean6bc18fb2018-04-11 21:09:10 +09001354 return networkCapabilitiesRestrictedForCallerPermissions(
1355 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001356 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001357 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001358 }
1359 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001360 return null;
1361 }
1362
1363 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001364 public NetworkCapabilities getNetworkCapabilities(Network network) {
1365 enforceAccessPermission();
1366 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1367 }
1368
Chalard Jean6bc18fb2018-04-11 21:09:10 +09001369 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001370 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean6bc18fb2018-04-11 21:09:10 +09001371 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jeanff8710a2018-04-18 20:18:38 +09001372 if (!checkSettingsPermission(callerPid, callerUid)) {
1373 newNc.setUids(null);
1374 newNc.setSSID(null);
1375 }
Chalard Jean6bc18fb2018-04-11 21:09:10 +09001376 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001377 }
1378
Chalard Jeanb552c462018-02-21 18:43:54 +09001379 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1380 if (!checkSettingsPermission()) {
1381 nc.setSingleUid(Binder.getCallingUid());
1382 }
1383 }
1384
Chalard Jean1d738002018-03-20 19:13:57 +09001385 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1386 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1387 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1388 }
1389 }
1390
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001391 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001392 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001393 // Require internal since we're handing out IMSI details
1394 enforceConnectivityInternalPermission();
1395
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001396 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001397 for (Network network : getAllNetworks()) {
1398 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1399 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001400 // TODO (b/73321673) : NetworkState contains a copy of the
1401 // NetworkCapabilities, which may contain UIDs of apps to which the
1402 // network applies. Should the UIDs be cleared so as not to leak or
1403 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001404 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001405 }
1406 }
1407 return result.toArray(new NetworkState[result.size()]);
1408 }
1409
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001410 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001411 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001412 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001413 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1414 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1415 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001416 }
1417
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001418 @Override
1419 public boolean isActiveNetworkMetered() {
1420 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001421
Eric Enslen7784d2c2018-02-07 18:03:53 -08001422 final int uid = Binder.getCallingUid();
1423 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001424 if (caps != null) {
1425 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1426 } else {
1427 // Always return the most conservative value
1428 return true;
1429 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001430 }
1431
Jeff Sharkey216c1812012-08-05 14:29:23 -07001432 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1433 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001434 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001435 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001436 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001437 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001438 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001439
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001440 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 * Ensure that a network route exists to deliver traffic to the specified
1442 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001443 * @param networkType the type of the network over which traffic to the
1444 * specified host is to be routed
1445 * @param hostAddress the IP address of the host to which the route is
1446 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 * @return {@code true} on success, {@code false} on failure
1448 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001449 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001450 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001452 if (mProtectedNetworks.contains(networkType)) {
1453 enforceConnectivityInternalPermission();
1454 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001455
Chad Brubakerc0234532014-02-14 13:24:29 -08001456 InetAddress addr;
1457 try {
1458 addr = InetAddress.getByAddress(hostAddress);
1459 } catch (UnknownHostException e) {
1460 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1461 return false;
1462 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001465 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 return false;
1467 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001468
1469 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1470 if (nai == null) {
1471 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1472 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1473 } else {
1474 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1475 }
1476 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001477 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001478
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001479 DetailedState netState;
1480 synchronized (nai) {
1481 netState = nai.networkInfo.getDetailedState();
1482 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001483
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001484 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001485 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001486 log("requestRouteToHostAddress on down network "
1487 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001488 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001489 }
1490 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001492
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001493 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001494 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001495 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001496 LinkProperties lp;
1497 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001498 synchronized (nai) {
1499 lp = nai.linkProperties;
1500 netId = nai.network.netId;
1501 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001502 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001503 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1504 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001505 } finally {
1506 Binder.restoreCallingIdentity(token);
1507 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001508 }
1509
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001510 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001511 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001512 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001513 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001514 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001515 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001516 if (bestRoute.getGateway().equals(addr)) {
1517 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001518 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001519 } else {
1520 // if we will connect to this through another route, add a direct route
1521 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001522 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001523 }
1524 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001525 if (DBG) log("Adding legacy route " + bestRoute +
1526 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001527 try {
1528 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1529 } catch (Exception e) {
1530 // never crash - catch them all
1531 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001532 return false;
1533 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001534 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 }
1536
dalyk7301aa42018-03-05 12:42:22 -05001537 @VisibleForTesting
1538 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1539 @Override
1540 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1541 String hostname, boolean validated) {
1542 try {
1543 mHandler.sendMessage(mHandler.obtainMessage(
1544 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1545 new PrivateDnsValidationUpdate(netId,
1546 InetAddress.parseNumericAddress(ipAddress),
1547 hostname, validated)));
1548 } catch (IllegalArgumentException e) {
1549 loge("Error parsing ip address in validation event");
1550 }
1551 }
1552 };
1553
1554 @VisibleForTesting
1555 protected void registerNetdEventCallback() {
Chalard Jean4133a122018-06-04 13:33:12 +09001556 final IIpConnectivityMetrics ipConnectivityMetrics =
1557 IIpConnectivityMetrics.Stub.asInterface(
1558 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1559 if (ipConnectivityMetrics == null) {
dalyk7301aa42018-03-05 12:42:22 -05001560 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
Chalard Jean4133a122018-06-04 13:33:12 +09001561 return;
dalyk7301aa42018-03-05 12:42:22 -05001562 }
1563
1564 try {
Chalard Jean4133a122018-06-04 13:33:12 +09001565 ipConnectivityMetrics.addNetdEventCallback(
dalyk7301aa42018-03-05 12:42:22 -05001566 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1567 mNetdEventCallback);
1568 } catch (Exception e) {
1569 loge("Error registering netd callback: " + e);
1570 }
1571 }
1572
Jeff Sharkey75d31892018-01-18 22:01:59 +09001573 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001574 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001575 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001576 // TODO: notify UID when it has requested targeted updates
1577 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001578 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001579 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001580 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001581 if (restrictBackground) {
1582 log("onRestrictBackgroundChanged(true): disabling tethering");
1583 mTethering.untetherAll();
1584 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001585 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001586 };
1587
Robin Lee3b3dd942015-05-12 18:14:58 +01001588 /**
1589 * Require that the caller is either in the same user or has appropriate permission to interact
1590 * across users.
1591 *
1592 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1593 */
1594 private void enforceCrossUserPermission(int userId) {
1595 if (userId == UserHandle.getCallingUserId()) {
1596 // Not a cross-user call.
1597 return;
1598 }
1599 mContext.enforceCallingOrSelfPermission(
1600 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1601 "ConnectivityService");
1602 }
1603
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001604 private void enforceInternetPermission() {
1605 mContext.enforceCallingOrSelfPermission(
1606 android.Manifest.permission.INTERNET,
1607 "ConnectivityService");
1608 }
1609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001611 mContext.enforceCallingOrSelfPermission(
1612 android.Manifest.permission.ACCESS_NETWORK_STATE,
1613 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 }
1615
1616 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001617 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 }
1619
Charles Hea0a87e82017-05-15 17:07:18 +01001620 private void enforceSettingsPermission() {
1621 mContext.enforceCallingOrSelfPermission(
1622 android.Manifest.permission.NETWORK_SETTINGS,
1623 "ConnectivityService");
1624 }
1625
Chalard Jeanb552c462018-02-21 18:43:54 +09001626 private boolean checkSettingsPermission() {
1627 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1628 android.Manifest.permission.NETWORK_SETTINGS);
1629 }
1630
1631 private boolean checkSettingsPermission(int pid, int uid) {
1632 return PERMISSION_GRANTED == mContext.checkPermission(
1633 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1634 }
1635
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001636 private void enforceTetherAccessPermission() {
1637 mContext.enforceCallingOrSelfPermission(
1638 android.Manifest.permission.ACCESS_NETWORK_STATE,
1639 "ConnectivityService");
1640 }
1641
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001642 private void enforceConnectivityInternalPermission() {
1643 mContext.enforceCallingOrSelfPermission(
1644 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1645 "ConnectivityService");
1646 }
1647
Hugo Benichi514da602016-07-19 15:59:27 +09001648 private void enforceConnectivityRestrictedNetworksPermission() {
1649 try {
1650 mContext.enforceCallingOrSelfPermission(
1651 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1652 "ConnectivityService");
1653 return;
1654 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1655 enforceConnectivityInternalPermission();
1656 }
1657
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001658 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001659 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001660 }
1661
Lorenzo Colitti18660282016-07-04 12:55:44 +09001662 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001663 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001664 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001665 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001666 }
1667
1668 private void sendInetConditionBroadcast(NetworkInfo info) {
1669 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1670 }
1671
Wink Saville628b0852011-08-04 15:01:58 -07001672 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001673 synchronized (mVpns) {
1674 if (mLockdownTracker != null) {
1675 info = new NetworkInfo(info);
1676 mLockdownTracker.augmentNetworkInfo(info);
1677 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001678 }
1679
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001680 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001681 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001682 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 if (info.isFailover()) {
1684 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1685 info.setFailover(false);
1686 }
1687 if (info.getReason() != null) {
1688 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1689 }
1690 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001691 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1692 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001694 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001695 return intent;
1696 }
1697
1698 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1699 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1700 }
1701
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001702 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001703 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1704 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1705 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001706 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001707 final long ident = Binder.clearCallingIdentity();
1708 try {
1709 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1710 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1711 } finally {
1712 Binder.restoreCallingIdentity(ident);
1713 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001714 }
1715
Mike Lockwood0f79b542009-08-14 14:18:49 -04001716 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001717 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001718 if (!mSystemReady) {
1719 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001720 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001721 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001722 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001723 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001724 }
1725
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001726 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001727 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001728 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001729 final NetworkInfo ni = intent.getParcelableExtra(
1730 ConnectivityManager.EXTRA_NETWORK_INFO);
1731 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1732 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1733 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001734 } else {
1735 BroadcastOptions opts = BroadcastOptions.makeBasic();
1736 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1737 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001738 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001739 final IBatteryStats bs = BatteryStatsService.getService();
1740 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001741 bs.noteConnectivityChanged(intent.getIntExtra(
1742 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
Chalard Jean4133a122018-06-04 13:33:12 +09001743 ni.getState().toString());
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001744 } catch (RemoteException e) {
1745 }
Chad Brubaker626a33c2018-03-08 10:37:09 -08001746 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001747 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001748 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001749 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001750 } finally {
1751 Binder.restoreCallingIdentity(ident);
1752 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001753 }
1754 }
1755
1756 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001757 loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05001758 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001759
Hugo Benichi20035e02017-04-26 14:53:28 +09001760 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001761 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001762 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001763 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001764 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001765 }
1766 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001767 // load the global proxy at startup
1768 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001769
Robin Lee244ce8e2016-01-05 18:03:46 +00001770 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1771 // for user to unlock device too.
1772 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001773
Erik Klineda4bfa82015-04-30 12:58:40 +09001774 // Configure whether mobile data is always on.
1775 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1776
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001777 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001778
1779 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 }
1781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001783 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001784 *
1785 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001786 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001787 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001788 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1789 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001790
1791 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001792 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001793
Robert Greenwalt7b816022014-04-18 15:25:25 -07001794 if (networkAgent.networkCapabilities.hasTransport(
1795 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001796 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1797 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001798 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001799 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001800 } else if (networkAgent.networkCapabilities.hasTransport(
1801 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001802 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1803 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001804 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001805 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001806 } else {
1807 // do not track any other networks
1808 timeout = 0;
1809 }
1810
Robert Greenwalt7b816022014-04-18 15:25:25 -07001811 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001812 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001813 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001814 } catch (Exception e) {
1815 // You shall not crash!
1816 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001817 }
1818 }
1819 }
1820
1821 /**
1822 * Remove data activity tracking when network disconnects.
1823 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001824 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1825 final String iface = networkAgent.linkProperties.getInterfaceName();
1826 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001827
Robert Greenwalt7b816022014-04-18 15:25:25 -07001828 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1829 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001830 try {
1831 // the call fails silently if no idletimer setup for this interface
1832 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001833 } catch (Exception e) {
1834 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001835 }
1836 }
1837 }
1838
1839 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001840 * Reads the network specific MTU size from reources.
1841 * and set it on it's iface.
1842 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001843 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1844 final String iface = newLp.getInterfaceName();
1845 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001846 if (oldLp == null && mtu == 0) {
1847 // Silently ignore unset MTU value.
1848 return;
1849 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001850 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1851 if (VDBG) log("identical MTU - not setting");
1852 return;
1853 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001854 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001855 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001856 return;
1857 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001858
w1997615afd812014-08-05 15:18:11 -07001859 // Cannot set MTU without interface name
1860 if (TextUtils.isEmpty(iface)) {
1861 loge("Setting MTU size with null iface.");
1862 return;
1863 }
1864
Robert Greenwalt7b816022014-04-18 15:25:25 -07001865 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001866 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001867 mNetd.setMtu(iface, mtu);
1868 } catch (Exception e) {
1869 Slog.e(TAG, "exception in setMtu()" + e);
1870 }
1871 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001872
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001873 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001874 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1875
1876 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001877 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001878 protected MockableSystemProperties getSystemProperties() {
1879 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001880 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001881
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001882 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1883 if (isDefaultNetwork(nai) == false) {
1884 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001885 }
1886
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001887 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1888 String[] values = null;
1889 if (tcpBufferSizes != null) {
1890 values = tcpBufferSizes.split(",");
1891 }
1892
1893 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001894 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001895 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1896 values = tcpBufferSizes.split(",");
1897 }
1898
1899 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1900
1901 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001902 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001903
1904 final String prefix = "/sys/kernel/ipv4/tcp_";
1905 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1906 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1907 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1908 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1909 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1910 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1911 mCurrentTcpBufferSizes = tcpBufferSizes;
1912 } catch (IOException e) {
1913 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001914 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001915
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001916 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001917 Settings.Global.TCP_DEFAULT_INIT_RWND,
1918 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001919 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1920 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001921 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001922 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001923 }
1924
Robert Greenwalt562cc542014-05-15 18:07:26 -07001925 @Override
1926 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001927 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001928 NETWORK_RESTORE_DELAY_PROP_NAME);
1929 if(restoreDefaultNetworkDelayStr != null &&
1930 restoreDefaultNetworkDelayStr.length() != 0) {
1931 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001932 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001933 } catch (NumberFormatException e) {
1934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001936 // if the system property isn't set, use the value for the apn type
1937 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1938
1939 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1940 (mNetConfigs[networkType] != null)) {
1941 ret = mNetConfigs[networkType].restoreTime;
1942 }
1943 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 }
1945
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001946 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1947 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1948 final long DIAG_TIME_MS = 5000;
1949 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1950 // Start gathering diagnostic information.
1951 netDiags.add(new NetworkDiagnostics(
1952 nai.network,
1953 new LinkProperties(nai.linkProperties), // Must be a copy.
1954 DIAG_TIME_MS));
1955 }
1956
1957 for (NetworkDiagnostics netDiag : netDiags) {
1958 pw.println();
1959 netDiag.waitForMeasurements();
1960 netDiag.dump(pw);
1961 }
1962 }
1963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001965 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1966 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001967 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001968
Erik Klinec172c7d2018-05-01 16:51:44 +09001969 if (ArrayUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001970 dumpNetworkDiagnostics(pw);
1971 return;
Erik Klinec172c7d2018-05-01 16:51:44 +09001972 } else if (ArrayUtils.contains(args, TETHERING_ARG)) {
Erik Klineee363c42017-05-29 09:11:03 +09001973 mTethering.dump(fd, pw, args);
1974 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001975 }
Erik Kline379747a2015-06-05 17:47:34 +09001976
Lorenzo Colittie3805462015-06-03 11:18:24 +09001977 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001978 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001979 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001980 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001981 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001982 pw.println();
1983
Paul Jensen85cf78e2015-06-25 13:25:07 -04001984 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001985 pw.print("Active default network: ");
1986 if (defaultNai == null) {
1987 pw.println("none");
1988 } else {
1989 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001991 pw.println();
1992
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001993 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001994 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001995 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1996 pw.println(nai.toString());
1997 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001998 pw.println(String.format(
1999 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2000 nai.numForegroundNetworkRequests(),
2001 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2002 nai.numBackgroundNetworkRequests(),
2003 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002004 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002005 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2006 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002007 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002008 pw.decreaseIndent();
2009 pw.println("Lingered:");
2010 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002011 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002012 pw.decreaseIndent();
2013 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002014 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002015 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002016 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002017
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002018 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002019 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002020 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2021 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002022 }
2023 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002024 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002025
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002026 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002027
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002028 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002029 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002030
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002031 pw.println();
2032 mKeepaliveTracker.dump(pw);
2033
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002034 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002035 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002036
Erik Klinec172c7d2018-05-01 16:51:44 +09002037 if (ArrayUtils.contains(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002038 pw.println();
2039 synchronized (mValidationLogs) {
2040 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002041 for (ValidationLog p : mValidationLogs) {
Chalard Jeanfdd9e2f2018-04-26 16:16:10 +09002042 pw.println(p.mNetwork + " - " + p.mName);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002043 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002044 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002045 pw.decreaseIndent();
2046 }
2047 }
Erik Kline7523eb32015-07-09 18:24:03 +09002048
2049 pw.println();
2050 pw.println("mNetworkRequestInfoLogs (most recent first):");
2051 pw.increaseIndent();
2052 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2053 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002054
2055 pw.println();
2056 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2057 pw.increaseIndent();
2058 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2059 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002060
2061 pw.println();
2062 pw.println("NetTransition WakeLock activity (most recent first):");
2063 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09002064 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2065 pw.println("total releases: " + mTotalWakelockReleases);
2066 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2067 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2068 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2069 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2070 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2071 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002072 mWakelockLogs.reverseDump(fd, pw, args);
2073 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 }
2076
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002077 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002078 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002079 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002080 if (officialNai != null && officialNai.equals(nai)) return true;
2081 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002082 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002083 " - " + nai);
2084 }
2085 return false;
2086 }
2087
Robert Greenwalt42acef32009-08-12 16:08:25 -07002088 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002089 private class NetworkStateTrackerHandler extends Handler {
2090 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002091 super(looper);
2092 }
2093
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002094 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002096 default:
2097 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002098 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002099 handleAsyncChannelHalfConnect(msg);
2100 break;
2101 }
2102 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2103 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2104 if (nai != null) nai.asyncChannel.disconnect();
2105 break;
2106 }
2107 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2108 handleAsyncChannelDisconnected(msg);
2109 break;
2110 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002111 }
2112 return true;
2113 }
2114
2115 private void maybeHandleNetworkAgentMessage(Message msg) {
2116 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2117 if (nai == null) {
2118 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002119 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002120 }
2121 return;
2122 }
2123
2124 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002125 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002126 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2127 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002128 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2129 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002130 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002131 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002132 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002133 break;
2134 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002136 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002137 break;
2138 }
2139 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002140 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002141 updateNetworkInfo(nai, info);
2142 break;
2143 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002144 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002145 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002146 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002147 break;
2148 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002149 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002150 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2151 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002152 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002153 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002154 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002155 break;
2156 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002157 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002158 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2159 break;
2160 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002161 }
2162 }
2163
2164 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2165 switch (msg.what) {
2166 default:
2167 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002168 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002169 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002170 if (nai == null) break;
2171
2172 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2173 final boolean wasValidated = nai.lastValidated;
2174 final boolean wasDefault = isDefaultNetwork(nai);
2175
Erik Klinea24d4592018-01-11 21:07:29 +09002176 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2177
Erik Klinea24d4592018-01-11 21:07:29 +09002178 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002179 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2180 ? " with redirect to " + redirectUrl
2181 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002182 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2183 }
Erik Klinea24d4592018-01-11 21:07:29 +09002184 if (valid != nai.lastValidated) {
2185 if (wasDefault) {
2186 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2187 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002188 }
Erik Klinea24d4592018-01-11 21:07:29 +09002189 final int oldScore = nai.getCurrentScore();
2190 nai.lastValidated = valid;
2191 nai.everValidated |= valid;
2192 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2193 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2194 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2195 }
2196 updateInetCondition(nai);
2197 // Let the NetworkAgent know the state of its network
2198 Bundle redirectUrlBundle = new Bundle();
2199 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2200 nai.asyncChannel.sendMessage(
2201 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2202 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2203 0, redirectUrlBundle);
2204 if (wasValidated && !nai.lastValidated) {
2205 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002206 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002207 break;
2208 }
Paul Jensen869868be2014-05-15 10:33:05 -04002209 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002210 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002211 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002212 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002213 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002214 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002215 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002216 nai.lastCaptivePortalDetected = visible;
2217 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002218 if (nai.lastCaptivePortalDetected &&
2219 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2220 if (DBG) log("Avoiding captive portal network: " + nai.name());
2221 nai.asyncChannel.sendMessage(
2222 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2223 teardownUnneededNetwork(nai);
2224 break;
2225 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002226 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002227 }
2228 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002229 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002230 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002231 if (nai == null) {
2232 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2233 break;
2234 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002235 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002236 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002237 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002238 }
Paul Jensen869868be2014-05-15 10:33:05 -04002239 }
Paul Jensen869868be2014-05-15 10:33:05 -04002240 break;
2241 }
Erik Klinea24d4592018-01-11 21:07:29 +09002242 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002243 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002244 if (nai == null) break;
2245
Erik Kline736353a2018-03-21 07:18:33 -07002246 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002247 break;
2248 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002249 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002250 return true;
2251 }
2252
Calvin Onbe96da12016-10-11 15:10:46 -07002253 private int getCaptivePortalMode() {
2254 return Settings.Global.getInt(mContext.getContentResolver(),
2255 Settings.Global.CAPTIVE_PORTAL_MODE,
2256 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2257 }
2258
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002259 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2260 switch (msg.what) {
2261 default:
2262 return false;
2263 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2264 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2265 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2266 handleLingerComplete(nai);
2267 }
2268 break;
2269 }
2270 }
2271 return true;
2272 }
2273
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002274 @Override
2275 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002276 if (!maybeHandleAsyncChannelMessage(msg) &&
2277 !maybeHandleNetworkMonitorMessage(msg) &&
2278 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002279 maybeHandleNetworkAgentMessage(msg);
2280 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002281 }
2282 }
2283
Erik Kline736353a2018-03-21 07:18:33 -07002284 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2285 return NetworkMonitor.isValidationRequired(
2286 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2287 }
2288
Erik Klinea24d4592018-01-11 21:07:29 +09002289 private void handlePrivateDnsSettingsChanged() {
2290 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2291
2292 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002293 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002294 if (networkRequiresValidation(nai)) {
2295 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2296 }
Erik Klinea24d4592018-01-11 21:07:29 +09002297 }
2298 }
2299
Erik Kline736353a2018-03-21 07:18:33 -07002300 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2301 // Private DNS only ever applies to networks that might provide
2302 // Internet access and therefore also require validation.
2303 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002304
Erik Kline736353a2018-03-21 07:18:33 -07002305 // Notify the NetworkMonitor thread in case it needs to cancel or
2306 // schedule DNS resolutions. If a DNS resolution is required the
2307 // result will be sent back to us.
2308 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2309
2310 // With Private DNS bypass support, we can proceed to update the
2311 // Private DNS config immediately, even if we're in strict mode
2312 // and have not yet resolved the provider name into a set of IPs.
2313 updatePrivateDns(nai, cfg);
2314 }
2315
2316 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2317 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002318 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002319 }
2320
dalyk7301aa42018-03-05 12:42:22 -05002321 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2322 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2323 if (nai == null) {
2324 return;
2325 }
2326 mDnsManager.updatePrivateDnsValidation(update);
2327 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2328 }
2329
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002330 private void updateLingerState(NetworkAgentInfo nai, long now) {
2331 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2332 // 2. If the network was lingering and there are now requests, unlinger it.
2333 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2334 // one lingered request, start lingering.
2335 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002336 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002337 if (DBG) log("Unlingering " + nai.name());
2338 nai.unlinger();
2339 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002340 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002341 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002342 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002343 nai.linger();
2344 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2345 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2346 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002347 }
2348
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349 private void handleAsyncChannelHalfConnect(Message msg) {
2350 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002351 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002352 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2353 if (VDBG) log("NetworkFactory connected");
2354 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002355 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002356 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002357 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002358 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002359 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002360 }
2361 } else {
2362 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002363 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002364 }
2365 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2366 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2367 if (VDBG) log("NetworkAgent connected");
2368 // A network agent has requested a connection. Establish the connection.
2369 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2370 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2371 } else {
2372 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002373 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002374 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002375 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002376 synchronized (mNetworkForNetId) {
2377 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002378 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002379 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002380 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002381 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002382 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002383 }
2384 }
2385 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002386
Chalard Jean49d81082018-05-11 20:19:20 +09002387 // This is a no-op if it's called with a message designating a network that has
2388 // already been destroyed, because its reference will not be found in the relevant
2389 // maps.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002390 private void handleAsyncChannelDisconnected(Message msg) {
2391 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2392 if (nai != null) {
Chalard Jean49d81082018-05-11 20:19:20 +09002393 disconnectAndDestroyNetwork(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002394 } else {
2395 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2396 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002397 }
2398 }
2399
Chalard Jean49d81082018-05-11 20:19:20 +09002400 // Destroys a network, remove references to it from the internal state managed by
2401 // ConnectivityService, free its interfaces and clean up.
2402 // Must be called on the Handler thread.
2403 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
2404 if (DBG) {
2405 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
2406 }
2407 // A network agent has disconnected.
2408 // TODO - if we move the logic to the network agent (have them disconnect
2409 // because they lost all their requests or because their score isn't good)
2410 // then they would disconnect organically, report their new state and then
2411 // disconnect the channel.
2412 if (nai.networkInfo.isConnected()) {
2413 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2414 null, null);
2415 }
2416 final boolean wasDefault = isDefaultNetwork(nai);
2417 if (wasDefault) {
2418 mDefaultInetConditionPublished = 0;
2419 // Log default network disconnection before required book-keeping.
2420 // Let rematchAllNetworksAndRequests() below record a new default network event
2421 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2422 // whose timestamps tell how long it takes to recover a default network.
2423 long now = SystemClock.elapsedRealtime();
2424 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
2425 }
2426 notifyIfacesChangedForNetworkStats();
2427 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2428 // by other networks that are already connected. Perhaps that can be done by
2429 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2430 // of rematchAllNetworksAndRequests
2431 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2432 mKeepaliveTracker.handleStopAllKeepalives(nai,
2433 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2434 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2435 // Disable wakeup packet monitoring for each interface.
2436 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2437 }
2438 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2439 mNetworkAgentInfos.remove(nai.messenger);
2440 nai.maybeStopClat();
2441 synchronized (mNetworkForNetId) {
2442 // Remove the NetworkAgent, but don't mark the netId as
2443 // available until we've told netd to delete it below.
2444 mNetworkForNetId.remove(nai.network.netId);
2445 }
2446 // Remove all previously satisfied requests.
2447 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2448 NetworkRequest request = nai.requestAt(i);
2449 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
2450 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2451 clearNetworkForRequest(request.requestId);
2452 sendUpdatedScoreToFactories(request, 0);
2453 }
2454 }
2455 nai.clearLingerState();
2456 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
2457 removeDataActivityTracking(nai);
2458 notifyLockdownVpn(nai);
2459 ensureNetworkTransitionWakelock(nai.name());
2460 }
2461 mLegacyTypeTracker.remove(nai, wasDefault);
2462 if (!nai.networkCapabilities.hasTransport(TRANSPORT_VPN)) {
2463 updateAllVpnsCapabilities();
2464 }
2465 rematchAllNetworksAndRequests(null, 0);
2466 mLingerMonitor.noteDisconnect(nai);
2467 if (nai.created) {
2468 // Tell netd to clean up the configuration for this network
2469 // (routing rules, DNS, etc).
2470 // This may be slow as it requires a lot of netd shelling out to ip and
2471 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2472 // after we've rematched networks with requests which should make a potential
2473 // fallback network the default or requested a new network from the
2474 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2475 // long time.
2476 try {
2477 mNetd.removeNetwork(nai.network.netId);
2478 } catch (Exception e) {
2479 loge("Exception removing network: " + e);
2480 }
2481 mDnsManager.removeNetwork(nai.network);
2482 }
2483 synchronized (mNetworkForNetId) {
2484 mNetIdInUse.delete(nai.network.netId);
2485 }
2486 }
2487
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002488 // If this method proves to be too slow then we can maintain a separate
2489 // pendingIntent => NetworkRequestInfo map.
2490 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2491 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2492 Intent intent = pendingIntent.getIntent();
2493 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2494 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2495 if (existingPendingIntent != null &&
2496 existingPendingIntent.getIntent().filterEquals(intent)) {
2497 return entry.getValue();
2498 }
2499 }
2500 return null;
2501 }
2502
2503 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2504 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2505
2506 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2507 if (existingRequest != null) { // remove the existing request.
2508 if (DBG) log("Replacing " + existingRequest.request + " with "
2509 + nri.request + " because their intents matched.");
2510 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2511 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002512 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002513 }
2514
Erik Klineda4bfa82015-04-30 12:58:40 +09002515 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002516 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002517 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002518 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002519 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002520 if (nri.request.networkCapabilities.hasSignalStrength() &&
2521 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2522 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002523 }
2524 }
2525 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002526 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002527 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002528 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002529 }
2530 }
2531
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002532 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2533 int callingUid) {
2534 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2535 if (nri != null) {
2536 handleReleaseNetworkRequest(nri.request, callingUid);
2537 }
2538 }
2539
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002540 // Determines whether the network is the best (or could become the best, if it validated), for
2541 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2542 // on the value of reason:
2543 //
2544 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2545 // then it should be torn down.
2546 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2547 // then it should be lingered.
2548 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2549 final int numRequests;
2550 switch (reason) {
2551 case TEARDOWN:
2552 numRequests = nai.numRequestNetworkRequests();
2553 break;
2554 case LINGER:
2555 numRequests = nai.numForegroundNetworkRequests();
2556 break;
2557 default:
2558 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2559 return true;
2560 }
2561
2562 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002563 return false;
2564 }
Paul Jensene0988542015-06-25 15:30:08 -04002565 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002566 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2567 // Background requests don't affect lingering.
2568 continue;
2569 }
2570
Paul Jensene0988542015-06-25 15:30:08 -04002571 // If this Network is already the highest scoring Network for a request, or if
2572 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002573 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002574 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002575 // Note that this catches two important cases:
2576 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2577 // is currently satisfying the request. This is desirable when
2578 // cellular ends up validating but WiFi does not.
2579 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002580 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002581 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002582 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002583 nai.getCurrentScoreAsValidated())) {
2584 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002585 }
2586 }
Paul Jensene0988542015-06-25 15:30:08 -04002587 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002588 }
2589
Erik Klineacdd6392016-07-07 16:50:58 +09002590 private NetworkRequestInfo getNriForAppRequest(
2591 NetworkRequest request, int callingUid, String requestedOperation) {
2592 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2593
Robert Greenwalt9258c642014-03-26 16:47:06 -07002594 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002595 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002596 log(String.format("UID %d attempted to %s for unowned request %s",
2597 callingUid, requestedOperation, nri));
2598 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002599 }
Erik Klineacdd6392016-07-07 16:50:58 +09002600 }
2601
2602 return nri;
2603 }
2604
Erik Kline57faba92015-11-25 12:49:38 +09002605 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002606 if (mNetworkRequests.get(nri.request) == null) {
2607 return;
Erik Kline57faba92015-11-25 12:49:38 +09002608 }
Hugo Benichicd952782017-09-20 11:20:14 +09002609 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002610 return;
2611 }
2612 if (VDBG || (DBG && nri.request.isRequest())) {
2613 log("releasing " + nri.request + " (timeout)");
2614 }
2615 handleRemoveNetworkRequest(nri);
2616 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002617 }
2618
Erik Klineacdd6392016-07-07 16:50:58 +09002619 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002620 final NetworkRequestInfo nri =
2621 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2622 if (nri == null) {
2623 return;
Erik Kline57faba92015-11-25 12:49:38 +09002624 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002625 if (VDBG || (DBG && nri.request.isRequest())) {
2626 log("releasing " + nri.request + " (release request)");
2627 }
2628 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002629 }
Erik Klineacdd6392016-07-07 16:50:58 +09002630
Hugo Benichidba33db2017-03-23 22:40:44 +09002631 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002632 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002633 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002634
Erik Klineacdd6392016-07-07 16:50:58 +09002635 synchronized (mUidToNetworkRequestCount) {
2636 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2637 if (requests < 1) {
2638 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2639 nri.mUid);
2640 } else if (requests == 1) {
2641 mUidToNetworkRequestCount.removeAt(
2642 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2643 } else {
2644 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2645 }
2646 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002647
Erik Klineacdd6392016-07-07 16:50:58 +09002648 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2649 if (nri.request.isRequest()) {
2650 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002651 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002652 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002653 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002654 nai.removeRequest(nri.request.requestId);
2655 if (VDBG) {
2656 log(" Removing from current network " + nai.name() +
2657 ", leaving " + nai.numNetworkRequests() + " requests.");
2658 }
2659 // If there are still lingered requests on this network, don't tear it down,
2660 // but resume lingering instead.
2661 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002662 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002663 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2664 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002665 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002666 wasKept = true;
2667 }
Hugo Benichicd952782017-09-20 11:20:14 +09002668 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002669 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2670 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002671 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002672 }
Erik Klineacdd6392016-07-07 16:50:58 +09002673 }
2674
2675 // TODO: remove this code once we know that the Slog.wtf is never hit.
2676 //
2677 // Find all networks that are satisfying this request and remove the request
2678 // from their request lists.
2679 // TODO - it's my understanding that for a request there is only a single
2680 // network satisfying it, so this loop is wasteful
2681 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2682 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2683 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2684 otherNai.name() + ", but mNetworkAgentInfos says " +
2685 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002686 }
2687 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002688
Erik Klineacdd6392016-07-07 16:50:58 +09002689 // Maintain the illusion. When this request arrived, we might have pretended
2690 // that a network connected to serve it, even though the network was already
2691 // connected. Now that this request has gone away, we might have to pretend
2692 // that the network disconnected. LegacyTypeTracker will generate that
2693 // phantom disconnect for this type.
2694 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2695 boolean doRemove = true;
2696 if (wasKept) {
2697 // check if any of the remaining requests for this network are for the
2698 // same legacy type - if so, don't remove the nai
2699 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2700 NetworkRequest otherRequest = nai.requestAt(i);
2701 if (otherRequest.legacyType == nri.request.legacyType &&
2702 otherRequest.isRequest()) {
2703 if (DBG) log(" still have other legacy request - leaving");
2704 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002705 }
2706 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002707 }
2708
Erik Klineacdd6392016-07-07 16:50:58 +09002709 if (doRemove) {
2710 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002711 }
2712 }
Erik Klineacdd6392016-07-07 16:50:58 +09002713
2714 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2715 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2716 nri.request);
2717 }
2718 } else {
2719 // listens don't have a singular affectedNetwork. Check all networks to see
2720 // if this listen request applies and remove it.
2721 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2722 nai.removeRequest(nri.request.requestId);
2723 if (nri.request.networkCapabilities.hasSignalStrength() &&
2724 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2725 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2726 }
2727 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002728 }
2729 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002730
Lorenzo Colitti18660282016-07-04 12:55:44 +09002731 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002732 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2733 enforceConnectivityInternalPermission();
2734 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002735 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002736 }
2737
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002738 @Override
2739 public void setAvoidUnvalidated(Network network) {
2740 enforceConnectivityInternalPermission();
2741 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2742 }
2743
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002744 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2745 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2746 " accept=" + accept + " always=" + always);
2747
2748 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2749 if (nai == null) {
2750 // Nothing to do.
2751 return;
2752 }
2753
2754 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002755 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002756 return;
2757 }
2758
2759 if (!nai.networkMisc.explicitlySelected) {
2760 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2761 }
2762
2763 if (accept != nai.networkMisc.acceptUnvalidated) {
2764 int oldScore = nai.getCurrentScore();
2765 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002766 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002767 sendUpdatedScoreToFactories(nai);
2768 }
2769
2770 if (always) {
2771 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002772 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002773 }
2774
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002775 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002776 // Tell the NetworkAgent to not automatically reconnect to the network.
2777 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2778 // Teardown the nework.
2779 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002780 }
2781
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002782 }
2783
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002784 private void handleSetAvoidUnvalidated(Network network) {
2785 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2786 if (nai == null || nai.lastValidated) {
2787 // Nothing to do. The network either disconnected or revalidated.
2788 return;
2789 }
2790 if (!nai.avoidUnvalidated) {
2791 int oldScore = nai.getCurrentScore();
2792 nai.avoidUnvalidated = true;
2793 rematchAllNetworksAndRequests(nai, oldScore);
2794 sendUpdatedScoreToFactories(nai);
2795 }
2796 }
2797
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002798 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002799 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002800 mHandler.sendMessageDelayed(
2801 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2802 PROMPT_UNVALIDATED_DELAY_MS);
2803 }
2804
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002805 @Override
2806 public void startCaptivePortalApp(Network network) {
2807 enforceConnectivityInternalPermission();
2808 mHandler.post(() -> {
2809 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2810 if (nai == null) return;
2811 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2812 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2813 });
2814 }
2815
Hugo Benichic8e9e122016-09-14 23:23:08 +00002816 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002817 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002818 }
2819
Erik Kline065ab6e2016-10-02 18:02:14 +09002820 private void rematchForAvoidBadWifiUpdate() {
2821 rematchAllNetworksAndRequests(null, 0);
2822 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2823 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2824 sendUpdatedScoreToFactories(nai);
2825 }
2826 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002827 }
2828
Erik Kline065ab6e2016-10-02 18:02:14 +09002829 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002830 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002831 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002832 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002833 if (!configRestrict) {
2834 pw.println("Bad Wi-Fi avoidance: unrestricted");
2835 return;
2836 }
2837
2838 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2839 pw.increaseIndent();
2840 pw.println("Config restrict: " + configRestrict);
2841
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002842 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002843 String description;
2844 // Can't use a switch statement because strings are legal case labels, but null is not.
2845 if ("0".equals(value)) {
2846 description = "get stuck";
2847 } else if (value == null) {
2848 description = "prompt";
2849 } else if ("1".equals(value)) {
2850 description = "avoid";
2851 } else {
2852 description = value + " (?)";
2853 }
2854 pw.println("User setting: " + description);
2855 pw.println("Network overrides:");
2856 pw.increaseIndent();
2857 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2858 if (nai.avoidUnvalidated) {
2859 pw.println(nai.name());
2860 }
2861 }
2862 pw.decreaseIndent();
2863 pw.decreaseIndent();
2864 }
2865
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002866 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2867 final String action;
2868 switch (type) {
2869 case NO_INTERNET:
2870 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2871 break;
2872 case LOST_INTERNET:
2873 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2874 break;
2875 default:
2876 Slog.wtf(TAG, "Unknown notification type " + type);
2877 return;
2878 }
2879
2880 Intent intent = new Intent(action);
2881 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2882 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2883 intent.setClassName("com.android.settings",
2884 "com.android.settings.wifi.WifiNoInternetDialog");
2885
2886 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2887 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2888 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2889 }
2890
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002891 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002892 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002893 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2894
2895 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2896 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002897 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002898 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002899 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2900 return;
2901 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002902 showValidationNotification(nai, NotificationType.NO_INTERNET);
2903 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002904
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002905 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2906 NetworkCapabilities nc = nai.networkCapabilities;
2907 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002908
Erik Kline065ab6e2016-10-02 18:02:14 +09002909 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002910 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002911 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2912 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002913 }
2914
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002915 @Override
2916 public int getMultipathPreference(Network network) {
2917 enforceAccessPermission();
2918
2919 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002920 if (nai != null && nai.networkCapabilities
2921 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002922 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2923 }
2924
2925 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2926 }
2927
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002928 private class InternalHandler extends Handler {
2929 public InternalHandler(Looper looper) {
2930 super(looper);
2931 }
2932
2933 @Override
2934 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002935 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002936 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002937 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002938 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002939 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002940 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002941 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002942 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002943 break;
2944 }
Jason Monkdecd2952013-10-10 14:02:51 -04002945 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002946 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002947 break;
2948 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002949 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002950 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2951 break;
2952 }
2953 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2954 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002955 break;
2956 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002957 case EVENT_REGISTER_NETWORK_AGENT: {
2958 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2959 break;
2960 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002961 case EVENT_REGISTER_NETWORK_REQUEST:
2962 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002963 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002964 break;
2965 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002966 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2967 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002968 handleRegisterNetworkRequestWithIntent(msg);
2969 break;
2970 }
Erik Kline57faba92015-11-25 12:49:38 +09002971 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2972 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2973 handleTimedOutNetworkRequest(nri);
2974 break;
2975 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002976 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2977 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2978 break;
2979 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002980 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002981 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002982 break;
2983 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002984 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002985 Network network = (Network) msg.obj;
2986 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002987 break;
2988 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002989 case EVENT_SET_AVOID_UNVALIDATED: {
2990 handleSetAvoidUnvalidated((Network) msg.obj);
2991 break;
2992 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002993 case EVENT_PROMPT_UNVALIDATED: {
2994 handlePromptUnvalidated((Network) msg.obj);
2995 break;
2996 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002997 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2998 handleMobileDataAlwaysOn();
2999 break;
3000 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003001 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3002 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3003 mKeepaliveTracker.handleStartKeepalive(msg);
3004 break;
3005 }
3006 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3007 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3008 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3009 int slot = msg.arg1;
3010 int reason = msg.arg2;
3011 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3012 break;
3013 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003014 case EVENT_SYSTEM_READY: {
3015 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3016 nai.networkMonitor.systemReady = true;
3017 }
3018 break;
3019 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003020 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003021 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003022 break;
3023 }
Erik Klinea24d4592018-01-11 21:07:29 +09003024 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3025 handlePrivateDnsSettingsChanged();
3026 break;
dalyk7301aa42018-03-05 12:42:22 -05003027 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3028 handlePrivateDnsValidationUpdate(
3029 (PrivateDnsValidationUpdate) msg.obj);
3030 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
3032 }
3033 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003034
3035 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003036 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003037 public int tether(String iface, String callerPkg) {
3038 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003039 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003040 return mTethering.tether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003041 } else {
3042 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3043 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003044 }
3045
3046 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003047 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003048 public int untether(String iface, String callerPkg) {
3049 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003050
3051 if (isTetheringSupported()) {
Chalard Jean4133a122018-06-04 13:33:12 +09003052 return mTethering.untether(iface);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003053 } else {
3054 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3055 }
3056 }
3057
3058 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003059 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003060 public int getLastTetherError(String iface) {
3061 enforceTetherAccessPermission();
3062
3063 if (isTetheringSupported()) {
3064 return mTethering.getLastTetherError(iface);
3065 } else {
3066 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3067 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003068 }
3069
3070 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003071 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003072 public String[] getTetherableUsbRegexs() {
3073 enforceTetherAccessPermission();
3074 if (isTetheringSupported()) {
3075 return mTethering.getTetherableUsbRegexs();
3076 } else {
3077 return new String[0];
3078 }
3079 }
3080
Lorenzo Colitti18660282016-07-04 12:55:44 +09003081 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003082 public String[] getTetherableWifiRegexs() {
3083 enforceTetherAccessPermission();
3084 if (isTetheringSupported()) {
3085 return mTethering.getTetherableWifiRegexs();
3086 } else {
3087 return new String[0];
3088 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003089 }
3090
Lorenzo Colitti18660282016-07-04 12:55:44 +09003091 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003092 public String[] getTetherableBluetoothRegexs() {
3093 enforceTetherAccessPermission();
3094 if (isTetheringSupported()) {
3095 return mTethering.getTetherableBluetoothRegexs();
3096 } else {
3097 return new String[0];
3098 }
3099 }
3100
Lorenzo Colitti18660282016-07-04 12:55:44 +09003101 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003102 public int setUsbTethering(boolean enable, String callerPkg) {
3103 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003104 if (isTetheringSupported()) {
3105 return mTethering.setUsbTethering(enable);
3106 } else {
3107 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3108 }
3109 }
3110
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003111 // TODO - move iface listing, queries, etc to new module
3112 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003113 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003114 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003115 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003116 return mTethering.getTetherableIfaces();
3117 }
3118
Lorenzo Colitti18660282016-07-04 12:55:44 +09003119 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003120 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003121 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003122 return mTethering.getTetheredIfaces();
3123 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003124
Lorenzo Colitti18660282016-07-04 12:55:44 +09003125 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003126 public String[] getTetheringErroredIfaces() {
3127 enforceTetherAccessPermission();
3128 return mTethering.getErroredIfaces();
3129 }
3130
Lorenzo Colitti18660282016-07-04 12:55:44 +09003131 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003132 public String[] getTetheredDhcpRanges() {
3133 enforceConnectivityInternalPermission();
3134 return mTethering.getTetheredDhcpRanges();
3135 }
3136
Udam Sainic3b640c2017-06-07 12:06:28 -07003137 @Override
3138 public boolean isTetheringSupported(String callerPkg) {
3139 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3140 return isTetheringSupported();
3141 }
3142
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003143 // if ro.tether.denied = true we default to no tethering
3144 // gservices could set the secure setting to 1 though to enable it on a build where it
3145 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07003146 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003147 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3148 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3149 Settings.Global.TETHER_SUPPORTED, defaultVal));
3150 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003151 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003152
3153 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3154 boolean adminUser = false;
3155 final long token = Binder.clearCallingIdentity();
3156 try {
3157 adminUser = mUserManager.isAdminUser();
3158 } finally {
3159 Binder.restoreCallingIdentity(token);
3160 }
3161
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003162 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003163 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003164
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003165 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003166 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3167 String callerPkg) {
3168 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003169 if (!isTetheringSupported()) {
3170 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3171 return;
3172 }
3173 mTethering.startTethering(type, receiver, showProvisioningUi);
3174 }
3175
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003176 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003177 public void stopTethering(int type, String callerPkg) {
3178 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003179 mTethering.stopTethering(type);
3180 }
3181
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003182 // Called when we lose the default network and have no replacement yet.
3183 // This will automatically be cleared after X seconds or a new default network
3184 // becomes CONNECTED, whichever happens first. The timer is started by the
3185 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003186 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003187 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003188 if (mNetTransitionWakeLock.isHeld()) {
3189 return;
3190 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003191 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003192 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3193 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003194 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003195 mWakelockLogs.log("ACQUIRE for " + forWhom);
3196 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3197 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003198 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003199
Hugo Benichi4c31b342017-03-30 23:18:10 +09003200 // Called when we gain a new default network to release the network transition wakelock in a
3201 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3202 // message is cancelled.
3203 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003204 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003205 if (!mNetTransitionWakeLock.isHeld()) {
3206 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003207 }
3208 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003209 // Cancel self timeout on wakelock hold.
3210 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3211 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3212 mHandler.sendMessageDelayed(msg, 1000);
3213 }
3214
3215 // Called when either message of ensureNetworkTransitionWakelock or
3216 // scheduleReleaseNetworkTransitionWakelock is processed.
3217 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3218 String event = eventName(eventId);
3219 synchronized (this) {
3220 if (!mNetTransitionWakeLock.isHeld()) {
3221 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3222 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3223 return;
3224 }
3225 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003226 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3227 mTotalWakelockDurationMs += lockDuration;
3228 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3229 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003230 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003231 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003232 }
3233
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003234 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003235 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003236 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003237 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003238 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003239 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003240 }
3241
Lorenzo Colitti18660282016-07-04 12:55:44 +09003242 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003243 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003244 enforceAccessPermission();
3245 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003246 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003247 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003248 mHandler.sendMessage(
3249 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3250 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003251
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003252 private void handleReportNetworkConnectivity(
3253 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003254 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003255 if (network == null) {
3256 nai = getDefaultNetwork();
3257 } else {
3258 nai = getNetworkAgentInfoForNetwork(network);
3259 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003260 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3261 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3262 return;
3263 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003264 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003265 if (hasConnectivity == nai.lastValidated) {
3266 return;
3267 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003268 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003269 int netid = nai.network.netId;
3270 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003271 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003272 // Validating a network that has not yet connected could result in a call to
3273 // rematchNetworkAndRequests() which is not meant to work on such networks.
3274 if (!nai.everConnected) {
3275 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003276 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003277 LinkProperties lp = getLinkProperties(nai);
3278 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3279 return;
3280 }
Erik Kline736353a2018-03-21 07:18:33 -07003281 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003282 }
3283
Paul Jensencee9b512015-05-06 07:32:40 -04003284 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003285 // this information is already available as a world read/writable jvm property
3286 // so this API change wouldn't have a benifit. It also breaks the passing
3287 // of proxy info to all the JVMs.
3288 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003289 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003290 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003291 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3292 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003293 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003294 }
3295
Lorenzo Colitti18660282016-07-04 12:55:44 +09003296 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003297 public ProxyInfo getProxyForNetwork(Network network) {
3298 if (network == null) return getDefaultProxy();
3299 final ProxyInfo globalProxy = getGlobalProxy();
3300 if (globalProxy != null) return globalProxy;
3301 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3302 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3303 // caller may not have.
3304 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3305 if (nai == null) return null;
3306 synchronized (nai) {
3307 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3308 if (proxyInfo == null) return null;
3309 return new ProxyInfo(proxyInfo);
3310 }
3311 }
3312
Paul Jensene0bef712014-12-10 15:12:18 -05003313 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3314 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3315 // proxy is null then there is no proxy in place).
3316 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3317 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3318 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3319 proxy = null;
3320 }
3321 return proxy;
3322 }
3323
3324 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3325 // better for determining if a new proxy broadcast is necessary:
3326 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3327 // avoid unnecessary broadcasts.
3328 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3329 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3330 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3331 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3332 // all set.
3333 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3334 a = canonicalizeProxyInfo(a);
3335 b = canonicalizeProxyInfo(b);
3336 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3337 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3338 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3339 }
3340
Jason Monk207900c2014-04-25 15:00:09 -04003341 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003342 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003343
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003344 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003345 if (proxyProperties == mGlobalProxy) return;
3346 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3347 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3348
3349 String host = "";
3350 int port = 0;
3351 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003352 String pacFileUrl = "";
3353 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003354 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003355 if (!proxyProperties.isValid()) {
3356 if (DBG)
3357 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3358 return;
3359 }
Jason Monk207900c2014-04-25 15:00:09 -04003360 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003361 host = mGlobalProxy.getHost();
3362 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003363 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003364 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003365 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003366 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003367 } else {
3368 mGlobalProxy = null;
3369 }
3370 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003371 final long token = Binder.clearCallingIdentity();
3372 try {
3373 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3374 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3375 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3376 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003377 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003378 } finally {
3379 Binder.restoreCallingIdentity(token);
3380 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003381
Jason Monkcf0f97a2014-10-02 15:39:38 -04003382 if (mGlobalProxy == null) {
3383 proxyProperties = mDefaultProxy;
3384 }
3385 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003386 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003387 }
3388
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003389 private void loadGlobalProxy() {
3390 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003391 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3392 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3393 String exclList = Settings.Global.getString(res,
3394 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003395 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3396 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003397 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003398 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003399 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003400 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003401 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003402 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003403 if (!proxyProperties.isValid()) {
3404 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3405 return;
3406 }
3407
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003408 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003409 mGlobalProxy = proxyProperties;
3410 }
3411 }
3412 }
3413
Jason Monk207900c2014-04-25 15:00:09 -04003414 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003415 // this information is already available as a world read/writable jvm property
3416 // so this API change wouldn't have a benifit. It also breaks the passing
3417 // of proxy info to all the JVMs.
3418 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003419 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003420 return mGlobalProxy;
3421 }
3422 }
3423
Jason Monk207900c2014-04-25 15:00:09 -04003424 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003425 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003426 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003427 proxy = null;
3428 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003429 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003430 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003431 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003432 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003433 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3434 return;
3435 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003436
3437 // This call could be coming from the PacManager, containing the port of the local
3438 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3439 // global (to get the correct local port), and send a broadcast.
3440 // TODO: Switch PacManager to have its own message to send back rather than
3441 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003442 if ((mGlobalProxy != null) && (proxy != null)
3443 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003444 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3445 mGlobalProxy = proxy;
3446 sendProxyBroadcast(mGlobalProxy);
3447 return;
3448 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003449 mDefaultProxy = proxy;
3450
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003451 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003452 if (!mDefaultProxyDisabled) {
3453 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003454 }
3455 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003456 }
3457
Paul Jensene0bef712014-12-10 15:12:18 -05003458 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3459 // This method gets called when any network changes proxy, but the broadcast only ever contains
3460 // the default proxy (even if it hasn't changed).
3461 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3462 // world where an app might be bound to a non-default network.
Chalard Jean4133a122018-06-04 13:33:12 +09003463 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensene0bef712014-12-10 15:12:18 -05003464 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3465 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3466
3467 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3468 sendProxyBroadcast(getDefaultProxy());
3469 }
3470 }
3471
Robert Greenwalt434203a2010-10-11 16:00:27 -07003472 private void handleDeprecatedGlobalHttpProxy() {
Chalard Jean4133a122018-06-04 13:33:12 +09003473 final String proxy = Settings.Global.getString(mContext.getContentResolver(),
Jeff Sharkey625239a2012-09-26 22:03:49 -07003474 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003475 if (!TextUtils.isEmpty(proxy)) {
3476 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003477 if (data.length == 0) {
3478 return;
3479 }
3480
Chalard Jean4133a122018-06-04 13:33:12 +09003481 final String proxyHost = data[0];
Robert Greenwalt434203a2010-10-11 16:00:27 -07003482 int proxyPort = 8080;
3483 if (data.length > 1) {
3484 try {
3485 proxyPort = Integer.parseInt(data[1]);
3486 } catch (NumberFormatException e) {
3487 return;
3488 }
3489 }
Chalard Jean4133a122018-06-04 13:33:12 +09003490 final ProxyInfo p = new ProxyInfo(proxyHost, proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003491 setGlobalProxy(p);
3492 }
3493 }
3494
Jason Monk207900c2014-04-25 15:00:09 -04003495 private void sendProxyBroadcast(ProxyInfo proxy) {
3496 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003497 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003498 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003499 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003500 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3501 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003502 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003503 final long ident = Binder.clearCallingIdentity();
3504 try {
3505 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3506 } finally {
3507 Binder.restoreCallingIdentity(ident);
3508 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003509 }
3510
3511 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003512 final private HashMap<Uri, Integer> mUriEventMap;
3513 final private Context mContext;
3514 final private Handler mHandler;
3515
3516 SettingsObserver(Context context, Handler handler) {
3517 super(null);
Chalard Jean4133a122018-06-04 13:33:12 +09003518 mUriEventMap = new HashMap<>();
Erik Klineda4bfa82015-04-30 12:58:40 +09003519 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003520 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003521 }
3522
Erik Klineda4bfa82015-04-30 12:58:40 +09003523 void observe(Uri uri, int what) {
3524 mUriEventMap.put(uri, what);
3525 final ContentResolver resolver = mContext.getContentResolver();
3526 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003527 }
3528
3529 @Override
3530 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003531 Slog.wtf(TAG, "Should never be reached.");
3532 }
3533
3534 @Override
3535 public void onChange(boolean selfChange, Uri uri) {
3536 final Integer what = mUriEventMap.get(uri);
3537 if (what != null) {
3538 mHandler.obtainMessage(what.intValue()).sendToTarget();
3539 } else {
3540 loge("No matching event to send for URI=" + uri);
3541 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003542 }
3543 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003544
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003545 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003546 Slog.d(TAG, s);
3547 }
3548
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003549 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003550 Slog.e(TAG, s);
3551 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003552
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003553 private static void loge(String s, Throwable t) {
3554 Slog.e(TAG, s, t);
3555 }
3556
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003557 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003558 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003559 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3560 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3561 *
3562 * @param oldPackage Package name of the application which currently controls VPN, which will
3563 * be replaced. If there is no such application, this should should either be
3564 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3565 * @param newPackage Package name of the application which should gain control of VPN, or
3566 * {@code null} to disable.
3567 * @param userId User for whom to prepare the new VPN.
3568 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003569 * @hide
3570 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003571 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003572 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3573 int userId) {
3574 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003575
Hugo Benichi20035e02017-04-26 14:53:28 +09003576 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003577 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003578 Vpn vpn = mVpns.get(userId);
3579 if (vpn != null) {
3580 return vpn.prepare(oldPackage, newPackage);
3581 } else {
3582 return false;
3583 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003584 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003585 }
3586
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003587 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003588 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3589 * This method is used by system-privileged apps.
3590 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3591 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3592 *
3593 * @param packageName The package for which authorization state should change.
3594 * @param userId User for whom {@code packageName} is installed.
3595 * @param authorized {@code true} if this app should be able to start a VPN connection without
3596 * explicit user approval, {@code false} if not.
3597 *
Jeff Davidson05542602014-08-11 14:07:27 -07003598 * @hide
3599 */
3600 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003601 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3602 enforceCrossUserPermission(userId);
3603
Hugo Benichi20035e02017-04-26 14:53:28 +09003604 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003605 Vpn vpn = mVpns.get(userId);
3606 if (vpn != null) {
3607 vpn.setPackageAuthorization(packageName, authorized);
3608 }
Jeff Davidson05542602014-08-11 14:07:27 -07003609 }
3610 }
3611
3612 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003613 * Configure a TUN interface and return its file descriptor. Parameters
3614 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003615 * and not available in ConnectivityManager. Permissions are checked in
3616 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003617 * @hide
3618 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003619 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003620 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003621 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003622 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003623 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003624 return mVpns.get(user).establish(config);
3625 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003626 }
3627
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003628 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003629 * Start legacy VPN, controlling native daemons as needed. Creates a
3630 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003631 */
3632 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003633 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003634 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003635 final LinkProperties egress = getActiveLinkProperties();
3636 if (egress == null) {
3637 throw new IllegalStateException("Missing active network connection");
3638 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003639 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003640 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003641 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3642 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003643 }
3644
3645 /**
3646 * Return the information of the ongoing legacy VPN. This method is used
3647 * by VpnSettings and not available in ConnectivityManager. Permissions
3648 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003649 */
3650 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003651 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3652 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003653
Hugo Benichi20035e02017-04-26 14:53:28 +09003654 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003655 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003656 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003657 }
3658
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003659 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003660 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3661 * and not available in ConnectivityManager.
3662 */
3663 @Override
3664 public VpnInfo[] getAllVpnInfo() {
3665 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003666 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003667 if (mLockdownEnabled) {
3668 return new VpnInfo[0];
3669 }
3670
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003671 List<VpnInfo> infoList = new ArrayList<>();
3672 for (int i = 0; i < mVpns.size(); i++) {
3673 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3674 if (info != null) {
3675 infoList.add(info);
3676 }
3677 }
3678 return infoList.toArray(new VpnInfo[infoList.size()]);
3679 }
3680 }
3681
3682 /**
3683 * @return VPN information for accounting, or null if we can't retrieve all required
3684 * information, e.g primary underlying iface.
3685 */
3686 @Nullable
3687 private VpnInfo createVpnInfo(Vpn vpn) {
3688 VpnInfo info = vpn.getVpnInfo();
3689 if (info == null) {
3690 return null;
3691 }
3692 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3693 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3694 // the underlyingNetworks list.
3695 if (underlyingNetworks == null) {
3696 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3697 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3698 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3699 }
3700 } else if (underlyingNetworks.length > 0) {
3701 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3702 if (linkProperties != null) {
3703 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3704 }
3705 }
3706 return info.primaryUnderlyingIface == null ? null : info;
3707 }
3708
3709 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003710 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3711 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003712 * Permissions are checked in Vpn class.
3713 * @hide
3714 */
3715 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003716 public VpnConfig getVpnConfig(int userId) {
3717 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003718 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003719 Vpn vpn = mVpns.get(userId);
3720 if (vpn != null) {
3721 return vpn.getVpnConfig();
3722 } else {
3723 return null;
3724 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003725 }
3726 }
3727
Chalard Jean8d538292018-05-18 22:02:56 +09003728 /**
3729 * Ask all VPN objects to recompute and update their capabilities.
3730 *
3731 * When underlying networks change, VPNs may have to update capabilities to reflect things
3732 * like the metered bit, their transports, and so on. This asks the VPN objects to update
3733 * their capabilities, and as this will cause them to send messages to the ConnectivityService
3734 * handler thread through their agent, this is asynchronous. When the capabilities objects
3735 * are computed they will be up-to-date as they are computed synchronously from here and
3736 * this is running on the ConnectivityService thread.
3737 * TODO : Fix this and call updateCapabilities inline to remove out-of-order events.
3738 */
3739 private void updateAllVpnsCapabilities() {
3740 synchronized (mVpns) {
3741 for (int i = 0; i < mVpns.size(); i++) {
3742 final Vpn vpn = mVpns.valueAt(i);
3743 vpn.updateCapabilities();
3744 }
3745 }
3746 }
3747
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003748 @Override
3749 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003750 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3751 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3752 return false;
3753 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003754
Hugo Benichi69744342017-11-27 10:57:16 +09003755 synchronized (mVpns) {
3756 // Tear down existing lockdown if profile was removed
3757 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3758 if (mLockdownEnabled) {
3759 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3760 if (profileTag == null) {
3761 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3762 return false;
3763 }
3764 String profileName = new String(profileTag);
3765 final VpnProfile profile = VpnProfile.decode(
3766 profileName, mKeyStore.get(Credentials.VPN + profileName));
3767 if (profile == null) {
3768 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3769 setLockdownTracker(null);
3770 return true;
3771 }
3772 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003773 Vpn vpn = mVpns.get(user);
3774 if (vpn == null) {
3775 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3776 return false;
3777 }
3778 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003779 } else {
3780 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003781 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003782 }
3783
3784 return true;
3785 }
3786
3787 /**
3788 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3789 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3790 */
Hugo Benichi69744342017-11-27 10:57:16 +09003791 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003792 private void setLockdownTracker(LockdownVpnTracker tracker) {
3793 // Shutdown any existing tracker
3794 final LockdownVpnTracker existing = mLockdownTracker;
3795 mLockdownTracker = null;
3796 if (existing != null) {
3797 existing.shutdown();
3798 }
3799
Robin Leec3736bc2017-03-10 16:19:54 +00003800 if (tracker != null) {
3801 mLockdownTracker = tracker;
3802 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003803 }
3804 }
3805
Hugo Benichi69744342017-11-27 10:57:16 +09003806 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003807 private void throwIfLockdownEnabled() {
3808 if (mLockdownEnabled) {
3809 throw new IllegalStateException("Unavailable in lockdown mode");
3810 }
3811 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003812
Robin Lee244ce8e2016-01-05 18:03:46 +00003813 /**
Robin Lee17e61832016-05-09 13:46:28 +01003814 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3815 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003816 *
Robin Lee17e61832016-05-09 13:46:28 +01003817 * @return {@code true} if the service was started, the service was already connected, or there
3818 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003819 */
Robin Lee17e61832016-05-09 13:46:28 +01003820 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003821 synchronized (mVpns) {
3822 Vpn vpn = mVpns.get(userId);
3823 if (vpn == null) {
3824 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3825 // exists already.
3826 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3827 return false;
3828 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003829
Robin Lee812800c2016-05-13 15:38:08 +01003830 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003831 }
3832 }
3833
3834 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003835 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3836 enforceSettingsPermission();
3837 enforceCrossUserPermission(userId);
3838
3839 synchronized (mVpns) {
3840 Vpn vpn = mVpns.get(userId);
3841 if (vpn == null) {
3842 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3843 return false;
3844 }
3845 return vpn.isAlwaysOnPackageSupported(packageName);
3846 }
3847 }
3848
3849 @Override
Robin Leedc679712016-05-03 13:23:03 +01003850 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003851 enforceConnectivityInternalPermission();
3852 enforceCrossUserPermission(userId);
3853
Robin Lee244ce8e2016-01-05 18:03:46 +00003854 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003855 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3856 if (LockdownVpnTracker.isEnabled()) {
3857 return false;
3858 }
3859
Robin Lee244ce8e2016-01-05 18:03:46 +00003860 Vpn vpn = mVpns.get(userId);
3861 if (vpn == null) {
3862 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3863 return false;
3864 }
Robin Lee17e61832016-05-09 13:46:28 +01003865 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003866 return false;
3867 }
Robin Lee17e61832016-05-09 13:46:28 +01003868 if (!startAlwaysOnVpn(userId)) {
3869 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003870 return false;
3871 }
3872 }
3873 return true;
3874 }
3875
3876 @Override
3877 public String getAlwaysOnVpnPackage(int userId) {
3878 enforceConnectivityInternalPermission();
3879 enforceCrossUserPermission(userId);
3880
3881 synchronized (mVpns) {
3882 Vpn vpn = mVpns.get(userId);
3883 if (vpn == null) {
3884 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3885 return null;
3886 }
3887 return vpn.getAlwaysOnPackage();
3888 }
3889 }
3890
Wink Savilleab9321d2013-06-29 21:10:57 -07003891 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003892 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003893 // TODO: Remove? Any reason to trigger a provisioning check?
3894 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003895 }
3896
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003897 /** Location to an updatable file listing carrier provisioning urls.
3898 * An example:
3899 *
3900 * <?xml version="1.0" encoding="utf-8"?>
3901 * <provisioningUrls>
3902 * <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 -07003903 * </provisioningUrls>
3904 */
3905 private static final String PROVISIONING_URL_PATH =
3906 "/data/misc/radio/provisioning_urls.xml";
3907 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003908
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003909 /** XML tag for root element. */
3910 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3911 /** XML tag for individual url */
3912 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003913 /** XML attribute for mcc */
3914 private static final String ATTR_MCC = "mcc";
3915 /** XML attribute for mnc */
3916 private static final String ATTR_MNC = "mnc";
3917
Paul Jensen434dde82015-06-11 09:43:30 -04003918 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003919 FileReader fileReader = null;
3920 XmlPullParser parser = null;
3921 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003922
3923 try {
3924 fileReader = new FileReader(mProvisioningUrlFile);
3925 parser = Xml.newPullParser();
3926 parser.setInput(fileReader);
3927 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3928
3929 while (true) {
3930 XmlUtils.nextElement(parser);
3931
3932 String element = parser.getName();
3933 if (element == null) break;
3934
Paul Jensen434dde82015-06-11 09:43:30 -04003935 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003936 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3937 try {
3938 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3939 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3940 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3941 parser.next();
3942 if (parser.getEventType() == XmlPullParser.TEXT) {
3943 return parser.getText();
3944 }
3945 }
3946 }
3947 } catch (NumberFormatException e) {
3948 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3949 }
3950 }
3951 }
3952 return null;
3953 } catch (FileNotFoundException e) {
3954 loge("Carrier Provisioning Urls file not found");
3955 } catch (XmlPullParserException e) {
3956 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3957 } catch (IOException e) {
3958 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3959 } finally {
3960 if (fileReader != null) {
3961 try {
3962 fileReader.close();
3963 } catch (IOException e) {}
3964 }
3965 }
3966 return null;
3967 }
3968
Wink Saville42d4f082013-07-20 20:31:59 -07003969 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003970 public String getMobileProvisioningUrl() {
3971 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003972 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003973 if (TextUtils.isEmpty(url)) {
3974 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003975 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003976 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003977 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003978 }
Wink Saville8cf35602013-07-10 23:00:07 -07003979 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003980 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003981 String phoneNumber = mTelephonyManager.getLine1Number();
3982 if (TextUtils.isEmpty(phoneNumber)) {
3983 phoneNumber = "0000000000";
3984 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003985 url = String.format(url,
3986 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3987 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003988 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003989 }
3990
Wink Savilleab9321d2013-06-29 21:10:57 -07003991 return url;
3992 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003993
Wink Saville948282b2013-08-29 08:55:16 -07003994 @Override
3995 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003996 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003997 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003998 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3999 return;
4000 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004001 final long ident = Binder.clearCallingIdentity();
4002 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004003 // Concatenate the range of types onto the range of NetIDs.
4004 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4005 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004006 } finally {
4007 Binder.restoreCallingIdentity(ident);
4008 }
Wink Saville948282b2013-08-29 08:55:16 -07004009 }
Wink Saville7788c612013-08-29 14:57:08 -07004010
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004011 @Override
4012 public void setAirplaneMode(boolean enable) {
4013 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004014 final long ident = Binder.clearCallingIdentity();
4015 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004016 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004017 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004018 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4019 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004020 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004021 } finally {
4022 Binder.restoreCallingIdentity(ident);
4023 }
4024 }
4025
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004026 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004027 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004028 Vpn userVpn = mVpns.get(userId);
4029 if (userVpn != null) {
4030 loge("Starting user already has a VPN");
4031 return;
4032 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004033 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004034 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004035 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4036 updateLockdownVpn();
4037 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004038 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004039 }
4040
4041 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004042 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004043 Vpn userVpn = mVpns.get(userId);
4044 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004045 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004046 return;
4047 }
Robin Lee17e61832016-05-09 13:46:28 +01004048 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004049 mVpns.delete(userId);
4050 }
4051 }
4052
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004053 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004054 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004055 final int vpnsSize = mVpns.size();
4056 for (int i = 0; i < vpnsSize; i++) {
4057 Vpn vpn = mVpns.valueAt(i);
4058 vpn.onUserAdded(userId);
4059 }
4060 }
4061 }
4062
4063 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004064 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004065 final int vpnsSize = mVpns.size();
4066 for (int i = 0; i < vpnsSize; i++) {
4067 Vpn vpn = mVpns.valueAt(i);
4068 vpn.onUserRemoved(userId);
4069 }
4070 }
4071 }
4072
Robin Lee89e7a692016-02-29 14:38:17 +00004073 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004074 synchronized (mVpns) {
4075 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4076 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4077 updateLockdownVpn();
4078 } else {
4079 startAlwaysOnVpn(userId);
4080 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004081 }
4082 }
4083
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004084 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4085 @Override
4086 public void onReceive(Context context, Intent intent) {
4087 final String action = intent.getAction();
4088 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4089 if (userId == UserHandle.USER_NULL) return;
4090
Robin Lee323f29d2016-05-04 16:38:06 +01004091 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004092 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004093 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004094 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004095 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4096 onUserAdded(userId);
4097 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4098 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004099 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4100 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004101 }
4102 }
4103 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004104
Robin Lee95204e02017-01-27 11:59:22 +00004105 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4106 @Override
4107 public void onReceive(Context context, Intent intent) {
4108 // Try creating lockdown tracker, since user present usually means
4109 // unlocked keystore.
4110 updateLockdownVpn();
4111 mContext.unregisterReceiver(this);
4112 }
4113 };
4114
Chalard Jean4133a122018-06-04 13:33:12 +09004115 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = new HashMap<>();
4116 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004117
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004118 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4119 // Map from UID to number of NetworkRequests that UID has filed.
4120 @GuardedBy("mUidToNetworkRequestCount")
4121 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4122
Robert Greenwalta67be032014-05-16 15:49:14 -07004123 private static class NetworkFactoryInfo {
4124 public final String name;
4125 public final Messenger messenger;
4126 public final AsyncChannel asyncChannel;
4127
4128 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4129 this.name = name;
4130 this.messenger = messenger;
4131 this.asyncChannel = asyncChannel;
4132 }
4133 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004134
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004135 private void ensureNetworkRequestHasType(NetworkRequest request) {
4136 if (request.type == NetworkRequest.Type.NONE) {
4137 throw new IllegalArgumentException(
4138 "All NetworkRequests in ConnectivityService must have a type");
4139 }
4140 }
4141
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004142 /**
4143 * Tracks info about the requester.
4144 * Also used to notice when the calling process dies so we can self-expire
4145 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004146 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004147 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004148 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004149 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004150 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004151 final int mPid;
4152 final int mUid;
4153 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004154
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004155 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004156 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004157 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004158 mPendingIntent = pi;
4159 messenger = null;
4160 mBinder = null;
4161 mPid = getCallingPid();
4162 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004163 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004164 }
4165
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004166 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004167 super();
4168 messenger = m;
4169 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004170 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 mBinder = binder;
4172 mPid = getCallingPid();
4173 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004174 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004175 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004176
4177 try {
4178 mBinder.linkToDeath(this, 0);
4179 } catch (RemoteException e) {
4180 binderDied();
4181 }
4182 }
4183
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004184 private void enforceRequestCountLimit() {
4185 synchronized (mUidToNetworkRequestCount) {
4186 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4187 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004188 throw new ServiceSpecificException(
4189 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004190 }
4191 mUidToNetworkRequestCount.put(mUid, networkRequests);
4192 }
4193 }
4194
Robert Greenwalt9258c642014-03-26 16:47:06 -07004195 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004196 if (mBinder != null) {
4197 mBinder.unlinkToDeath(this, 0);
4198 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004199 }
4200
4201 public void binderDied() {
4202 log("ConnectivityService NetworkRequestInfo binderDied(" +
4203 request + ", " + mBinder + ")");
4204 releaseNetworkRequest(request);
4205 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004206
4207 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004208 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004209 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004210 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004211 }
4212
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004213 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4214 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4215 if (badCapability != null) {
4216 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004217 }
4218 }
4219
Chalard Jean6bc18fb2018-04-11 21:09:10 +09004220 // This checks that the passed capabilities either do not request a specific SSID, or the
4221 // calling app has permission to do so.
4222 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4223 int callerPid, int callerUid) {
Chalard Jean7a635d82018-04-16 12:25:22 +09004224 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean6bc18fb2018-04-11 21:09:10 +09004225 throw new SecurityException("Insufficient permissions to request a specific SSID");
4226 }
4227 }
4228
Erik Kline9d598e12015-07-13 16:37:51 +09004229 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Chalard Jean4133a122018-06-04 13:33:12 +09004230 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004231 synchronized (nai) {
4232 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4233 if (nri.request.networkCapabilities.hasSignalStrength() &&
4234 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4235 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4236 }
4237 }
4238 }
Chalard Jean4133a122018-06-04 13:33:12 +09004239 return new ArrayList<>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004240 }
4241
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004242 private void updateSignalStrengthThresholds(
4243 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4244 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004245 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004246 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4247
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004248 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004249 String detail;
4250 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4251 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4252 } else {
4253 detail = reason;
4254 }
4255 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4256 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4257 }
4258
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004259 nai.asyncChannel.sendMessage(
4260 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004261 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004262 }
4263
Etan Cohen859748f2017-04-03 17:42:34 -07004264 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4265 if (nc == null) {
4266 return;
4267 }
4268 NetworkSpecifier ns = nc.getNetworkSpecifier();
4269 if (ns == null) {
4270 return;
4271 }
4272 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4273 ns.assertValidFromUid(Binder.getCallingUid());
4274 }
4275
Robert Greenwalt9258c642014-03-26 16:47:06 -07004276 @Override
4277 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004278 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004279 final NetworkRequest.Type type = (networkCapabilities == null)
4280 ? NetworkRequest.Type.TRACK_DEFAULT
4281 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004282 // If the requested networkCapabilities is null, take them instead from
4283 // the default network request. This allows callers to keep track of
4284 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004285 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Chalard Jeanff8710a2018-04-18 20:18:38 +09004286 networkCapabilities = createDefaultNetworkCapabilitiesForUid(Binder.getCallingUid());
Erik Klinea2d29402016-03-16 15:31:39 +09004287 enforceAccessPermission();
4288 } else {
4289 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4290 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004291 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4292 // of the app when the request is filed, but we never change the request if the app
4293 // changes network state. http://b/29964605
4294 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004295 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004296 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean6bc18fb2018-04-11 21:09:10 +09004297 ensureSufficientPermissionsForRequest(networkCapabilities,
4298 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004299 // Set the UID range for this request to the single UID of the requester, or to an empty
4300 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004301 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4302 // are no visible methods to set the UIDs, an app could use reflection to try and get
4303 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004304 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004305
Etan Cohenba07c8c2017-02-05 10:42:27 -08004306 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004307 throw new IllegalArgumentException("Bad timeout specified");
4308 }
Etan Cohen859748f2017-04-03 17:42:34 -07004309 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004310
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004311 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004312 nextNetworkRequestId(), type);
4313 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004314 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004315
4316 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004317 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004318 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004319 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004320 }
4321 return networkRequest;
4322 }
4323
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004324 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004325 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004326 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004327 } else {
4328 enforceChangePermission();
4329 }
4330 }
4331
fenglub15e72b2015-03-20 11:29:56 -07004332 @Override
fengludb571472015-04-21 17:12:05 -07004333 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004334 enforceAccessPermission();
4335 NetworkAgentInfo nai = null;
4336 if (network == null) {
4337 return false;
4338 }
4339 synchronized (mNetworkForNetId) {
4340 nai = mNetworkForNetId.get(network.netId);
4341 }
4342 if (nai != null) {
4343 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4344 return true;
4345 }
4346 return false;
4347 }
4348
Felipe Lemeee27cab2016-06-20 16:36:29 -07004349 private boolean isSystem(int uid) {
4350 return uid < Process.FIRST_APPLICATION_UID;
4351 }
fenglub15e72b2015-03-20 11:29:56 -07004352
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004353 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004354 final int uid = Binder.getCallingUid();
4355 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004356 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004357 return;
4358 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004359 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4360 // Policy already enforced.
4361 return;
4362 }
4363 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4364 // If UID is restricted, don't allow them to bring up metered APNs.
4365 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004366 }
4367 }
4368
Robert Greenwalt9258c642014-03-26 16:47:06 -07004369 @Override
4370 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4371 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004372 checkNotNull(operation, "PendingIntent cannot be null.");
4373 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4374 enforceNetworkRequestPermissions(networkCapabilities);
4375 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004376 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean6bc18fb2018-04-11 21:09:10 +09004377 ensureSufficientPermissionsForRequest(networkCapabilities,
4378 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004379 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004380 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004381
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004382 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004383 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4384 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004385 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004386 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4387 nri));
4388 return networkRequest;
4389 }
4390
Jeremy Joslin79294842014-12-03 17:15:28 -08004391 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4392 mHandler.sendMessageDelayed(
4393 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4394 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4395 }
4396
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004397 @Override
4398 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004399 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004400 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4401 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004402 }
4403
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004404 // In order to implement the compatibility measure for pre-M apps that call
4405 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4406 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4407 // This ensures it has permission to do so.
4408 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4409 if (nc == null) {
4410 return false;
4411 }
4412 int[] transportTypes = nc.getTransportTypes();
4413 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4414 return false;
4415 }
4416 try {
4417 mContext.enforceCallingOrSelfPermission(
4418 android.Manifest.permission.ACCESS_WIFI_STATE,
4419 "ConnectivityService");
4420 } catch (SecurityException e) {
4421 return false;
4422 }
4423 return true;
4424 }
4425
Robert Greenwalt9258c642014-03-26 16:47:06 -07004426 @Override
4427 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4428 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004429 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4430 enforceAccessPermission();
4431 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004432
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004433 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean6bc18fb2018-04-11 21:09:10 +09004434 ensureSufficientPermissionsForRequest(networkCapabilities,
4435 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004436 restrictRequestUidsForCaller(nc);
Chalard Jean1d738002018-03-20 19:13:57 +09004437 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4438 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4439 // onLost and onAvailable callbacks when networks move in and out of the background.
4440 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4441 // can't request networks.
4442 restrictBackgroundRequestForCaller(nc);
4443 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004444
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004445 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004446 NetworkRequest.Type.LISTEN);
4447 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004448 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004449
4450 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4451 return networkRequest;
4452 }
4453
4454 @Override
4455 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4456 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004457 checkNotNull(operation, "PendingIntent cannot be null.");
4458 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4459 enforceAccessPermission();
4460 }
Etan Cohen859748f2017-04-03 17:42:34 -07004461 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jean6bc18fb2018-04-11 21:09:10 +09004462 ensureSufficientPermissionsForRequest(networkCapabilities,
4463 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004464
Chalard Jeandda156a2018-01-10 21:19:32 +09004465 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004466 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004467
4468 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004469 NetworkRequest.Type.LISTEN);
4470 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004471 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004472
4473 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004474 }
4475
Erik Klineacdd6392016-07-07 16:50:58 +09004476 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004477 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004478 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004479 mHandler.sendMessage(mHandler.obtainMessage(
4480 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004481 }
4482
4483 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004484 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004485 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004486 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4487 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004488 }
4489
Robert Greenwalta67be032014-05-16 15:49:14 -07004490 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004491 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004492 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4493 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4494 }
4495
4496 @Override
4497 public void unregisterNetworkFactory(Messenger messenger) {
4498 enforceConnectivityInternalPermission();
4499 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4500 }
4501
4502 private void handleUnregisterNetworkFactory(Messenger messenger) {
4503 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4504 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004505 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004506 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004507 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004508 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004509 }
4510
Robert Greenwalt7b816022014-04-18 15:25:25 -07004511 /**
4512 * NetworkAgentInfo supporting a request by requestId.
4513 * These have already been vetted (their Capabilities satisfy the request)
4514 * and the are the highest scored network available.
4515 * the are keyed off the Requests requestId.
4516 */
Hugo Benichicd952782017-09-20 11:20:14 +09004517 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4518 @GuardedBy("mNetworkForRequestId")
Chalard Jean4133a122018-06-04 13:33:12 +09004519 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = new SparseArray<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004520
Paul Jensen31a94f42015-02-13 14:18:39 -05004521 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4522 @GuardedBy("mNetworkForNetId")
Chalard Jean4133a122018-06-04 13:33:12 +09004523 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004524 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4525 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4526 // there may not be a strict 1:1 correlation between the two.
4527 @GuardedBy("mNetworkForNetId")
4528 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004529
Robert Greenwalt7b816022014-04-18 15:25:25 -07004530 // NetworkAgentInfo keyed off its connecting messenger
4531 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004532 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Chalard Jean4133a122018-06-04 13:33:12 +09004533 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004534
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004535 @GuardedBy("mBlockedAppUids")
Chalard Jean4133a122018-06-04 13:33:12 +09004536 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004537
Paul Jensen2c311d62014-11-17 12:34:51 -05004538 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004539 private final NetworkRequest mDefaultRequest;
Chalard Jean8d538292018-05-18 22:02:56 +09004540
Erik Klineda4bfa82015-04-30 12:58:40 +09004541 // Request used to optionally keep mobile data active even when higher
4542 // priority networks like Wi-Fi are active.
4543 private final NetworkRequest mDefaultMobileDataRequest;
4544
Hugo Benichicd952782017-09-20 11:20:14 +09004545 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4546 synchronized (mNetworkForRequestId) {
4547 return mNetworkForRequestId.get(requestId);
4548 }
4549 }
4550
4551 private void clearNetworkForRequest(int requestId) {
4552 synchronized (mNetworkForRequestId) {
4553 mNetworkForRequestId.remove(requestId);
4554 }
4555 }
4556
4557 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4558 synchronized (mNetworkForRequestId) {
4559 mNetworkForRequestId.put(requestId, nai);
4560 }
4561 }
4562
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004563 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004564 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004565 }
4566
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004567 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004568 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004569 }
4570
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004571 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4572 return nri.request.requestId == mDefaultRequest.requestId;
4573 }
4574
Paul Jensen31a94f42015-02-13 14:18:39 -05004575 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004576 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004577 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004578 enforceConnectivityInternalPermission();
4579
Rubin Xu1bb5c082017-09-05 18:40:49 +01004580 LinkProperties lp = new LinkProperties(linkProperties);
4581 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004582 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4583 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004584 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004585 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004586 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004587 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004588 // Make sure the network capabilities reflect what the agent info says.
4589 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004590 synchronized (this) {
4591 nai.networkMonitor.systemReady = mSystemReady;
4592 }
Chalard Jeanfdd9e2f2018-04-26 16:16:10 +09004593 final String extraInfo = networkInfo.getExtraInfo();
4594 final String name = TextUtils.isEmpty(extraInfo)
4595 ? nai.networkCapabilities.getSSID() : extraInfo;
4596 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network, name);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004597 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004598 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004599 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004600 }
4601
Erik Klinee5dac902018-03-04 21:01:01 +09004602 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004603 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004604 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004605 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004606 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004607 }
Erik Klinee5dac902018-03-04 21:01:01 +09004608 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4609 NetworkInfo networkInfo = nai.networkInfo;
4610 nai.networkInfo = null;
4611 updateNetworkInfo(nai, networkInfo);
4612 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004613 }
4614
4615 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
Chalard Jean6d89a782018-05-23 09:07:51 +09004616 LinkProperties newLp = new LinkProperties(networkAgent.linkProperties);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004617 int netId = networkAgent.network.netId;
4618
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004619 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4620 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004621 if (networkAgent.clatd != null) {
4622 networkAgent.clatd.fixupLinkProperties(oldLp);
4623 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004624
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004625 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004626 updateMtu(newLp, oldLp);
4627 // TODO - figure out what to do for clat
4628// for (LinkProperties lp : newLp.getStackedLinks()) {
4629// updateMtu(lp, null);
4630// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004631 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004632
Erik Kline94887872016-04-05 13:30:49 +09004633 updateRoutes(newLp, oldLp, netId);
4634 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05004635 // Make sure LinkProperties represents the latest private DNS status.
4636 // This does not need to be done before updateDnses because the
4637 // LinkProperties are not the source of the private DNS configuration.
4638 // updateDnses will fetch the private DNS configuration from DnsManager.
4639 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004640
Hugo Benichib577d652017-06-27 15:13:20 +09004641 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004642 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004643 if (isDefaultNetwork(networkAgent)) {
4644 handleApplyDefaultProxy(newLp.getHttpProxy());
4645 } else {
Chalard Jean4133a122018-06-04 13:33:12 +09004646 updateProxy(newLp, oldLp);
Paul Jensene0bef712014-12-10 15:12:18 -05004647 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004648 // TODO - move this check to cover the whole function
4649 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean6d89a782018-05-23 09:07:51 +09004650 synchronized (networkAgent) {
4651 networkAgent.linkProperties = newLp;
4652 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004653 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004654 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4655 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004656
4657 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004658 }
4659
Joel Scherpelz668370b2017-06-08 15:35:21 +09004660 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004661 // Marks are only available on WiFi interaces. Checking for
4662 // marks on unsupported interfaces is harmless.
4663 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4664 return;
4665 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004666
Joel Scherpelz668370b2017-06-08 15:35:21 +09004667 int mark = mContext.getResources().getInteger(
4668 com.android.internal.R.integer.config_networkWakeupPacketMark);
4669 int mask = mContext.getResources().getInteger(
4670 com.android.internal.R.integer.config_networkWakeupPacketMask);
4671
4672 // Mask/mark of zero will not detect anything interesting.
4673 // Don't install rules unless both values are nonzero.
4674 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004675 return;
4676 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004677
4678 final String prefix = "iface:" + iface;
4679 try {
4680 if (add) {
4681 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4682 } else {
4683 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4684 }
4685 } catch (Exception e) {
4686 loge("Exception modifying wakeup packet monitoring: " + e);
4687 }
4688
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004689 }
4690
4691 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4692 NetworkCapabilities caps) {
Chalard Jean4133a122018-06-04 13:33:12 +09004693 CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fc72f72017-08-22 16:35:52 +01004694 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4695 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004696 for (String iface : interfaceDiff.added) {
4697 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004698 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004699 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004700 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004701 } catch (Exception e) {
4702 loge("Exception adding interface: " + e);
4703 }
4704 }
4705 for (String iface : interfaceDiff.removed) {
4706 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004707 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004708 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004709 mNetd.removeInterfaceFromNetwork(iface, netId);
4710 } catch (Exception e) {
4711 loge("Exception removing interface: " + e);
4712 }
4713 }
4714 }
4715
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004716 /**
4717 * Have netd update routes from oldLp to newLp.
4718 * @return true if routes changed between oldLp and newLp
4719 */
4720 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004721 // Compare the route diff to determine which routes should be added and removed.
4722 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4723 oldLp != null ? oldLp.getAllRoutes() : null,
4724 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004725
4726 // add routes before removing old in case it helps with continuous connectivity
4727
4728 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4729 for (RouteInfo route : routeDiff.added) {
4730 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004731 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004732 try {
4733 mNetd.addRoute(netId, route);
4734 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004735 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4736 loge("Exception in addRoute for non-gateway: " + e);
4737 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004738 }
4739 }
4740 for (RouteInfo route : routeDiff.added) {
4741 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004742 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004743 try {
4744 mNetd.addRoute(netId, route);
4745 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004746 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4747 loge("Exception in addRoute for gateway: " + e);
4748 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004749 }
4750 }
4751
4752 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004753 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004754 try {
4755 mNetd.removeRoute(netId, route);
4756 } catch (Exception e) {
4757 loge("Exception in removeRoute: " + e);
4758 }
4759 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004760 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004761 }
Erik Kline41368502015-06-17 13:19:54 +09004762
Erik Kline94887872016-04-05 13:30:49 +09004763 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4764 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4765 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004766 }
Erik Kline94887872016-04-05 13:30:49 +09004767
Erik Kline1742fe12017-12-13 19:40:49 +09004768 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4769 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4770
Erik Klinea24d4592018-01-11 21:07:29 +09004771 if (DBG) {
4772 final Collection<InetAddress> dnses = newLp.getDnsServers();
4773 log("Setting DNS servers for network " + netId + " to " + dnses);
4774 }
Erik Kline94887872016-04-05 13:30:49 +09004775 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004776 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004777 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004778 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004779 }
Erik Kline4edba012017-04-07 15:29:29 +09004780 }
4781
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004782 private String getNetworkPermission(NetworkCapabilities nc) {
4783 // TODO: make these permission strings AIDL constants instead.
4784 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4785 return NetworkManagementService.PERMISSION_SYSTEM;
4786 }
4787 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4788 return NetworkManagementService.PERMISSION_NETWORK;
4789 }
4790 return null;
4791 }
4792
Paul Jensen3d194ea2015-06-16 14:27:36 -04004793 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004794 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4795 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4796 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004797 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004798 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004799 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004800 if (nai.everConnected &&
4801 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4802 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichibae105a2017-08-16 13:19:04 +09004803 // does not cause any request (that is not a listen) currently matching that agent to
4804 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004805 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichieae7a222017-07-25 11:40:56 +09004806 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004807 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004808 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004809 }
4810
Paul Jensen3d194ea2015-06-16 14:27:36 -04004811 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004812 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004813 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004814 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004815 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004816 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004817 }
Paul Jensene0988542015-06-25 15:30:08 -04004818 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004819 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004820 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004821 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004822 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004823 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004824 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004825 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004826 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004827 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004828 if (nai.isSuspended()) {
4829 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4830 } else {
4831 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4832 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004833
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004834 return newNc;
4835 }
4836
4837 /**
4838 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4839 *
4840 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4841 * capabilities we manage and store in {@code nai}, such as validated status and captive
4842 * portal status)
4843 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4844 * potentially triggers rematches.
4845 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4846 * change.)
4847 *
4848 * @param oldScore score of the network before any of the changes that prompted us
4849 * to call this function.
4850 * @param nai the network having its capabilities updated.
4851 * @param nc the new network capabilities.
4852 */
4853 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4854 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4855
4856 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004857
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004858 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004859 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004860 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004861 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004862 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004863 } catch (RemoteException e) {
4864 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004865 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004866 }
4867
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004868 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004869 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004870 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004871 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004872 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004873
Chalard Jeanf213ca12018-01-16 18:43:05 +09004874 updateUids(nai, prevNc, newNc);
4875
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004876 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004877 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4878 // the change we're processing can't affect any requests, it can only affect the listens
4879 // on this network. We might have been called by rematchNetworkAndRequests when a
4880 // network changed foreground state.
4881 processListenRequests(nai, true);
4882 } else {
4883 // If the requestable capabilities have changed or the score changed, we can't have been
4884 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004885 rematchAllNetworksAndRequests(nai, oldScore);
4886 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004887 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004888
4889 // Report changes that are interesting for network statistics tracking.
4890 if (prevNc != null) {
4891 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004892 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004893 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004894 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004895 if (meteredChanged || roamingChanged) {
4896 notifyIfacesChangedForNetworkStats();
4897 }
4898 }
4899
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004900 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004901 // Tell VPNs about updated capabilities, since they may need to
4902 // bubble those changes through.
Chalard Jean8d538292018-05-18 22:02:56 +09004903 updateAllVpnsCapabilities();
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004904 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004905 }
4906
Chalard Jeanf213ca12018-01-16 18:43:05 +09004907 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4908 NetworkCapabilities newNc) {
4909 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4910 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4911 if (null == prevRanges) prevRanges = new ArraySet<>();
4912 if (null == newRanges) newRanges = new ArraySet<>();
4913 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4914
4915 prevRanges.removeAll(newRanges);
4916 newRanges.removeAll(prevRangesCopy);
4917
4918 try {
4919 if (!newRanges.isEmpty()) {
4920 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4921 newRanges.toArray(addedRangesArray);
4922 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4923 }
4924 if (!prevRanges.isEmpty()) {
4925 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4926 prevRanges.toArray(removedRangesArray);
4927 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4928 }
4929 } catch (Exception e) {
4930 // Never crash!
4931 loge("Exception in updateUids: " + e);
4932 }
4933 }
4934
Hugo Benichief502882017-09-01 01:23:32 +00004935 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07004936 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004937 // Ignore updates for disconnected networks
4938 return;
4939 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004940 // newLp is already a defensive copy.
4941 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004942 if (VDBG) {
4943 log("Update of LinkProperties for " + nai.name() +
4944 "; created=" + nai.created +
4945 "; everConnected=" + nai.everConnected);
4946 }
4947 LinkProperties oldLp = nai.linkProperties;
4948 synchronized (nai) {
4949 nai.linkProperties = newLp;
4950 }
4951 if (nai.everConnected) {
4952 updateLinkProperties(nai, oldLp);
4953 }
4954 }
4955
Paul Jensenc8b9a742014-09-30 15:37:41 -04004956 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004957 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4958 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004959 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004960 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004961 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4962 }
4963 }
4964
Robert Greenwalt7b816022014-04-18 15:25:25 -07004965 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4966 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004967 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004968 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4969 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004970 }
4971 }
4972
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004973 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4974 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004975 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004976 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004977 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4978 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004979 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004980 sendIntent(nri.mPendingIntent, intent);
4981 }
4982 // else not handled
4983 }
4984
4985 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4986 mPendingIntentWakeLock.acquire();
4987 try {
4988 if (DBG) log("Sending " + pendingIntent);
4989 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4990 } catch (PendingIntent.CanceledException e) {
4991 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4992 mPendingIntentWakeLock.release();
4993 releasePendingNetworkRequest(pendingIntent);
4994 }
4995 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4996 }
4997
4998 @Override
4999 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5000 String resultData, Bundle resultExtras) {
5001 if (DBG) log("Finished sending " + pendingIntent);
5002 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005003 // Release with a delay so the receiving client has an opportunity to put in its
5004 // own request.
5005 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005006 }
5007
Chalard Jeanf19db372018-01-26 19:24:40 +09005008 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005009 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005010 if (nri.messenger == null) {
5011 return; // Default request has no msgr
5012 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005013 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005014 // TODO: check if defensive copies of data is needed.
5015 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005016 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005017 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5018 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005019 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005020 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005021 case ConnectivityManager.CALLBACK_AVAILABLE: {
5022 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5023 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5024 break;
5025 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005026 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005027 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005028 break;
5029 }
5030 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005031 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jean6bc18fb2018-04-11 21:09:10 +09005032 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005033 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005034 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005035 break;
5036 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005037 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005038 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005039 break;
5040 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005041 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005042 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005043 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005044 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005045 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005046 String notification = ConnectivityManager.getCallbackName(notificationType);
5047 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005048 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005049 nri.messenger.send(msg);
5050 } catch (RemoteException e) {
5051 // may occur naturally in the race of binder death.
5052 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5053 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005054 }
5055
Hugo Benichidba33db2017-03-23 22:40:44 +09005056 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5057 bundle.putParcelable(t.getClass().getSimpleName(), t);
5058 }
5059
Paul Jensenc8b9a742014-09-30 15:37:41 -04005060 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005061 if (nai.numRequestNetworkRequests() != 0) {
5062 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5063 NetworkRequest nr = nai.requestAt(i);
5064 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005065 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005066 loge("Dead network still had at least " + nr);
5067 break;
5068 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005069 }
5070 nai.asyncChannel.disconnect();
5071 }
5072
Robert Greenwalt7b816022014-04-18 15:25:25 -07005073 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5074 if (oldNetwork == null) {
5075 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5076 return;
5077 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005078 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005079
5080 // If we get here it means that the last linger timeout for this network expired. So there
5081 // must be no other active linger timers, and we must stop lingering.
5082 oldNetwork.clearLingerState();
5083
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005084 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005085 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005086 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005087 } else {
5088 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005089 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5090 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005091 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005092 }
5093
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005094 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005095 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005096 setupDataActivityTracking(newNetwork);
5097 try {
5098 mNetd.setDefaultNetId(newNetwork.network.netId);
5099 } catch (Exception e) {
5100 loge("Exception setting default network :" + e);
5101 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005102
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005103 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005104 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005105 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005106 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005107 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005108 }
5109
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005110 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005111 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5112 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5113 NetworkRequest nr = nri.request;
5114 if (!nr.isListen()) continue;
5115 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5116 nai.removeRequest(nri.request.requestId);
5117 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5118 }
5119 }
5120
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005121 if (capabilitiesChanged) {
5122 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5123 }
5124
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005125 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5126 NetworkRequest nr = nri.request;
5127 if (!nr.isListen()) continue;
5128 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5129 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005130 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005131 }
5132 }
5133 }
5134
Paul Jensen2161a8e2014-09-11 11:00:39 -04005135 // Handles a network appearing or improving its score.
5136 //
5137 // - Evaluates all current NetworkRequests that can be
5138 // satisfied by newNetwork, and reassigns to newNetwork
5139 // any such requests for which newNetwork is the best.
5140 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005141 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005142 // needed. A network is needed if it is the best network for
5143 // one or more NetworkRequests, or if it is a VPN.
5144 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005145 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005146 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005147 //
5148 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5149 // networks that have no chance (i.e. even if validated)
5150 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005151 //
5152 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5153 // it does not remove NetworkRequests that other Networks could better satisfy.
5154 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5155 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5156 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005157 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005158 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005159 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5160 // performed to tear down unvalidated networks that have no chance (i.e. even if
5161 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005162 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005163 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005164 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005165 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005166 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005167 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005168
5169 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5170 final int score = newNetwork.getCurrentScore();
5171
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005172 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005173
Paul Jensen2161a8e2014-09-11 11:00:39 -04005174 // Find and migrate to this Network any NetworkRequests for
5175 // which this network is now the best.
Chalard Jean4133a122018-06-04 13:33:12 +09005176 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<>();
5177 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005178 NetworkCapabilities nc = newNetwork.networkCapabilities;
5179 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005180 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005181 // Process requests in the first pass and listens in the second pass. This allows us to
5182 // change a network's capabilities depending on which requests it has. This is only
5183 // correct if the change in capabilities doesn't affect whether the network satisfies
5184 // requests or not, and doesn't affect the network's score.
5185 if (nri.request.isListen()) continue;
5186
Hugo Benichicd952782017-09-20 11:20:14 +09005187 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005188 final boolean satisfies = newNetwork.satisfies(nri.request);
5189 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005190 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005191 log("Network " + newNetwork.name() + " was already satisfying" +
5192 " request " + nri.request.requestId + ". No change.");
5193 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005194 keep = true;
5195 continue;
5196 }
5197
5198 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005199 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005200 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005201 // next check if it's better than any current network we're using for
5202 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005203 if (VDBG) {
5204 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005205 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005206 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005207 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005208 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005209 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005210 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005211 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005212 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005213 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005214 affectedNetworks.add(currentNetwork);
5215 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005216 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005217 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005218 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005219 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005220 if (!newNetwork.addRequest(nri.request)) {
5221 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5222 }
5223 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005224 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005225 // Tell NetworkFactories about the new score, so they can stop
5226 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005227 // TODO - this could get expensive if we have alot of requests for this
5228 // network. Think about if there is a way to reduce this. Push
5229 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005230 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005231 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005232 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005233 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005234 if (currentNetwork != null) {
5235 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5236 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005237 }
5238 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005239 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005240 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5241 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005242 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005243 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5244 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5245 // This means this code doesn't have to handle the case where "currentNetwork" no
5246 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5247 if (DBG) {
5248 log("Network " + newNetwork.name() + " stopped satisfying" +
5249 " request " + nri.request.requestId);
5250 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005251 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005252 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005253 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005254 sendUpdatedScoreToFactories(nri.request, 0);
5255 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005256 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5257 newNetwork.name() +
5258 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005259 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005260 // TODO: Technically, sending CALLBACK_LOST here is
5261 // incorrect if there is a replacement network currently
5262 // connected that can satisfy nri, which is a request
5263 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005264 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5265 // so this code is only incorrect for a network that loses
5266 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005267 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005268 }
5269 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005270 if (isNewDefault) {
5271 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005272 makeDefault(newNetwork);
5273 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005274 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005275 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005276 // Have a new default network, release the transition wakelock in
5277 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005278 }
5279
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005280 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5281 Slog.wtf(TAG, String.format(
5282 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005283 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005284 }
5285 if (newNetwork.getCurrentScore() != score) {
5286 Slog.wtf(TAG, String.format(
5287 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005288 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005289 }
5290
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005291 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005292 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5293 // If the network went from background to foreground or vice versa, we need to update
5294 // its foreground state. It is safe to do this after rematching the requests because
5295 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5296 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005297 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005298 } else {
5299 processListenRequests(newNetwork, false);
5300 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005301
Paul Jensencf4c2c62015-07-01 14:16:32 -04005302 // do this after the default net is switched, but
5303 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005304 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005305
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005306 // Linger any networks that are no longer needed. This should be done after sending the
5307 // available callback for newNetwork.
5308 for (NetworkAgentInfo nai : affectedNetworks) {
5309 updateLingerState(nai, now);
5310 }
5311 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5312 // does not need to be done in any particular order.
5313 updateLingerState(newNetwork, now);
5314
Paul Jensencf4c2c62015-07-01 14:16:32 -04005315 if (isNewDefault) {
5316 // Maintain the illusion: since the legacy API only
5317 // understands one network at a time, we must pretend
5318 // that the current default network disconnected before
5319 // the new one connected.
5320 if (oldDefaultNetwork != null) {
5321 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5322 oldDefaultNetwork, true);
5323 }
5324 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5325 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5326 notifyLockdownVpn(newNetwork);
5327 }
5328
Robert Greenwalt7b816022014-04-18 15:25:25 -07005329 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005330 // Notify battery stats service about this network, both the normal
5331 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005332 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005333 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005334 final IBatteryStats bs = BatteryStatsService.getService();
5335 final int type = newNetwork.networkInfo.getType();
5336
5337 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5338 bs.noteNetworkInterfaceType(baseIface, type);
5339 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5340 final String stackedIface = stacked.getInterfaceName();
5341 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005342 }
5343 } catch (RemoteException ignored) {
5344 }
5345
Robert Greenwalt152ed372014-12-17 17:19:53 -08005346 // This has to happen after the notifyNetworkCallbacks as that tickles each
5347 // ConnectivityManager instance so that legacy requests correctly bind dns
5348 // requests to this network. The legacy users are listening for this bcast
5349 // and will generally do a dns request so they can ensureRouteToHost and if
5350 // they do that before the callbacks happen they'll use the default network.
5351 //
5352 // TODO: Is there still a race here? We send the broadcast
5353 // after sending the callback, but if the app can receive the
5354 // broadcast before the callback, it might still break.
5355 //
5356 // This *does* introduce a race where if the user uses the new api
5357 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5358 // they may get old info. Reverse this after the old startUsing api is removed.
5359 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005360 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5361 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005362 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005363 // legacy type tracker filters out repeat adds
5364 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5365 }
5366 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005367
5368 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5369 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5370 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5371 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5372 if (newNetwork.isVPN()) {
5373 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5374 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005375 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005376 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5377 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005378 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005379 if (nai.getLingerExpiry() > 0) {
5380 // This network has active linger timers and no requests, but is not
5381 // lingering. Linger it.
5382 //
5383 // One way (the only way?) this can happen if this network is unvalidated
5384 // and became unneeded due to another network improving its score to the
5385 // point where this network will no longer be able to satisfy any requests
5386 // even if it validates.
5387 updateLingerState(nai, now);
5388 } else {
5389 if (DBG) log("Reaping " + nai.name());
5390 teardownUnneededNetwork(nai);
5391 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005392 }
5393 }
5394 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005395 }
5396
Paul Jensen1c7ba022015-06-16 14:27:36 -04005397 /**
5398 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5399 * being disconnected.
5400 * @param changed If only one Network's score or capabilities have been modified since the last
5401 * time this function was called, pass this Network in this argument, otherwise pass
5402 * null.
5403 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5404 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5405 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5406 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5407 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005408 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005409 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005410 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5411 // to avoid the slowness. It is not simply enough to process just "changed", for
5412 // example in the case where "changed"'s score decreases and another network should begin
5413 // satifying a NetworkRequest that "changed" currently satisfies.
5414
5415 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5416 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5417 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005418 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005419 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005420 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005421 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005422 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5423 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5424 // Rematch higher scoring networks first to prevent requests first matching a lower
5425 // scoring network and then a higher scoring network, which could produce multiple
5426 // callbacks and inadvertently unlinger networks.
5427 Arrays.sort(nais);
5428 for (NetworkAgentInfo nai : nais) {
5429 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005430 // Only reap the last time through the loop. Reaping before all rematching
5431 // is complete could incorrectly teardown a network that hasn't yet been
5432 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005433 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005434 : ReapUnvalidatedNetworks.REAP,
5435 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005436 }
5437 }
5438 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005439
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005440 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005441 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005442 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005443 // For now only update icons for default connection.
5444 // TODO: Update WiFi and cellular icons separately. b/17237507
5445 if (!isDefaultNetwork(nai)) return;
5446
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005447 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005448 // Don't repeat publish.
5449 if (newInetCondition == mDefaultInetConditionPublished) return;
5450
5451 mDefaultInetConditionPublished = newInetCondition;
5452 sendInetConditionBroadcast(nai.networkInfo);
5453 }
5454
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005455 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005456 synchronized (mVpns) {
5457 if (mLockdownTracker != null) {
5458 if (nai != null && nai.isVPN()) {
5459 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5460 } else {
5461 mLockdownTracker.onNetworkInfoChanged();
5462 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005463 }
5464 }
5465 }
5466
Robert Greenwalt7b816022014-04-18 15:25:25 -07005467 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005468 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005469 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005470 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005471 synchronized (networkAgent) {
5472 oldInfo = networkAgent.networkInfo;
5473 networkAgent.networkInfo = newInfo;
5474 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005475 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005476
Robert Greenwalt7b816022014-04-18 15:25:25 -07005477 if (DBG) {
5478 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5479 (oldInfo == null ? "null" : oldInfo.getState()) +
5480 " to " + state);
5481 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005482
Robin Lee585e2482016-05-01 23:00:00 +01005483 if (!networkAgent.created
5484 && (state == NetworkInfo.State.CONNECTED
5485 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005486
5487 // A network that has just connected has zero requests and is thus a foreground network.
5488 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5489
Robert Greenwalt7b816022014-04-18 15:25:25 -07005490 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005491 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005492 if (networkAgent.isVPN()) {
5493 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005494 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5495 (networkAgent.networkMisc == null ||
5496 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005497 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005498 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005499 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005500 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005501 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005502 loge("Error creating network " + networkAgent.network.netId + ": "
5503 + e.getMessage());
5504 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005505 }
Paul Jenseneec75412014-08-04 12:21:19 -04005506 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005507 }
5508
5509 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5510 networkAgent.everConnected = true;
5511
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005512 if (networkAgent.linkProperties == null) {
5513 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5514 }
5515
Erik Kline736353a2018-03-21 07:18:33 -07005516 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005517 updateLinkProperties(networkAgent, null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005518
Paul Jensenca8f16a2014-05-09 12:47:55 -04005519 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005520 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005521
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005522 if (networkAgent.isVPN()) {
5523 // Temporarily disable the default proxy (not global).
5524 synchronized (mProxyLock) {
5525 if (!mDefaultProxyDisabled) {
5526 mDefaultProxyDisabled = true;
5527 if (mGlobalProxy == null && mDefaultProxy != null) {
5528 sendProxyBroadcast(null);
5529 }
5530 }
5531 }
5532 // TODO: support proxy per network.
5533 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005534
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005535 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5536 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5537 // capabilities, so it only needs to be done once on initial connect, not every time the
5538 // network's capabilities change. Note that we do this before rematching the network,
5539 // so we could decide to tear it down immediately afterwards. That's fine though - on
5540 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5541 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005542 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005543
Paul Jensen2161a8e2014-09-11 11:00:39 -04005544 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005545 final long now = SystemClock.elapsedRealtime();
5546 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005547
5548 // This has to happen after matching the requests, because callbacks are just requests.
5549 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005550 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005551 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005552 if (networkAgent.isVPN()) {
5553 synchronized (mProxyLock) {
5554 if (mDefaultProxyDisabled) {
5555 mDefaultProxyDisabled = false;
5556 if (mGlobalProxy == null && mDefaultProxy != null) {
5557 sendProxyBroadcast(mDefaultProxy);
5558 }
5559 }
5560 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005561 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005562 }
Chalard Jean49d81082018-05-11 20:19:20 +09005563 disconnectAndDestroyNetwork(networkAgent);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005564 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5565 state == NetworkInfo.State.SUSPENDED) {
5566 // going into or coming out of SUSPEND: rescore and notify
5567 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005568 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005569 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005570 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5571 networkAgent.networkCapabilities);
5572 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5573 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005574 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5575 ConnectivityManager.CALLBACK_SUSPENDED :
5576 ConnectivityManager.CALLBACK_RESUMED));
5577 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005578 }
5579 }
5580
Robert Greenwaltac96c522014-06-03 16:43:57 -07005581 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005582 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005583 if (score < 0) {
5584 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5585 "). Bumping score to min of 0");
5586 score = 0;
5587 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005588
Paul Jensen2161a8e2014-09-11 11:00:39 -04005589 final int oldScore = nai.getCurrentScore();
5590 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005591
Paul Jensen85cf78e2015-06-25 13:25:07 -04005592 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005593
Paul Jensenc8b9a742014-09-30 15:37:41 -04005594 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005595 }
5596
Erik Klinec75d4fa2017-02-15 19:59:17 +09005597 // Notify only this one new request of the current state. Transfer all the
5598 // current state by calling NetworkCapabilities and LinkProperties callbacks
5599 // so that callers can be guaranteed to have as close to atomicity in state
5600 // transfer as can be supported by this current API.
5601 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005602 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005603 if (nri.mPendingIntent != null) {
5604 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5605 // Attempt no subsequent state pushes where intents are involved.
5606 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005607 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005608
5609 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005610 }
5611
Robert Greenwalt8d482522015-06-24 13:23:42 -07005612 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005613 // The NetworkInfo we actually send out has no bearing on the real
5614 // state of affairs. For example, if the default connection is mobile,
5615 // and a request for HIPRI has just gone away, we need to pretend that
5616 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5617 // the state to DISCONNECTED, even though the network is of type MOBILE
5618 // and is still connected.
5619 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5620 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005621 if (state != DetailedState.DISCONNECTED) {
5622 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005623 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005624 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005625 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005626 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5627 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5628 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5629 if (info.isFailover()) {
5630 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5631 nai.networkInfo.setFailover(false);
5632 }
5633 if (info.getReason() != null) {
5634 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5635 }
5636 if (info.getExtraInfo() != null) {
5637 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5638 }
5639 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005640 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005641 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005642 if (newDefaultAgent != null) {
5643 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5644 newDefaultAgent.networkInfo);
5645 } else {
5646 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5647 }
5648 }
5649 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5650 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005651 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005652 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005653 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005654 }
5655 }
5656 }
5657
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005658 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005659 if (VDBG) {
5660 String notification = ConnectivityManager.getCallbackName(notifyType);
5661 log("notifyType " + notification + " for " + networkAgent.name());
5662 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005663 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5664 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005665 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5666 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005667 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5668 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005669 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005670 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005671 } else {
5672 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5673 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005674 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005675 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005676
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005677 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5678 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5679 }
5680
Jeff Sharkey69736342014-12-08 14:50:12 -08005681 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005682 * Returns the list of all interfaces that could be used by network traffic that does not
5683 * explicitly specify a network. This includes the default network, but also all VPNs that are
5684 * currently connected.
5685 *
5686 * Must be called on the handler thread.
5687 */
5688 private Network[] getDefaultNetworks() {
5689 ArrayList<Network> defaultNetworks = new ArrayList<>();
5690 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5691 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5692 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5693 defaultNetworks.add(nai.network);
5694 }
5695 }
5696 return defaultNetworks.toArray(new Network[0]);
5697 }
5698
5699 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005700 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5701 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005702 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005703 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005704 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005705 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005706 } catch (Exception ignored) {
5707 }
5708 }
5709
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005710 @Override
5711 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005712 int user = UserHandle.getUserId(Binder.getCallingUid());
5713 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005714 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005715 return mVpns.get(user).addAddress(address, prefixLength);
5716 }
5717 }
5718
5719 @Override
5720 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005721 int user = UserHandle.getUserId(Binder.getCallingUid());
5722 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005723 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005724 return mVpns.get(user).removeAddress(address, prefixLength);
5725 }
5726 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005727
5728 @Override
5729 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005730 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005731 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005732 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005733 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005734 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005735 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005736 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005737 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005738 }
5739 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005740 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005741
5742 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005743 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005744 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005745 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005746 }
5747
5748 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005749 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5750 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5751 enforceKeepalivePermission();
5752 mKeepaliveTracker.startNattKeepalive(
5753 getNetworkAgentInfoForNetwork(network),
5754 intervalSeconds, messenger, binder,
5755 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5756 }
5757
5758 @Override
5759 public void stopKeepalive(Network network, int slot) {
5760 mHandler.sendMessage(mHandler.obtainMessage(
5761 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5762 }
5763
5764 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005765 public void factoryReset() {
5766 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005767
5768 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5769 return;
5770 }
5771
Robin Lee3b3dd942015-05-12 18:14:58 +01005772 final int userId = UserHandle.getCallingUserId();
5773
Stuart Scottf1fb3972015-04-02 18:00:02 -07005774 // Turn airplane mode off
5775 setAirplaneMode(false);
5776
Stuart Scotte3e314d2015-04-20 14:07:45 -07005777 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5778 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005779 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005780 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005781 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005782 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005783 }
5784
Stuart Scotte3e314d2015-04-20 14:07:45 -07005785 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005786 // Remove always-on package
5787 synchronized (mVpns) {
5788 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5789 if (alwaysOnPackage != null) {
5790 setAlwaysOnVpnPackage(userId, null, false);
5791 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5792 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005793
Hugo Benichi69744342017-11-27 10:57:16 +09005794 // Turn Always-on VPN off
5795 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5796 final long ident = Binder.clearCallingIdentity();
5797 try {
5798 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5799 mLockdownEnabled = false;
5800 setLockdownTracker(null);
5801 } finally {
5802 Binder.restoreCallingIdentity(ident);
5803 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005804 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005805
Hugo Benichi69744342017-11-27 10:57:16 +09005806 // Turn VPN off
5807 VpnConfig vpnConfig = getVpnConfig(userId);
5808 if (vpnConfig != null) {
5809 if (vpnConfig.legacy) {
5810 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5811 } else {
5812 // Prevent this app (packagename = vpnConfig.user) from initiating
5813 // VPN connections in the future without user intervention.
5814 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005815
Hugo Benichi69744342017-11-27 10:57:16 +09005816 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5817 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005818 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005819 }
5820 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005821
5822 Settings.Global.putString(mContext.getContentResolver(),
5823 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005824 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005825
5826 @VisibleForTesting
5827 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5828 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5829 return new NetworkMonitor(context, handler, nai, defaultRequest);
5830 }
Erik Kline48f12f22016-04-14 17:30:59 +09005831
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005832 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005833 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5834 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005835 }
5836
5837 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005838 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5839 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5840 }
5841
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005842 @VisibleForTesting
5843 public boolean hasService(String name) {
5844 return ServiceManager.checkService(name) != null;
5845 }
5846
Hugo Benichi64901e52017-10-19 14:42:40 +09005847 @VisibleForTesting
5848 protected IpConnectivityMetrics.Logger metricsLogger() {
5849 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5850 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005851 }
5852
5853 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005854 int[] transports = nai.networkCapabilities.getTransportTypes();
5855 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005856 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005857
5858 private static boolean toBool(int encodedBoolean) {
5859 return encodedBoolean != 0; // Only 0 means false.
5860 }
5861
5862 private static int encodeBool(boolean b) {
5863 return b ? 1 : 0;
5864 }
mswest462b24f8c2018-03-12 10:34:34 -07005865
5866 @Override
5867 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5868 FileDescriptor err, String[] args, ShellCallback callback,
5869 ResultReceiver resultReceiver) {
5870 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5871 }
5872
5873 private class ShellCmd extends ShellCommand {
5874
5875 @Override
5876 public int onCommand(String cmd) {
5877 if (cmd == null) {
5878 return handleDefaultCommands(cmd);
5879 }
5880 final PrintWriter pw = getOutPrintWriter();
5881 try {
5882 switch (cmd) {
5883 case "airplane-mode":
5884 final String action = getNextArg();
5885 if ("enable".equals(action)) {
5886 setAirplaneMode(true);
5887 return 0;
5888 } else if ("disable".equals(action)) {
5889 setAirplaneMode(false);
5890 return 0;
5891 } else if (action == null) {
5892 final ContentResolver cr = mContext.getContentResolver();
5893 final int enabled = Settings.Global.getInt(cr,
5894 Settings.Global.AIRPLANE_MODE_ON);
5895 pw.println(enabled == 0 ? "disabled" : "enabled");
5896 return 0;
5897 } else {
5898 onHelp();
5899 return -1;
5900 }
5901 default:
5902 return handleDefaultCommands(cmd);
5903 }
5904 } catch (Exception e) {
5905 pw.println(e);
5906 }
5907 return -1;
5908 }
5909
5910 @Override
5911 public void onHelp() {
5912 PrintWriter pw = getOutPrintWriter();
5913 pw.println("Connectivity service commands:");
5914 pw.println(" help");
5915 pw.println(" Print this help text.");
5916 pw.println(" airplane-mode [enable|disable]");
5917 pw.println(" Turn airplane mode on or off.");
5918 pw.println(" airplane-mode");
5919 pw.println(" Get airplane mode.");
5920 }
5921 }
5922}