blob: 76e3131c37e8e1ba2888638e8095e7c559f8004e [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;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900105import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700106import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400107import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700109import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700110import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700111import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700112import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900113import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700114import android.util.LocalLog;
115import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600116import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800117import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700118import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500119import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700120import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700121import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
Wink Savilleab9321d2013-06-29 21:10:57 -0700123import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400124import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400125import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700126import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700127import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700128import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700129import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800130import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700131import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700132import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600133import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700134import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900135import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900136import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700137import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700138import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400139import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900140import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900141import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
dalyk7301aa42018-03-05 12:42:22 -0500142import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900143import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900144import com.android.server.connectivity.KeepaliveTracker;
Charles Hea0a87e82017-05-15 17:07:18 +0100145import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700146import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700147import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600148import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400149import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900150import com.android.server.connectivity.NetworkNotificationManager;
151import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400152import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700153import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800154import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700155import com.android.server.connectivity.Vpn;
Hugo Benichib577d652017-06-27 15:13:20 +0900156import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk7301aa42018-03-05 12:42:22 -0500157import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700158import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700159import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900160import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600161
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700162import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700163
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700164import org.xmlpull.v1.XmlPullParser;
165import org.xmlpull.v1.XmlPullParserException;
166
167import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700169import java.io.FileNotFoundException;
170import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700171import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700173import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700174import java.net.InetAddress;
175import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700176import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700177import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700178import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700179import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700180import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700181import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700182import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700183import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700184import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900185import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600186import java.util.SortedSet;
187import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
189/**
190 * @hide
191 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800192public class ConnectivityService extends IConnectivityManager.Stub
193 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900194 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195
Erik Kline7747fd42017-05-12 16:52:48 +0900196 public static final String DIAG_ARG = "--diag";
197 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900198 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900199
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900200 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700201 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
Jake Hamby786e71a2014-02-06 14:43:50 -0800203 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900204 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700205
Jeff Sharkey899223b2012-08-04 15:24:58 -0700206 // TODO: create better separation between radio types and network types
207
Robert Greenwalt42acef32009-08-12 16:08:25 -0700208 // how long to wait before switching back to a radio's default network
209 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
210 // system property that can override the above value
211 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
212 "android.telephony.apn-restore";
213
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900214 // How long to wait before putting up a "This network doesn't have an Internet connection,
215 // connect anyway?" dialog after the user selects a network that doesn't validate.
216 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
217
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900218 // Default to 30s linger time-out. Modifiable only for testing.
219 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
220 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
221 @VisibleForTesting
222 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
223
Jeremy Joslin79294842014-12-03 17:15:28 -0800224 // How long to delay to removal of a pending intent based request.
225 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
226 private final int mReleasePendingIntentDelayMs;
227
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900228 private MockableSystemProperties mSystemProperties;
229
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800230 private Tethering mTethering;
231
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700232 private final PermissionMonitor mPermissionMonitor;
233
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700234 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700235
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700236 @GuardedBy("mVpns")
237 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700238
Hugo Benichi69744342017-11-27 10:57:16 +0900239 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
240 // a direct call to LockdownVpnTracker.isEnabled().
241 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700242 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900243 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700244 private LockdownVpnTracker mLockdownTracker;
245
Erik Klineda4bfa82015-04-30 12:58:40 +0900246 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700248 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700249 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700252 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700254 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800255 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700256 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900257 private NetworkPolicyManagerInternal mPolicyManagerInternal;
dalyk7301aa42018-03-05 12:42:22 -0500258 private IIpConnectivityMetrics mIpConnectivityMetrics;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700259
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700260 private String mCurrentTcpBufferSizes;
261
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700262 private static final int ENABLED = 1;
263 private static final int DISABLED = 0;
264
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900265 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900266 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
267 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900268
Paul Jensenb10e37f2014-11-25 12:33:08 -0500269 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400270 // Tear down networks that have no chance (e.g. even if validated) of becoming
271 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500272 // all networks have been rematched against all NetworkRequests.
273 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400274 // Don't reap networks. This should be passed when some networks have not yet been
275 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500276 DONT_REAP
277 };
278
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900279 private enum UnneededFor {
280 LINGER, // Determine whether this network is unneeded and should be lingered.
281 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
282 }
283
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700284 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700285 * used internally to change our mobile data enabled flag
286 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700287 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700288
289 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700290 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700291 * from one net to another. Clear happens when we get a new
292 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
293 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700294 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700295 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700296
Robert Greenwalt434203a2010-10-11 16:00:27 -0700297 /**
298 * used internally to reload global proxy settings
299 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700300 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700301
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700302 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400303 * PAC manager has received new port.
304 */
305 private static final int EVENT_PROXY_HAS_CHANGED = 16;
306
Robert Greenwalte049c232014-04-11 15:53:27 -0700307 /**
308 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700309 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700310 */
311 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
312
Robert Greenwalt7b816022014-04-18 15:25:25 -0700313 /**
314 * used internally when registering NetworkAgents
315 * obj = Messenger
316 */
317 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
318
Robert Greenwalt9258c642014-03-26 16:47:06 -0700319 /**
320 * used to add a network request
321 * includes a NetworkRequestInfo
322 */
323 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
324
325 /**
326 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900327 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700328 * cancel it.
329 * includes a NetworkRequestInfo
330 */
331 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
332
333 /**
334 * used to add a network listener - no request
335 * includes a NetworkRequestInfo
336 */
337 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
338
339 /**
340 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400341 * arg1 = UID of caller
342 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700343 */
344 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
345
Robert Greenwalta67be032014-05-16 15:49:14 -0700346 /**
347 * used internally when registering NetworkFactories
348 * obj = Messenger
349 */
350 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
351
Robert Greenwalt27711812014-06-25 16:45:57 -0700352 /**
353 * used internally to expire a wakelock when transitioning
354 * from one net to another. Expire happens when we fail to find
355 * a new network (typically after 1 minute) -
356 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
357 * a replacement network.
358 */
359 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
360
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700361 /**
362 * Used internally to indicate the system is ready.
363 */
364 private static final int EVENT_SYSTEM_READY = 25;
365
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800366 /**
367 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400368 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800369 */
370 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
371
372 /**
373 * used to remove a pending intent and its associated network request.
374 * arg1 = UID of caller
375 * obj = PendingIntent
376 */
377 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
378
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900379 /**
380 * used to specify whether a network should be used even if unvalidated.
381 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
382 * arg2 = whether to remember this choice in the future (1 or 0)
383 * obj = network
384 */
385 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
386
387 /**
388 * used to ask the user to confirm a connection to an unvalidated network.
389 * obj = network
390 */
391 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700392
Erik Klineda4bfa82015-04-30 12:58:40 +0900393 /**
394 * used internally to (re)configure mobile data always-on settings.
395 */
396 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
397
Paul Jensen694f2b82015-06-17 14:15:39 -0400398 /**
399 * used to add a network listener with a pending intent
400 * obj = NetworkRequestInfo
401 */
402 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
403
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900404 /**
405 * used to specify whether a network should not be penalized when it becomes unvalidated.
406 */
407 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
408
409 /**
410 * used to trigger revalidation of a network.
411 */
412 private static final int EVENT_REVALIDATE_NETWORK = 36;
413
Erik Klinea24d4592018-01-11 21:07:29 +0900414 // Handle changes in Private DNS settings.
415 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
416
dalyk7301aa42018-03-05 12:42:22 -0500417 // Handle private DNS validation status updates.
418 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
419
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900420 private static String eventName(int what) {
421 return sMagicDecoderRing.get(what, Integer.toString(what));
422 }
423
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900424 /** Handler thread used for both of the handlers below. */
425 @VisibleForTesting
426 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700427 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700428 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700429 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700430 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900431 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700432
Mike Lockwood0f79b542009-08-14 14:18:49 -0400433 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800434 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400435
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700436 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700437 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800438 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700439
Robert Greenwalt434203a2010-10-11 16:00:27 -0700440 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400441 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700442 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700443 private boolean mDefaultProxyDisabled = false;
444
Robert Greenwalt434203a2010-10-11 16:00:27 -0700445 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400446 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700447
Jason Monk602b2322013-07-03 17:04:33 -0400448 private PacManager mPacManager = null;
449
Erik Klineda4bfa82015-04-30 12:58:40 +0900450 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700451
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400452 private UserManager mUserManager;
453
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700454 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700455 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700456
Robert Greenwalt50393202011-06-21 17:26:14 -0700457 // the set of network types that can only be enabled by system/sig apps
458 List mProtectedNetworks;
459
John Spurlockbf991a82013-06-24 14:20:23 -0400460 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700461
Wink Savilleab9321d2013-06-29 21:10:57 -0700462 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400463
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900464 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900465 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900466 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900467
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700468 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800469 private static final int MIN_NET_ID = 100; // some reserved marks
470 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700471 private int mNextNetId = MIN_NET_ID;
472
Robert Greenwalt34524f02014-05-18 16:22:10 -0700473 // sequence number of NetworkRequests
474 private int mNextNetworkRequestId = 1;
475
Erik Kline7523eb32015-07-09 18:24:03 +0900476 // NetworkRequest activity String log entries.
477 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
478 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
479
Hugo Benichic2ae2872016-07-11 11:05:12 +0900480 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900481 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900482 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
483
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900484 private static final int MAX_WAKELOCK_LOGS = 20;
485 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichic3318aa2017-09-05 13:25:07 +0900486 private int mTotalWakelockAcquisitions = 0;
487 private int mTotalWakelockReleases = 0;
488 private long mTotalWakelockDurationMs = 0;
489 private long mMaxWakelockDurationMs = 0;
490 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900491
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700492 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
493 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400494 private static class ValidationLog {
495 final Network mNetwork;
496 final String mNetworkExtraInfo;
497 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700498
Paul Jensen0808eb82016-06-03 13:51:21 -0400499 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
500 mNetwork = network;
501 mNetworkExtraInfo = networkExtraInfo;
502 mLog = log;
503 }
504 }
505 private final ArrayDeque<ValidationLog> mValidationLogs =
506 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
507
508 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900509 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700510 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
511 mValidationLogs.removeLast();
512 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400513 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700514 }
515 }
516
Hugo Benichif9fdf872016-07-28 17:53:06 +0900517 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900518
Erik Kline065ab6e2016-10-02 18:02:14 +0900519 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900520 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900521
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700522 /**
523 * Implements support for the legacy "one network per network type" model.
524 *
525 * We used to have a static array of NetworkStateTrackers, one for each
526 * network type, but that doesn't work any more now that we can have,
527 * for example, more that one wifi network. This class stores all the
528 * NetworkAgentInfo objects that support a given type, but the legacy
529 * API will only see the first one.
530 *
531 * It serves two main purposes:
532 *
533 * 1. Provide information about "the network for a given type" (since this
534 * API only supports one).
535 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
536 * the first network for a given type changes, or if the default network
537 * changes.
538 */
539 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900540
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900541 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900542 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900543
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700544 /**
545 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
546 * Each list holds references to all NetworkAgentInfos that are used to
547 * satisfy requests for that network type.
548 *
549 * This array is built out at startup such that an unsupported network
550 * doesn't get an ArrayList instance, making this a tristate:
551 * unsupported, supported but not active and active.
552 *
553 * The actual lists are populated when we scan the network types that
554 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900555 *
556 * Threading model:
557 * - addSupportedType() is only called in the constructor
558 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
559 * They are therefore not thread-safe with respect to each other.
560 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
561 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
562 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900564 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700565
566 public LegacyTypeTracker() {
567 mTypeLists = (ArrayList<NetworkAgentInfo>[])
568 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
569 }
570
571 public void addSupportedType(int type) {
572 if (mTypeLists[type] != null) {
573 throw new IllegalStateException(
574 "legacy list for type " + type + "already initialized");
575 }
576 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
577 }
578
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700579 public boolean isTypeSupported(int type) {
580 return isNetworkTypeValid(type) && mTypeLists[type] != null;
581 }
582
583 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900584 synchronized (mTypeLists) {
585 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
586 return mTypeLists[type].get(0);
587 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700588 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900589 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700590 }
591
Robert Greenwalt8d482522015-06-24 13:23:42 -0700592 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900593 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900594 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700595 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900596 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900597 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900598 }
599 }
600
601 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700602 public void add(int type, NetworkAgentInfo nai) {
603 if (!isTypeSupported(type)) {
604 return; // Invalid network type.
605 }
606 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
607
608 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
609 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700610 return;
611 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900612 synchronized (mTypeLists) {
613 list.add(nai);
614 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900615
616 // 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 +0900617 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900618 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700619 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
620 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700621 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700622 }
623
Lorenzo Colittia793a672014-07-31 23:20:17 +0900624 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900625 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900626 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
627 if (list == null || list.isEmpty()) {
628 return;
629 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900631
Hugo Benichi78caa2582016-06-21 09:48:07 +0900632 synchronized (mTypeLists) {
633 if (!list.remove(nai)) {
634 return;
635 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900636 }
637
Robert Greenwalt8d482522015-06-24 13:23:42 -0700638 final DetailedState state = DetailedState.DISCONNECTED;
639
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900640 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700641 maybeLogBroadcast(nai, state, type, wasDefault);
642 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900643 }
644
645 if (!list.isEmpty() && wasFirstNetwork) {
646 if (DBG) log("Other network available for type " + type +
647 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900648 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700649 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
650 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651 }
652 }
653
654 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900655 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
656 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700657 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900658 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700659 }
660 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700661
Robert Greenwalt8d482522015-06-24 13:23:42 -0700662 // send out another legacy broadcast - currently only used for suspend/unsuspend
663 // toggle
664 public void update(NetworkAgentInfo nai) {
665 final boolean isDefault = isDefaultNetwork(nai);
666 final DetailedState state = nai.networkInfo.getDetailedState();
667 for (int type = 0; type < mTypeLists.length; type++) {
668 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700669 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900670 final boolean isFirst = contains && (nai == list.get(0));
671 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700672 maybeLogBroadcast(nai, state, type, isDefault);
673 sendLegacyNetworkBroadcast(nai, state, type);
674 }
675 }
676 }
677
Lorenzo Colittia793a672014-07-31 23:20:17 +0900678 private String naiToString(NetworkAgentInfo nai) {
679 String name = (nai != null) ? nai.name() : "null";
680 String state = (nai.networkInfo != null) ?
681 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
682 "???/???";
683 return name + " " + state;
684 }
685
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700686 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900687 pw.println("mLegacyTypeTracker:");
688 pw.increaseIndent();
689 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700690 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900691 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700692 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900693 pw.println();
694 pw.println("Current state:");
695 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900696 synchronized (mTypeLists) {
697 for (int type = 0; type < mTypeLists.length; type++) {
698 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
699 for (NetworkAgentInfo nai : mTypeLists[type]) {
700 pw.println(type + " " + naiToString(nai));
701 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900702 }
703 }
704 pw.decreaseIndent();
705 pw.decreaseIndent();
706 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700707 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700708 }
709 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
710
Jeff Sharkey899223b2012-08-04 15:24:58 -0700711 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700712 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900713 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
714 }
715
716 @VisibleForTesting
717 protected ConnectivityService(Context context, INetworkManagementService netManager,
718 INetworkStatsService statsService, INetworkPolicyManager policyManager,
719 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800720 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800721
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900722 mSystemProperties = getSystemProperties();
723
Hugo Benichif9fdf872016-07-28 17:53:06 +0900724 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900725 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900726 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900727 mNetworkRequests.put(mDefaultRequest, defaultNRI);
728 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900729
Chalard Jeandda156a2018-01-10 21:19:32 +0900730 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900731 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700732
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900733 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900734 mHandlerThread.start();
735 mHandler = new InternalHandler(mHandlerThread.getLooper());
736 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700737
Jeremy Joslin79294842014-12-03 17:15:28 -0800738 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
739 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
740
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900741 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900742
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700743 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700744 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800745 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700746 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900747 mPolicyManagerInternal = checkNotNull(
748 LocalServices.getService(NetworkPolicyManagerInternal.class),
749 "missing NetworkPolicyManagerInternal");
750
Jeff Sharkey82f85212012-08-24 11:17:25 -0700751 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700752 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700753
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700754 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900755 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700756 } catch (RemoteException e) {
757 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700758 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700759 }
760
761 final PowerManager powerManager = (PowerManager) context.getSystemService(
762 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700763 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
764 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
765 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800766 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700767
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700768 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700769
Wink Saville51f456f2013-04-23 14:26:51 -0700770 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900771 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700772 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700773 String[] naStrings = context.getResources().getStringArray(
774 com.android.internal.R.array.networkAttributes);
775 for (String naString : naStrings) {
776 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700777 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700778 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700779 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800780 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700781 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700782 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700783 }
Wink Saville51f456f2013-04-23 14:26:51 -0700784 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
785 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
786 n.type);
787 continue;
788 }
Wink Saville975c8482011-04-07 14:23:45 -0700789 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800790 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700791 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700792 continue;
793 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700794 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700795
Wink Saville975c8482011-04-07 14:23:45 -0700796 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700797 mNetworksDefined++;
798 } catch(Exception e) {
799 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700800 }
801 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700802
803 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
804 if (mNetConfigs[TYPE_VPN] == null) {
805 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
806 // don't need to add TYPE_VPN to mNetConfigs.
807 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
808 mNetworksDefined++; // used only in the log() statement below.
809 }
810
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900811 // Do the same for Ethernet, since it's often not specified in the configs, although many
812 // devices can use it via USB host adapters.
813 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
814 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
815 mNetworksDefined++;
816 }
817
Wink Saville5e56bc52013-07-29 15:00:57 -0700818 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700819
Robert Greenwalt50393202011-06-21 17:26:14 -0700820 mProtectedNetworks = new ArrayList<Integer>();
821 int[] protectedNetworks = context.getResources().getIntArray(
822 com.android.internal.R.array.config_protectedNetworks);
823 for (int p : protectedNetworks) {
824 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
825 mProtectedNetworks.add(p);
826 } else {
827 if (DBG) loge("Ignoring protectedNetwork " + p);
828 }
829 }
830
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900831 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
832 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700833
Erik Kline47222fc2017-04-30 19:36:15 +0900834 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800835
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700836 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
837
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700838 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700839 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100840 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700841 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700842 intentFilter.addAction(Intent.ACTION_USER_ADDED);
843 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000844 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700845 mContext.registerReceiverAsUser(
846 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000847 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
848 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900849
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700850 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700851 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700852 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700853 } catch (RemoteException e) {
854 loge("Error registering observer :" + e);
855 }
856
Erik Klineda4bfa82015-04-30 12:58:40 +0900857 mSettingsObserver = new SettingsObserver(mContext, mHandler);
858 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800859
John Spurlockbf991a82013-06-24 14:20:23 -0400860 mDataConnectionStats = new DataConnectionStats(mContext);
861 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400862
Jason Monkdecd2952013-10-10 14:02:51 -0400863 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700864
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400865 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900866
867 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900868 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
869 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900870
871 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
872 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
873 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
874 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
875 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
876 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
877 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900878
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900879 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900880 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900881 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900882
883 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900884 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700886
Erik Kline47222fc2017-04-30 19:36:15 +0900887 private Tethering makeTethering() {
888 // TODO: Move other elements into @Overridden getters.
Erik Kline465ff3a2018-03-09 14:18:02 +0900889 final TetheringDependencies deps = new TetheringDependencies() {
890 @Override
891 public boolean isTetheringSupported() {
892 return ConnectivityService.this.isTetheringSupported();
893 }
894 };
Erik Kline47222fc2017-04-30 19:36:15 +0900895 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
896 IoThread.get().getLooper(), new MockableSystemProperties(),
897 deps);
898 }
899
Chalard Jeandda156a2018-01-10 21:19:32 +0900900 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900901 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900902 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900903 netCap.addCapability(NET_CAPABILITY_INTERNET);
904 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900905 if (transportType > -1) {
906 netCap.addTransportType(transportType);
907 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900908 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900909 }
910
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900911 // Used only for testing.
912 // TODO: Delete this and either:
Erik Kline736353a2018-03-21 07:18:33 -0700913 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900914 // changing ContentResolver to make registerContentObserver non-final).
915 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
916 // by subclassing SettingsObserver.
917 @VisibleForTesting
918 void updateMobileDataAlwaysOn() {
919 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
920 }
921
Erik Kline736353a2018-03-21 07:18:33 -0700922 // See FakeSettingsProvider comment above.
923 @VisibleForTesting
924 void updatePrivateDnsSettings() {
925 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
926 }
927
Erik Klineda4bfa82015-04-30 12:58:40 +0900928 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900929 final boolean enable = toBool(Settings.Global.getInt(
930 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900931 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
932 if (enable == isEnabled) {
933 return; // Nothing to do.
934 }
935
936 if (enable) {
937 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900938 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900939 } else {
940 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
941 }
942 }
943
944 private void registerSettingsCallbacks() {
945 // Watch for global HTTP proxy changes.
946 mSettingsObserver.observe(
947 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
948 EVENT_APPLY_GLOBAL_HTTP_PROXY);
949
950 // Watch for whether or not to keep mobile data always on.
951 mSettingsObserver.observe(
952 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
953 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
954 }
955
Erik Klinea24d4592018-01-11 21:07:29 +0900956 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline736353a2018-03-21 07:18:33 -0700957 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
958 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +0900959 }
960 }
961
Robert Greenwalt34524f02014-05-18 16:22:10 -0700962 private synchronized int nextNetworkRequestId() {
963 return mNextNetworkRequestId++;
964 }
965
Paul Jensen67b0b072015-06-10 11:22:17 -0400966 @VisibleForTesting
967 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400968 synchronized (mNetworkForNetId) {
969 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
970 int netId = mNextNetId;
971 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
972 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500973 if (!mNetIdInUse.get(netId)) {
974 mNetIdInUse.put(netId, true);
975 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400976 }
977 }
978 }
979 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700980 }
981
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600982 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800983 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600984 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
985 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800986 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600987 state = nai.getNetworkState();
988 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800989 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600990 final NetworkInfo info = new NetworkInfo(networkType, 0,
991 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800992 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
993 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700994 final NetworkCapabilities capabilities = new NetworkCapabilities();
995 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
996 !info.isRoaming());
997 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600998 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800999 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001000 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001001 return state;
1002 } else {
1003 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001004 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001005 }
1006
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001007 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1008 if (network == null) {
1009 return null;
1010 }
Erik Kline736353a2018-03-21 07:18:33 -07001011 return getNetworkAgentInfoForNetId(network.netId);
1012 }
1013
1014 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 synchronized (mNetworkForNetId) {
Erik Kline736353a2018-03-21 07:18:33 -07001016 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001017 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001018 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001019
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001020 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001021 synchronized (mVpns) {
1022 if (!mLockdownEnabled) {
1023 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001024 Vpn vpn = mVpns.get(user);
1025 if (vpn != null && vpn.appliesToUid(uid)) {
1026 return vpn.getUnderlyingNetworks();
1027 }
1028 }
1029 }
1030 return null;
1031 }
1032
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001033 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001034 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001035
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001036 final Network[] networks = getVpnUnderlyingNetworks(uid);
1037 if (networks != null) {
1038 // getUnderlyingNetworks() returns:
1039 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1040 // empty array => the VPN explicitly said "no default network".
1041 // non-empty array => the VPN specified one or more default networks; we use the
1042 // first one.
1043 if (networks.length > 0) {
1044 nai = getNetworkAgentInfoForNetwork(networks[0]);
1045 } else {
1046 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001047 }
1048 }
1049
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001050 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001051 return nai.getNetworkState();
1052 } else {
1053 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001054 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001055 }
1056
1057 /**
1058 * Check if UID should be blocked from using the network with the given LinkProperties.
1059 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001060 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1061 boolean ignoreBlocked) {
1062 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001063 if (ignoreBlocked) {
1064 return false;
1065 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001066 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001067 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1068 if (isSystem(uid)) {
1069 return false;
1070 }
Robin Lee17e61832016-05-09 13:46:28 +01001071 synchronized (mVpns) {
1072 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1073 if (vpn != null && vpn.isBlockingUid(uid)) {
1074 return true;
1075 }
1076 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001077 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001078 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001079 }
1080
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001081 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001082 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1083 return;
1084 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001085 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001086 synchronized (mBlockedAppUids) {
1087 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001088 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001089 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001090 blocked = false;
1091 } else {
1092 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001093 }
1094 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001095 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1096 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1097 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001098 }
1099
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001100 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001101 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1102 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001103 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001104 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001105 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001106 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1107
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001108 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001109 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001110 }
Hugo Benichi69744342017-11-27 10:57:16 +09001111 synchronized (mVpns) {
1112 if (mLockdownTracker != null) {
1113 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1114 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001115 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001116 }
1117
1118 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 * Return NetworkInfo for the active (i.e., connected) network interface.
1120 * It is assumed that at most one network is active at a time. If more
1121 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001122 * @return the info for the active network, or {@code null} if none is
1123 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001125 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001127 enforceAccessPermission();
1128 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001129 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001130 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001131 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1132 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 }
1134
Paul Jensen31a94f42015-02-13 14:18:39 -05001135 @Override
1136 public Network getActiveNetwork() {
1137 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001138 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001139 }
1140
1141 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001142 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001143 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001144 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001145 }
1146
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001147 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001148 final int user = UserHandle.getUserId(uid);
1149 int vpnNetId = NETID_UNSET;
1150 synchronized (mVpns) {
1151 final Vpn vpn = mVpns.get(user);
1152 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1153 }
1154 NetworkAgentInfo nai;
1155 if (vpnNetId != NETID_UNSET) {
Erik Kline736353a2018-03-21 07:18:33 -07001156 nai = getNetworkAgentInfoForNetId(vpnNetId);
Paul Jensen31a94f42015-02-13 14:18:39 -05001157 if (nai != null) return nai.network;
1158 }
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
1269 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1270
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 Jeanb552c462018-02-21 18:43:54 +09001354 return networkCapabilitiesWithoutUidsUnlessAllowed(nai.networkCapabilities,
1355 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001356 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001357 }
1358 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001359 return null;
1360 }
1361
1362 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001363 public NetworkCapabilities getNetworkCapabilities(Network network) {
1364 enforceAccessPermission();
1365 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1366 }
1367
Chalard Jeanb552c462018-02-21 18:43:54 +09001368 private NetworkCapabilities networkCapabilitiesWithoutUidsUnlessAllowed(
1369 NetworkCapabilities nc, int callerPid, int callerUid) {
1370 if (checkSettingsPermission(callerPid, callerUid)) return new NetworkCapabilities(nc);
Chalard Jeanf19db372018-01-26 19:24:40 +09001371 return new NetworkCapabilities(nc).setUids(null);
1372 }
1373
Chalard Jeanb552c462018-02-21 18:43:54 +09001374 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1375 if (!checkSettingsPermission()) {
1376 nc.setSingleUid(Binder.getCallingUid());
1377 }
1378 }
1379
Chalard Jean1d738002018-03-20 19:13:57 +09001380 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1381 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1382 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1383 }
1384 }
1385
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001386 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001387 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001388 // Require internal since we're handing out IMSI details
1389 enforceConnectivityInternalPermission();
1390
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001391 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001392 for (Network network : getAllNetworks()) {
1393 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1394 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001395 // TODO (b/73321673) : NetworkState contains a copy of the
1396 // NetworkCapabilities, which may contain UIDs of apps to which the
1397 // network applies. Should the UIDs be cleared so as not to leak or
1398 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001399 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001400 }
1401 }
1402 return result.toArray(new NetworkState[result.size()]);
1403 }
1404
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001405 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001406 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001407 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001408 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1409 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1410 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001411 }
1412
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001413 @Override
1414 public boolean isActiveNetworkMetered() {
1415 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001416
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001417 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1418 if (caps != null) {
1419 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1420 } else {
1421 // Always return the most conservative value
1422 return true;
1423 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001424 }
1425
Jeff Sharkey216c1812012-08-05 14:29:23 -07001426 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1427 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001428 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001429 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001430 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001431 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001432 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001433
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001434 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 * Ensure that a network route exists to deliver traffic to the specified
1436 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001437 * @param networkType the type of the network over which traffic to the
1438 * specified host is to be routed
1439 * @param hostAddress the IP address of the host to which the route is
1440 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 * @return {@code true} on success, {@code false} on failure
1442 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001443 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001444 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001446 if (mProtectedNetworks.contains(networkType)) {
1447 enforceConnectivityInternalPermission();
1448 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001449
Chad Brubakerc0234532014-02-14 13:24:29 -08001450 InetAddress addr;
1451 try {
1452 addr = InetAddress.getByAddress(hostAddress);
1453 } catch (UnknownHostException e) {
1454 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1455 return false;
1456 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001459 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 return false;
1461 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001462
1463 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1464 if (nai == null) {
1465 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1466 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1467 } else {
1468 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1469 }
1470 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001471 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001472
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001473 DetailedState netState;
1474 synchronized (nai) {
1475 netState = nai.networkInfo.getDetailedState();
1476 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001477
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001478 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001479 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001480 log("requestRouteToHostAddress on down network "
1481 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001482 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001483 }
1484 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001486
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001487 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001488 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001489 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001490 LinkProperties lp;
1491 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001492 synchronized (nai) {
1493 lp = nai.linkProperties;
1494 netId = nai.network.netId;
1495 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001496 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001497 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1498 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001499 } finally {
1500 Binder.restoreCallingIdentity(token);
1501 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001502 }
1503
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001504 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001505 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001506 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001507 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001508 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001509 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001510 if (bestRoute.getGateway().equals(addr)) {
1511 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001512 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001513 } else {
1514 // if we will connect to this through another route, add a direct route
1515 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001516 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001517 }
1518 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001519 if (DBG) log("Adding legacy route " + bestRoute +
1520 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001521 try {
1522 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1523 } catch (Exception e) {
1524 // never crash - catch them all
1525 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001526 return false;
1527 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001528 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 }
1530
dalyk7301aa42018-03-05 12:42:22 -05001531 @VisibleForTesting
1532 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1533 @Override
1534 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1535 String hostname, boolean validated) {
1536 try {
1537 mHandler.sendMessage(mHandler.obtainMessage(
1538 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1539 new PrivateDnsValidationUpdate(netId,
1540 InetAddress.parseNumericAddress(ipAddress),
1541 hostname, validated)));
1542 } catch (IllegalArgumentException e) {
1543 loge("Error parsing ip address in validation event");
1544 }
1545 }
1546 };
1547
1548 @VisibleForTesting
1549 protected void registerNetdEventCallback() {
1550 mIpConnectivityMetrics =
1551 (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1552 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1553 if (mIpConnectivityMetrics == null) {
1554 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
1555 }
1556
1557 try {
1558 mIpConnectivityMetrics.addNetdEventCallback(
1559 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1560 mNetdEventCallback);
1561 } catch (Exception e) {
1562 loge("Error registering netd callback: " + e);
1563 }
1564 }
1565
Jeff Sharkey75d31892018-01-18 22:01:59 +09001566 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001567 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001568 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001569 // TODO: notify UID when it has requested targeted updates
1570 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001571 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001572 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001573 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001574 if (restrictBackground) {
1575 log("onRestrictBackgroundChanged(true): disabling tethering");
1576 mTethering.untetherAll();
1577 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001578 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001579 };
1580
Robin Lee3b3dd942015-05-12 18:14:58 +01001581 /**
1582 * Require that the caller is either in the same user or has appropriate permission to interact
1583 * across users.
1584 *
1585 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1586 */
1587 private void enforceCrossUserPermission(int userId) {
1588 if (userId == UserHandle.getCallingUserId()) {
1589 // Not a cross-user call.
1590 return;
1591 }
1592 mContext.enforceCallingOrSelfPermission(
1593 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1594 "ConnectivityService");
1595 }
1596
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001597 private void enforceInternetPermission() {
1598 mContext.enforceCallingOrSelfPermission(
1599 android.Manifest.permission.INTERNET,
1600 "ConnectivityService");
1601 }
1602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001604 mContext.enforceCallingOrSelfPermission(
1605 android.Manifest.permission.ACCESS_NETWORK_STATE,
1606 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
1608
1609 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001610 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612
Charles Hea0a87e82017-05-15 17:07:18 +01001613 private void enforceSettingsPermission() {
1614 mContext.enforceCallingOrSelfPermission(
1615 android.Manifest.permission.NETWORK_SETTINGS,
1616 "ConnectivityService");
1617 }
1618
Chalard Jeanb552c462018-02-21 18:43:54 +09001619 private boolean checkSettingsPermission() {
1620 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1621 android.Manifest.permission.NETWORK_SETTINGS);
1622 }
1623
1624 private boolean checkSettingsPermission(int pid, int uid) {
1625 return PERMISSION_GRANTED == mContext.checkPermission(
1626 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1627 }
1628
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001629 private void enforceTetherAccessPermission() {
1630 mContext.enforceCallingOrSelfPermission(
1631 android.Manifest.permission.ACCESS_NETWORK_STATE,
1632 "ConnectivityService");
1633 }
1634
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001635 private void enforceConnectivityInternalPermission() {
1636 mContext.enforceCallingOrSelfPermission(
1637 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1638 "ConnectivityService");
1639 }
1640
Hugo Benichi514da602016-07-19 15:59:27 +09001641 private void enforceConnectivityRestrictedNetworksPermission() {
1642 try {
1643 mContext.enforceCallingOrSelfPermission(
1644 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1645 "ConnectivityService");
1646 return;
1647 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1648 enforceConnectivityInternalPermission();
1649 }
1650
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001651 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001652 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001653 }
1654
Lorenzo Colitti18660282016-07-04 12:55:44 +09001655 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001656 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001657 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001658 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001659 }
1660
1661 private void sendInetConditionBroadcast(NetworkInfo info) {
1662 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1663 }
1664
Wink Saville628b0852011-08-04 15:01:58 -07001665 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001666 synchronized (mVpns) {
1667 if (mLockdownTracker != null) {
1668 info = new NetworkInfo(info);
1669 mLockdownTracker.augmentNetworkInfo(info);
1670 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001671 }
1672
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001673 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001674 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001675 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 if (info.isFailover()) {
1677 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1678 info.setFailover(false);
1679 }
1680 if (info.getReason() != null) {
1681 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1682 }
1683 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001684 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1685 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001687 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001688 return intent;
1689 }
1690
1691 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1692 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1693 }
1694
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001695 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001696 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1697 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1698 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001699 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001700 final long ident = Binder.clearCallingIdentity();
1701 try {
1702 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1703 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1704 } finally {
1705 Binder.restoreCallingIdentity(ident);
1706 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001707 }
1708
Mike Lockwood0f79b542009-08-14 14:18:49 -04001709 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001710 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001711 if (!mSystemReady) {
1712 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001713 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001714 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001715 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001716 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001717 }
1718
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001719 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001720 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001721 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001722 final NetworkInfo ni = intent.getParcelableExtra(
1723 ConnectivityManager.EXTRA_NETWORK_INFO);
1724 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1725 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1726 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001727 } else {
1728 BroadcastOptions opts = BroadcastOptions.makeBasic();
1729 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1730 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001731 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001732 final IBatteryStats bs = BatteryStatsService.getService();
1733 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001734 bs.noteConnectivityChanged(intent.getIntExtra(
1735 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1736 ni != null ? ni.getState().toString() : "?");
1737 } catch (RemoteException e) {
1738 }
1739 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001740 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001741 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001742 } finally {
1743 Binder.restoreCallingIdentity(ident);
1744 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001745 }
1746 }
1747
1748 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001749 loadGlobalProxy();
dalyk7301aa42018-03-05 12:42:22 -05001750 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001751
Hugo Benichi20035e02017-04-26 14:53:28 +09001752 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001753 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001754 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001755 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001756 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001757 }
1758 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001759 // load the global proxy at startup
1760 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001761
Robin Lee244ce8e2016-01-05 18:03:46 +00001762 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1763 // for user to unlock device too.
1764 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001765
Erik Klineda4bfa82015-04-30 12:58:40 +09001766 // Configure whether mobile data is always on.
1767 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1768
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001769 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001770
1771 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 }
1773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001775 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001776 *
1777 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001778 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001779 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001780 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1781 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001782
1783 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001784 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001785
Robert Greenwalt7b816022014-04-18 15:25:25 -07001786 if (networkAgent.networkCapabilities.hasTransport(
1787 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001788 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1789 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001790 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001791 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001792 } else if (networkAgent.networkCapabilities.hasTransport(
1793 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001794 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1795 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001796 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001797 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001798 } else {
1799 // do not track any other networks
1800 timeout = 0;
1801 }
1802
Robert Greenwalt7b816022014-04-18 15:25:25 -07001803 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001804 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001805 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001806 } catch (Exception e) {
1807 // You shall not crash!
1808 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001809 }
1810 }
1811 }
1812
1813 /**
1814 * Remove data activity tracking when network disconnects.
1815 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001816 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1817 final String iface = networkAgent.linkProperties.getInterfaceName();
1818 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001819
Robert Greenwalt7b816022014-04-18 15:25:25 -07001820 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1821 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001822 try {
1823 // the call fails silently if no idletimer setup for this interface
1824 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001825 } catch (Exception e) {
1826 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001827 }
1828 }
1829 }
1830
1831 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001832 * Reads the network specific MTU size from reources.
1833 * and set it on it's iface.
1834 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001835 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1836 final String iface = newLp.getInterfaceName();
1837 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001838 if (oldLp == null && mtu == 0) {
1839 // Silently ignore unset MTU value.
1840 return;
1841 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001842 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1843 if (VDBG) log("identical MTU - not setting");
1844 return;
1845 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001846 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001847 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001848 return;
1849 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001850
w1997615afd812014-08-05 15:18:11 -07001851 // Cannot set MTU without interface name
1852 if (TextUtils.isEmpty(iface)) {
1853 loge("Setting MTU size with null iface.");
1854 return;
1855 }
1856
Robert Greenwalt7b816022014-04-18 15:25:25 -07001857 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001858 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001859 mNetd.setMtu(iface, mtu);
1860 } catch (Exception e) {
1861 Slog.e(TAG, "exception in setMtu()" + e);
1862 }
1863 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001864
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001865 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001866 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1867
1868 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001869 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001870 protected MockableSystemProperties getSystemProperties() {
1871 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001872 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001873
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001874 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1875 if (isDefaultNetwork(nai) == false) {
1876 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001877 }
1878
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001879 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1880 String[] values = null;
1881 if (tcpBufferSizes != null) {
1882 values = tcpBufferSizes.split(",");
1883 }
1884
1885 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001886 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001887 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1888 values = tcpBufferSizes.split(",");
1889 }
1890
1891 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1892
1893 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001894 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001895
1896 final String prefix = "/sys/kernel/ipv4/tcp_";
1897 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1898 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1899 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1900 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1901 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1902 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1903 mCurrentTcpBufferSizes = tcpBufferSizes;
1904 } catch (IOException e) {
1905 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001906 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001907
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001908 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001909 Settings.Global.TCP_DEFAULT_INIT_RWND,
1910 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001911 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1912 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001913 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001914 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001915 }
1916
Robert Greenwalt562cc542014-05-15 18:07:26 -07001917 @Override
1918 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001919 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001920 NETWORK_RESTORE_DELAY_PROP_NAME);
1921 if(restoreDefaultNetworkDelayStr != null &&
1922 restoreDefaultNetworkDelayStr.length() != 0) {
1923 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001924 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001925 } catch (NumberFormatException e) {
1926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001928 // if the system property isn't set, use the value for the apn type
1929 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1930
1931 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1932 (mNetConfigs[networkType] != null)) {
1933 ret = mNetConfigs[networkType].restoreTime;
1934 }
1935 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
1937
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001938 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001939 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001940 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001941 }
1942 return false;
1943 }
1944
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001945 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1946 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1947 final long DIAG_TIME_MS = 5000;
1948 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1949 // Start gathering diagnostic information.
1950 netDiags.add(new NetworkDiagnostics(
1951 nai.network,
1952 new LinkProperties(nai.linkProperties), // Must be a copy.
1953 DIAG_TIME_MS));
1954 }
1955
1956 for (NetworkDiagnostics netDiag : netDiags) {
1957 pw.println();
1958 netDiag.waitForMeasurements();
1959 netDiag.dump(pw);
1960 }
1961 }
1962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001964 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1965 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001966 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001967
Erik Kline7747fd42017-05-12 16:52:48 +09001968 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001969 dumpNetworkDiagnostics(pw);
1970 return;
Erik Klineee363c42017-05-29 09:11:03 +09001971 } else if (argsContain(args, TETHERING_ARG)) {
1972 mTethering.dump(fd, pw, args);
1973 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001974 }
Erik Kline379747a2015-06-05 17:47:34 +09001975
Lorenzo Colittie3805462015-06-03 11:18:24 +09001976 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001977 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001978 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001979 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001980 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001981 pw.println();
1982
Paul Jensen85cf78e2015-06-25 13:25:07 -04001983 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001984 pw.print("Active default network: ");
1985 if (defaultNai == null) {
1986 pw.println("none");
1987 } else {
1988 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001990 pw.println();
1991
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001992 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001993 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001994 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1995 pw.println(nai.toString());
1996 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001997 pw.println(String.format(
1998 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1999 nai.numForegroundNetworkRequests(),
2000 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2001 nai.numBackgroundNetworkRequests(),
2002 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002003 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002004 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2005 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002006 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002007 pw.decreaseIndent();
2008 pw.println("Lingered:");
2009 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002010 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002011 pw.decreaseIndent();
2012 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002013 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002014 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002015 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002016
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002017 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002018 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002019 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2020 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002021 }
2022 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002023 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002024
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002025 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002026
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002027 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002028 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002029
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002030 pw.println();
2031 mKeepaliveTracker.dump(pw);
2032
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002033 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002034 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002035
Erik Kline7747fd42017-05-12 16:52:48 +09002036 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002037 pw.println();
2038 synchronized (mValidationLogs) {
2039 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002040 for (ValidationLog p : mValidationLogs) {
2041 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002042 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002043 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002044 pw.decreaseIndent();
2045 }
2046 }
Erik Kline7523eb32015-07-09 18:24:03 +09002047
2048 pw.println();
2049 pw.println("mNetworkRequestInfoLogs (most recent first):");
2050 pw.increaseIndent();
2051 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2052 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002053
2054 pw.println();
2055 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2056 pw.increaseIndent();
2057 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2058 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002059
2060 pw.println();
2061 pw.println("NetTransition WakeLock activity (most recent first):");
2062 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09002063 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2064 pw.println("total releases: " + mTotalWakelockReleases);
2065 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2066 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2067 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2068 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2069 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2070 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002071 mWakelockLogs.reverseDump(fd, pw, args);
2072 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 }
2075
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002076 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002077 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002078 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002079 if (officialNai != null && officialNai.equals(nai)) return true;
2080 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002081 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002082 " - " + nai);
2083 }
2084 return false;
2085 }
2086
Robert Greenwalt42acef32009-08-12 16:08:25 -07002087 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002088 private class NetworkStateTrackerHandler extends Handler {
2089 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002090 super(looper);
2091 }
2092
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002093 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002095 default:
2096 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002097 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002098 handleAsyncChannelHalfConnect(msg);
2099 break;
2100 }
2101 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2102 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2103 if (nai != null) nai.asyncChannel.disconnect();
2104 break;
2105 }
2106 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2107 handleAsyncChannelDisconnected(msg);
2108 break;
2109 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002110 }
2111 return true;
2112 }
2113
2114 private void maybeHandleNetworkAgentMessage(Message msg) {
2115 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2116 if (nai == null) {
2117 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002118 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002119 }
2120 return;
2121 }
2122
2123 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002124 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002125 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2126 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002127 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2128 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002129 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002130 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002131 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002132 break;
2133 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002134 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002135 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002136 break;
2137 }
2138 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002139 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002140 updateNetworkInfo(nai, info);
2141 break;
2142 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002143 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002144 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002145 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002146 break;
2147 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002148 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002149 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2150 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002151 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002152 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002153 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002154 break;
2155 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002156 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002157 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2158 break;
2159 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002160 }
2161 }
2162
2163 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2164 switch (msg.what) {
2165 default:
2166 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002167 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline736353a2018-03-21 07:18:33 -07002168 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002169 if (nai == null) break;
2170
2171 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2172 final boolean wasValidated = nai.lastValidated;
2173 final boolean wasDefault = isDefaultNetwork(nai);
2174
Erik Klinea24d4592018-01-11 21:07:29 +09002175 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2176
Erik Klinea24d4592018-01-11 21:07:29 +09002177 if (DBG) {
Erik Kline736353a2018-03-21 07:18:33 -07002178 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2179 ? " with redirect to " + redirectUrl
2180 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002181 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2182 }
Erik Klinea24d4592018-01-11 21:07:29 +09002183 if (valid != nai.lastValidated) {
2184 if (wasDefault) {
2185 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2186 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002187 }
Erik Klinea24d4592018-01-11 21:07:29 +09002188 final int oldScore = nai.getCurrentScore();
2189 nai.lastValidated = valid;
2190 nai.everValidated |= valid;
2191 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2192 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2193 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2194 }
2195 updateInetCondition(nai);
2196 // Let the NetworkAgent know the state of its network
2197 Bundle redirectUrlBundle = new Bundle();
2198 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2199 nai.asyncChannel.sendMessage(
2200 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2201 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2202 0, redirectUrlBundle);
2203 if (wasValidated && !nai.lastValidated) {
2204 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002205 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002206 break;
2207 }
Paul Jensen869868be2014-05-15 10:33:05 -04002208 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002209 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002210 final boolean visible = toBool(msg.arg1);
Erik Kline736353a2018-03-21 07:18:33 -07002211 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002212 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002213 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002214 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002215 nai.lastCaptivePortalDetected = visible;
2216 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002217 if (nai.lastCaptivePortalDetected &&
2218 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2219 if (DBG) log("Avoiding captive portal network: " + nai.name());
2220 nai.asyncChannel.sendMessage(
2221 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2222 teardownUnneededNetwork(nai);
2223 break;
2224 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002225 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002226 }
2227 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002228 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002229 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002230 if (nai == null) {
2231 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2232 break;
2233 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002234 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002235 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002236 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002237 }
Paul Jensen869868be2014-05-15 10:33:05 -04002238 }
Paul Jensen869868be2014-05-15 10:33:05 -04002239 break;
2240 }
Erik Klinea24d4592018-01-11 21:07:29 +09002241 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline736353a2018-03-21 07:18:33 -07002242 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002243 if (nai == null) break;
2244
Erik Kline736353a2018-03-21 07:18:33 -07002245 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002246 break;
2247 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002248 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002249 return true;
2250 }
2251
Calvin Onbe96da12016-10-11 15:10:46 -07002252 private int getCaptivePortalMode() {
2253 return Settings.Global.getInt(mContext.getContentResolver(),
2254 Settings.Global.CAPTIVE_PORTAL_MODE,
2255 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2256 }
2257
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002258 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2259 switch (msg.what) {
2260 default:
2261 return false;
2262 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2263 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2264 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2265 handleLingerComplete(nai);
2266 }
2267 break;
2268 }
2269 }
2270 return true;
2271 }
2272
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002273 @Override
2274 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002275 if (!maybeHandleAsyncChannelMessage(msg) &&
2276 !maybeHandleNetworkMonitorMessage(msg) &&
2277 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002278 maybeHandleNetworkAgentMessage(msg);
2279 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002280 }
2281 }
2282
Erik Kline736353a2018-03-21 07:18:33 -07002283 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2284 return NetworkMonitor.isValidationRequired(
2285 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2286 }
2287
Erik Klinea24d4592018-01-11 21:07:29 +09002288 private void handlePrivateDnsSettingsChanged() {
2289 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2290
2291 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline736353a2018-03-21 07:18:33 -07002292 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk7301aa42018-03-05 12:42:22 -05002293 if (networkRequiresValidation(nai)) {
2294 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2295 }
Erik Klinea24d4592018-01-11 21:07:29 +09002296 }
2297 }
2298
Erik Kline736353a2018-03-21 07:18:33 -07002299 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2300 // Private DNS only ever applies to networks that might provide
2301 // Internet access and therefore also require validation.
2302 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002303
Erik Kline736353a2018-03-21 07:18:33 -07002304 // Notify the NetworkMonitor thread in case it needs to cancel or
2305 // schedule DNS resolutions. If a DNS resolution is required the
2306 // result will be sent back to us.
2307 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2308
2309 // With Private DNS bypass support, we can proceed to update the
2310 // Private DNS config immediately, even if we're in strict mode
2311 // and have not yet resolved the provider name into a set of IPs.
2312 updatePrivateDns(nai, cfg);
2313 }
2314
2315 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2316 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002317 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002318 }
2319
dalyk7301aa42018-03-05 12:42:22 -05002320 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2321 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2322 if (nai == null) {
2323 return;
2324 }
2325 mDnsManager.updatePrivateDnsValidation(update);
2326 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2327 }
2328
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002329 private void updateLingerState(NetworkAgentInfo nai, long now) {
2330 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2331 // 2. If the network was lingering and there are now requests, unlinger it.
2332 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2333 // one lingered request, start lingering.
2334 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002335 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002336 if (DBG) log("Unlingering " + nai.name());
2337 nai.unlinger();
2338 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002339 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002340 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002341 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002342 nai.linger();
2343 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2344 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2345 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002346 }
2347
Robert Greenwalt7b816022014-04-18 15:25:25 -07002348 private void handleAsyncChannelHalfConnect(Message msg) {
2349 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002350 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002351 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2352 if (VDBG) log("NetworkFactory connected");
2353 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002354 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002355 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002356 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002357 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002358 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002359 }
2360 } else {
2361 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002362 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002363 }
2364 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2365 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2366 if (VDBG) log("NetworkAgent connected");
2367 // A network agent has requested a connection. Establish the connection.
2368 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2369 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2370 } else {
2371 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002372 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002373 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002374 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002375 synchronized (mNetworkForNetId) {
2376 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002377 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002378 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002379 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002380 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002381 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002382 }
2383 }
2384 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002385
Robert Greenwalt7b816022014-04-18 15:25:25 -07002386 private void handleAsyncChannelDisconnected(Message msg) {
2387 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2388 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002389 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002390 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002391 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002392 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002393 // TODO - if we move the logic to the network agent (have them disconnect
2394 // because they lost all their requests or because their score isn't good)
2395 // then they would disconnect organically, report their new state and then
2396 // disconnect the channel.
2397 if (nai.networkInfo.isConnected()) {
2398 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2399 null, null);
2400 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002401 final boolean wasDefault = isDefaultNetwork(nai);
2402 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002403 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002404 // Log default network disconnection before required book-keeping.
2405 // Let rematchAllNetworksAndRequests() below record a new default network event
2406 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2407 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002408 long now = SystemClock.elapsedRealtime();
2409 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002410 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002411 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002412 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2413 // by other networks that are already connected. Perhaps that can be done by
2414 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2415 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002416 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002417 mKeepaliveTracker.handleStopAllKeepalives(nai,
2418 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002419 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2420 // Disable wakeup packet monitoring for each interface.
2421 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2422 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002423 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002424 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002425 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002426 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002427 // Remove the NetworkAgent, but don't mark the netId as
2428 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002429 mNetworkForNetId.remove(nai.network.netId);
2430 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002431 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002432 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2433 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002434 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002435 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002436 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002437 sendUpdatedScoreToFactories(request, 0);
2438 }
2439 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002440 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002441 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002442 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002443 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002444 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002445 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002446 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002447 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002448 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002449 if (nai.created) {
2450 // Tell netd to clean up the configuration for this network
2451 // (routing rules, DNS, etc).
2452 // This may be slow as it requires a lot of netd shelling out to ip and
2453 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2454 // after we've rematched networks with requests which should make a potential
2455 // fallback network the default or requested a new network from the
2456 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2457 // long time.
2458 try {
2459 mNetd.removeNetwork(nai.network.netId);
2460 } catch (Exception e) {
2461 loge("Exception removing network: " + e);
2462 }
Erik Klinea24d4592018-01-11 21:07:29 +09002463 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002464 }
2465 synchronized (mNetworkForNetId) {
2466 mNetIdInUse.delete(nai.network.netId);
2467 }
2468 } else {
2469 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2470 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002471 }
2472 }
2473
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002474 // If this method proves to be too slow then we can maintain a separate
2475 // pendingIntent => NetworkRequestInfo map.
2476 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2477 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2478 Intent intent = pendingIntent.getIntent();
2479 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2480 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2481 if (existingPendingIntent != null &&
2482 existingPendingIntent.getIntent().filterEquals(intent)) {
2483 return entry.getValue();
2484 }
2485 }
2486 return null;
2487 }
2488
2489 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2490 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2491
2492 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2493 if (existingRequest != null) { // remove the existing request.
2494 if (DBG) log("Replacing " + existingRequest.request + " with "
2495 + nri.request + " because their intents matched.");
2496 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2497 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002498 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002499 }
2500
Erik Klineda4bfa82015-04-30 12:58:40 +09002501 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002502 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002503 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002504 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002505 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002506 if (nri.request.networkCapabilities.hasSignalStrength() &&
2507 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2508 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002509 }
2510 }
2511 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002512 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002513 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002514 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002515 }
2516 }
2517
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002518 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2519 int callingUid) {
2520 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2521 if (nri != null) {
2522 handleReleaseNetworkRequest(nri.request, callingUid);
2523 }
2524 }
2525
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002526 // Determines whether the network is the best (or could become the best, if it validated), for
2527 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2528 // on the value of reason:
2529 //
2530 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2531 // then it should be torn down.
2532 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2533 // then it should be lingered.
2534 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2535 final int numRequests;
2536 switch (reason) {
2537 case TEARDOWN:
2538 numRequests = nai.numRequestNetworkRequests();
2539 break;
2540 case LINGER:
2541 numRequests = nai.numForegroundNetworkRequests();
2542 break;
2543 default:
2544 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2545 return true;
2546 }
2547
2548 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002549 return false;
2550 }
Paul Jensene0988542015-06-25 15:30:08 -04002551 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002552 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2553 // Background requests don't affect lingering.
2554 continue;
2555 }
2556
Paul Jensene0988542015-06-25 15:30:08 -04002557 // If this Network is already the highest scoring Network for a request, or if
2558 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002559 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002560 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002561 // Note that this catches two important cases:
2562 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2563 // is currently satisfying the request. This is desirable when
2564 // cellular ends up validating but WiFi does not.
2565 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002566 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002567 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002568 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002569 nai.getCurrentScoreAsValidated())) {
2570 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002571 }
2572 }
Paul Jensene0988542015-06-25 15:30:08 -04002573 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002574 }
2575
Erik Klineacdd6392016-07-07 16:50:58 +09002576 private NetworkRequestInfo getNriForAppRequest(
2577 NetworkRequest request, int callingUid, String requestedOperation) {
2578 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2579
Robert Greenwalt9258c642014-03-26 16:47:06 -07002580 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002581 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002582 log(String.format("UID %d attempted to %s for unowned request %s",
2583 callingUid, requestedOperation, nri));
2584 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002585 }
Erik Klineacdd6392016-07-07 16:50:58 +09002586 }
2587
2588 return nri;
2589 }
2590
Erik Kline57faba92015-11-25 12:49:38 +09002591 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002592 if (mNetworkRequests.get(nri.request) == null) {
2593 return;
Erik Kline57faba92015-11-25 12:49:38 +09002594 }
Hugo Benichicd952782017-09-20 11:20:14 +09002595 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002596 return;
2597 }
2598 if (VDBG || (DBG && nri.request.isRequest())) {
2599 log("releasing " + nri.request + " (timeout)");
2600 }
2601 handleRemoveNetworkRequest(nri);
2602 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002603 }
2604
Erik Klineacdd6392016-07-07 16:50:58 +09002605 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002606 final NetworkRequestInfo nri =
2607 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2608 if (nri == null) {
2609 return;
Erik Kline57faba92015-11-25 12:49:38 +09002610 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002611 if (VDBG || (DBG && nri.request.isRequest())) {
2612 log("releasing " + nri.request + " (release request)");
2613 }
2614 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002615 }
Erik Klineacdd6392016-07-07 16:50:58 +09002616
Hugo Benichidba33db2017-03-23 22:40:44 +09002617 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002618 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002619 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002620
Erik Klineacdd6392016-07-07 16:50:58 +09002621 synchronized (mUidToNetworkRequestCount) {
2622 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2623 if (requests < 1) {
2624 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2625 nri.mUid);
2626 } else if (requests == 1) {
2627 mUidToNetworkRequestCount.removeAt(
2628 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2629 } else {
2630 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2631 }
2632 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002633
Erik Klineacdd6392016-07-07 16:50:58 +09002634 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2635 if (nri.request.isRequest()) {
2636 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002637 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002638 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002639 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002640 nai.removeRequest(nri.request.requestId);
2641 if (VDBG) {
2642 log(" Removing from current network " + nai.name() +
2643 ", leaving " + nai.numNetworkRequests() + " requests.");
2644 }
2645 // If there are still lingered requests on this network, don't tear it down,
2646 // but resume lingering instead.
2647 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002648 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002649 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2650 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002651 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002652 wasKept = true;
2653 }
Hugo Benichicd952782017-09-20 11:20:14 +09002654 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002655 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2656 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002657 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002658 }
Erik Klineacdd6392016-07-07 16:50:58 +09002659 }
2660
2661 // TODO: remove this code once we know that the Slog.wtf is never hit.
2662 //
2663 // Find all networks that are satisfying this request and remove the request
2664 // from their request lists.
2665 // TODO - it's my understanding that for a request there is only a single
2666 // network satisfying it, so this loop is wasteful
2667 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2668 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2669 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2670 otherNai.name() + ", but mNetworkAgentInfos says " +
2671 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002672 }
2673 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002674
Erik Klineacdd6392016-07-07 16:50:58 +09002675 // Maintain the illusion. When this request arrived, we might have pretended
2676 // that a network connected to serve it, even though the network was already
2677 // connected. Now that this request has gone away, we might have to pretend
2678 // that the network disconnected. LegacyTypeTracker will generate that
2679 // phantom disconnect for this type.
2680 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2681 boolean doRemove = true;
2682 if (wasKept) {
2683 // check if any of the remaining requests for this network are for the
2684 // same legacy type - if so, don't remove the nai
2685 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2686 NetworkRequest otherRequest = nai.requestAt(i);
2687 if (otherRequest.legacyType == nri.request.legacyType &&
2688 otherRequest.isRequest()) {
2689 if (DBG) log(" still have other legacy request - leaving");
2690 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002691 }
2692 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002693 }
2694
Erik Klineacdd6392016-07-07 16:50:58 +09002695 if (doRemove) {
2696 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002697 }
2698 }
Erik Klineacdd6392016-07-07 16:50:58 +09002699
2700 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2701 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2702 nri.request);
2703 }
2704 } else {
2705 // listens don't have a singular affectedNetwork. Check all networks to see
2706 // if this listen request applies and remove it.
2707 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2708 nai.removeRequest(nri.request.requestId);
2709 if (nri.request.networkCapabilities.hasSignalStrength() &&
2710 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2711 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2712 }
2713 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002714 }
2715 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002716
Lorenzo Colitti18660282016-07-04 12:55:44 +09002717 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002718 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2719 enforceConnectivityInternalPermission();
2720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002721 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002722 }
2723
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002724 @Override
2725 public void setAvoidUnvalidated(Network network) {
2726 enforceConnectivityInternalPermission();
2727 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2728 }
2729
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002730 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2731 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2732 " accept=" + accept + " always=" + always);
2733
2734 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2735 if (nai == null) {
2736 // Nothing to do.
2737 return;
2738 }
2739
2740 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002741 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002742 return;
2743 }
2744
2745 if (!nai.networkMisc.explicitlySelected) {
2746 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2747 }
2748
2749 if (accept != nai.networkMisc.acceptUnvalidated) {
2750 int oldScore = nai.getCurrentScore();
2751 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002752 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002753 sendUpdatedScoreToFactories(nai);
2754 }
2755
2756 if (always) {
2757 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002758 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002759 }
2760
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002761 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002762 // Tell the NetworkAgent to not automatically reconnect to the network.
2763 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2764 // Teardown the nework.
2765 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002766 }
2767
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002768 }
2769
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002770 private void handleSetAvoidUnvalidated(Network network) {
2771 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2772 if (nai == null || nai.lastValidated) {
2773 // Nothing to do. The network either disconnected or revalidated.
2774 return;
2775 }
2776 if (!nai.avoidUnvalidated) {
2777 int oldScore = nai.getCurrentScore();
2778 nai.avoidUnvalidated = true;
2779 rematchAllNetworksAndRequests(nai, oldScore);
2780 sendUpdatedScoreToFactories(nai);
2781 }
2782 }
2783
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002784 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002785 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002786 mHandler.sendMessageDelayed(
2787 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2788 PROMPT_UNVALIDATED_DELAY_MS);
2789 }
2790
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002791 @Override
2792 public void startCaptivePortalApp(Network network) {
2793 enforceConnectivityInternalPermission();
2794 mHandler.post(() -> {
2795 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2796 if (nai == null) return;
2797 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2798 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2799 });
2800 }
2801
Hugo Benichic8e9e122016-09-14 23:23:08 +00002802 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002803 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002804 }
2805
Erik Kline065ab6e2016-10-02 18:02:14 +09002806 private void rematchForAvoidBadWifiUpdate() {
2807 rematchAllNetworksAndRequests(null, 0);
2808 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2809 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2810 sendUpdatedScoreToFactories(nai);
2811 }
2812 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002813 }
2814
Erik Kline065ab6e2016-10-02 18:02:14 +09002815 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002816 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002817 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002818 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002819 if (!configRestrict) {
2820 pw.println("Bad Wi-Fi avoidance: unrestricted");
2821 return;
2822 }
2823
2824 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2825 pw.increaseIndent();
2826 pw.println("Config restrict: " + configRestrict);
2827
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002828 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002829 String description;
2830 // Can't use a switch statement because strings are legal case labels, but null is not.
2831 if ("0".equals(value)) {
2832 description = "get stuck";
2833 } else if (value == null) {
2834 description = "prompt";
2835 } else if ("1".equals(value)) {
2836 description = "avoid";
2837 } else {
2838 description = value + " (?)";
2839 }
2840 pw.println("User setting: " + description);
2841 pw.println("Network overrides:");
2842 pw.increaseIndent();
2843 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2844 if (nai.avoidUnvalidated) {
2845 pw.println(nai.name());
2846 }
2847 }
2848 pw.decreaseIndent();
2849 pw.decreaseIndent();
2850 }
2851
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002852 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2853 final String action;
2854 switch (type) {
2855 case NO_INTERNET:
2856 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2857 break;
2858 case LOST_INTERNET:
2859 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2860 break;
2861 default:
2862 Slog.wtf(TAG, "Unknown notification type " + type);
2863 return;
2864 }
2865
2866 Intent intent = new Intent(action);
2867 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2868 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2869 intent.setClassName("com.android.settings",
2870 "com.android.settings.wifi.WifiNoInternetDialog");
2871
2872 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2873 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2874 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2875 }
2876
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002877 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002878 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002879 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2880
2881 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2882 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002883 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002884 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002885 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2886 return;
2887 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002888 showValidationNotification(nai, NotificationType.NO_INTERNET);
2889 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002890
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002891 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2892 NetworkCapabilities nc = nai.networkCapabilities;
2893 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002894
Erik Kline065ab6e2016-10-02 18:02:14 +09002895 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002896 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002897 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2898 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002899 }
2900
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002901 @Override
2902 public int getMultipathPreference(Network network) {
2903 enforceAccessPermission();
2904
2905 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002906 if (nai != null && nai.networkCapabilities
2907 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002908 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2909 }
2910
2911 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2912 }
2913
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002914 private class InternalHandler extends Handler {
2915 public InternalHandler(Looper looper) {
2916 super(looper);
2917 }
2918
2919 @Override
2920 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002921 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002922 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002923 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002924 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002925 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002926 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002927 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002928 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002929 break;
2930 }
Jason Monkdecd2952013-10-10 14:02:51 -04002931 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002932 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002933 break;
2934 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002935 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002936 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2937 break;
2938 }
2939 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2940 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002941 break;
2942 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002943 case EVENT_REGISTER_NETWORK_AGENT: {
2944 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2945 break;
2946 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002947 case EVENT_REGISTER_NETWORK_REQUEST:
2948 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002949 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002950 break;
2951 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002952 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2953 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002954 handleRegisterNetworkRequestWithIntent(msg);
2955 break;
2956 }
Erik Kline57faba92015-11-25 12:49:38 +09002957 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2958 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2959 handleTimedOutNetworkRequest(nri);
2960 break;
2961 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002962 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2963 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2964 break;
2965 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002966 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002967 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002968 break;
2969 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002970 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002971 Network network = (Network) msg.obj;
2972 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002973 break;
2974 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002975 case EVENT_SET_AVOID_UNVALIDATED: {
2976 handleSetAvoidUnvalidated((Network) msg.obj);
2977 break;
2978 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002979 case EVENT_PROMPT_UNVALIDATED: {
2980 handlePromptUnvalidated((Network) msg.obj);
2981 break;
2982 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002983 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2984 handleMobileDataAlwaysOn();
2985 break;
2986 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002987 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2988 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2989 mKeepaliveTracker.handleStartKeepalive(msg);
2990 break;
2991 }
2992 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2993 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2994 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2995 int slot = msg.arg1;
2996 int reason = msg.arg2;
2997 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2998 break;
2999 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003000 case EVENT_SYSTEM_READY: {
3001 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3002 nai.networkMonitor.systemReady = true;
3003 }
3004 break;
3005 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003006 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003007 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003008 break;
3009 }
Erik Klinea24d4592018-01-11 21:07:29 +09003010 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3011 handlePrivateDnsSettingsChanged();
3012 break;
dalyk7301aa42018-03-05 12:42:22 -05003013 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3014 handlePrivateDnsValidationUpdate(
3015 (PrivateDnsValidationUpdate) msg.obj);
3016 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 }
3018 }
3019 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003020
3021 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003022 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003023 public int tether(String iface, String callerPkg) {
3024 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003025 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003026 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003027 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003028 } else {
3029 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3030 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003031 }
3032
3033 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003034 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003035 public int untether(String iface, String callerPkg) {
3036 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003037
3038 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003039 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003040 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003041 } else {
3042 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3043 }
3044 }
3045
3046 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003047 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003048 public int getLastTetherError(String iface) {
3049 enforceTetherAccessPermission();
3050
3051 if (isTetheringSupported()) {
3052 return mTethering.getLastTetherError(iface);
3053 } else {
3054 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3055 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003056 }
3057
3058 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003059 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003060 public String[] getTetherableUsbRegexs() {
3061 enforceTetherAccessPermission();
3062 if (isTetheringSupported()) {
3063 return mTethering.getTetherableUsbRegexs();
3064 } else {
3065 return new String[0];
3066 }
3067 }
3068
Lorenzo Colitti18660282016-07-04 12:55:44 +09003069 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003070 public String[] getTetherableWifiRegexs() {
3071 enforceTetherAccessPermission();
3072 if (isTetheringSupported()) {
3073 return mTethering.getTetherableWifiRegexs();
3074 } else {
3075 return new String[0];
3076 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003077 }
3078
Lorenzo Colitti18660282016-07-04 12:55:44 +09003079 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003080 public String[] getTetherableBluetoothRegexs() {
3081 enforceTetherAccessPermission();
3082 if (isTetheringSupported()) {
3083 return mTethering.getTetherableBluetoothRegexs();
3084 } else {
3085 return new String[0];
3086 }
3087 }
3088
Lorenzo Colitti18660282016-07-04 12:55:44 +09003089 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003090 public int setUsbTethering(boolean enable, String callerPkg) {
3091 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003092 if (isTetheringSupported()) {
3093 return mTethering.setUsbTethering(enable);
3094 } else {
3095 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3096 }
3097 }
3098
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003099 // TODO - move iface listing, queries, etc to new module
3100 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003101 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003102 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003103 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003104 return mTethering.getTetherableIfaces();
3105 }
3106
Lorenzo Colitti18660282016-07-04 12:55:44 +09003107 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003108 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003109 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003110 return mTethering.getTetheredIfaces();
3111 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003112
Lorenzo Colitti18660282016-07-04 12:55:44 +09003113 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003114 public String[] getTetheringErroredIfaces() {
3115 enforceTetherAccessPermission();
3116 return mTethering.getErroredIfaces();
3117 }
3118
Lorenzo Colitti18660282016-07-04 12:55:44 +09003119 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003120 public String[] getTetheredDhcpRanges() {
3121 enforceConnectivityInternalPermission();
3122 return mTethering.getTetheredDhcpRanges();
3123 }
3124
Udam Sainic3b640c2017-06-07 12:06:28 -07003125 @Override
3126 public boolean isTetheringSupported(String callerPkg) {
3127 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3128 return isTetheringSupported();
3129 }
3130
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003131 // if ro.tether.denied = true we default to no tethering
3132 // gservices could set the secure setting to 1 though to enable it on a build where it
3133 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07003134 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003135 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3136 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3137 Settings.Global.TETHER_SUPPORTED, defaultVal));
3138 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003139 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003140
3141 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3142 boolean adminUser = false;
3143 final long token = Binder.clearCallingIdentity();
3144 try {
3145 adminUser = mUserManager.isAdminUser();
3146 } finally {
3147 Binder.restoreCallingIdentity(token);
3148 }
3149
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003150 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003151 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003152
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003153 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003154 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3155 String callerPkg) {
3156 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003157 if (!isTetheringSupported()) {
3158 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3159 return;
3160 }
3161 mTethering.startTethering(type, receiver, showProvisioningUi);
3162 }
3163
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003164 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003165 public void stopTethering(int type, String callerPkg) {
3166 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003167 mTethering.stopTethering(type);
3168 }
3169
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003170 // Called when we lose the default network and have no replacement yet.
3171 // This will automatically be cleared after X seconds or a new default network
3172 // becomes CONNECTED, whichever happens first. The timer is started by the
3173 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003174 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003175 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003176 if (mNetTransitionWakeLock.isHeld()) {
3177 return;
3178 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003179 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003180 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3181 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003182 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003183 mWakelockLogs.log("ACQUIRE for " + forWhom);
3184 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3185 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003186 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003187
Hugo Benichi4c31b342017-03-30 23:18:10 +09003188 // Called when we gain a new default network to release the network transition wakelock in a
3189 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3190 // message is cancelled.
3191 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003192 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003193 if (!mNetTransitionWakeLock.isHeld()) {
3194 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003195 }
3196 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003197 // Cancel self timeout on wakelock hold.
3198 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3199 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3200 mHandler.sendMessageDelayed(msg, 1000);
3201 }
3202
3203 // Called when either message of ensureNetworkTransitionWakelock or
3204 // scheduleReleaseNetworkTransitionWakelock is processed.
3205 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3206 String event = eventName(eventId);
3207 synchronized (this) {
3208 if (!mNetTransitionWakeLock.isHeld()) {
3209 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3210 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3211 return;
3212 }
3213 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003214 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3215 mTotalWakelockDurationMs += lockDuration;
3216 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3217 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003218 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003219 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003220 }
3221
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003222 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003223 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003224 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003225 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003226 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003227 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003228 }
3229
Lorenzo Colitti18660282016-07-04 12:55:44 +09003230 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003231 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003232 enforceAccessPermission();
3233 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003234 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003235 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003236 mHandler.sendMessage(
3237 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3238 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003239
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003240 private void handleReportNetworkConnectivity(
3241 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003242 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003243 if (network == null) {
3244 nai = getDefaultNetwork();
3245 } else {
3246 nai = getNetworkAgentInfoForNetwork(network);
3247 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003248 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3249 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3250 return;
3251 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003252 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003253 if (hasConnectivity == nai.lastValidated) {
3254 return;
3255 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003256 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003257 int netid = nai.network.netId;
3258 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003259 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003260 // Validating a network that has not yet connected could result in a call to
3261 // rematchNetworkAndRequests() which is not meant to work on such networks.
3262 if (!nai.everConnected) {
3263 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003264 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003265 LinkProperties lp = getLinkProperties(nai);
3266 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3267 return;
3268 }
Erik Kline736353a2018-03-21 07:18:33 -07003269 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003270 }
3271
Paul Jensencee9b512015-05-06 07:32:40 -04003272 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003273 // this information is already available as a world read/writable jvm property
3274 // so this API change wouldn't have a benifit. It also breaks the passing
3275 // of proxy info to all the JVMs.
3276 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003277 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003278 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003279 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3280 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003281 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003282 }
3283
Lorenzo Colitti18660282016-07-04 12:55:44 +09003284 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003285 public ProxyInfo getProxyForNetwork(Network network) {
3286 if (network == null) return getDefaultProxy();
3287 final ProxyInfo globalProxy = getGlobalProxy();
3288 if (globalProxy != null) return globalProxy;
3289 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3290 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3291 // caller may not have.
3292 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3293 if (nai == null) return null;
3294 synchronized (nai) {
3295 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3296 if (proxyInfo == null) return null;
3297 return new ProxyInfo(proxyInfo);
3298 }
3299 }
3300
Paul Jensene0bef712014-12-10 15:12:18 -05003301 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3302 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3303 // proxy is null then there is no proxy in place).
3304 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3305 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3306 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3307 proxy = null;
3308 }
3309 return proxy;
3310 }
3311
3312 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3313 // better for determining if a new proxy broadcast is necessary:
3314 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3315 // avoid unnecessary broadcasts.
3316 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3317 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3318 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3319 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3320 // all set.
3321 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3322 a = canonicalizeProxyInfo(a);
3323 b = canonicalizeProxyInfo(b);
3324 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3325 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3326 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3327 }
3328
Jason Monk207900c2014-04-25 15:00:09 -04003329 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003330 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003331
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003332 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003333 if (proxyProperties == mGlobalProxy) return;
3334 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3335 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3336
3337 String host = "";
3338 int port = 0;
3339 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003340 String pacFileUrl = "";
3341 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003342 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003343 if (!proxyProperties.isValid()) {
3344 if (DBG)
3345 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3346 return;
3347 }
Jason Monk207900c2014-04-25 15:00:09 -04003348 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003349 host = mGlobalProxy.getHost();
3350 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003351 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003352 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003353 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003354 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003355 } else {
3356 mGlobalProxy = null;
3357 }
3358 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003359 final long token = Binder.clearCallingIdentity();
3360 try {
3361 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3362 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3363 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3364 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003365 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003366 } finally {
3367 Binder.restoreCallingIdentity(token);
3368 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003369
Jason Monkcf0f97a2014-10-02 15:39:38 -04003370 if (mGlobalProxy == null) {
3371 proxyProperties = mDefaultProxy;
3372 }
3373 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003374 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003375 }
3376
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003377 private void loadGlobalProxy() {
3378 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003379 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3380 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3381 String exclList = Settings.Global.getString(res,
3382 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003383 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3384 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003385 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003386 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003387 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003388 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003389 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003390 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003391 if (!proxyProperties.isValid()) {
3392 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3393 return;
3394 }
3395
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003396 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003397 mGlobalProxy = proxyProperties;
3398 }
3399 }
3400 }
3401
Jason Monk207900c2014-04-25 15:00:09 -04003402 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003403 // this information is already available as a world read/writable jvm property
3404 // so this API change wouldn't have a benifit. It also breaks the passing
3405 // of proxy info to all the JVMs.
3406 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003407 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003408 return mGlobalProxy;
3409 }
3410 }
3411
Jason Monk207900c2014-04-25 15:00:09 -04003412 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003413 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003414 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003415 proxy = null;
3416 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003417 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003418 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003419 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003420 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003421 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3422 return;
3423 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003424
3425 // This call could be coming from the PacManager, containing the port of the local
3426 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3427 // global (to get the correct local port), and send a broadcast.
3428 // TODO: Switch PacManager to have its own message to send back rather than
3429 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003430 if ((mGlobalProxy != null) && (proxy != null)
3431 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003432 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3433 mGlobalProxy = proxy;
3434 sendProxyBroadcast(mGlobalProxy);
3435 return;
3436 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003437 mDefaultProxy = proxy;
3438
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003439 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003440 if (!mDefaultProxyDisabled) {
3441 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003442 }
3443 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003444 }
3445
Paul Jensene0bef712014-12-10 15:12:18 -05003446 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3447 // This method gets called when any network changes proxy, but the broadcast only ever contains
3448 // the default proxy (even if it hasn't changed).
3449 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3450 // world where an app might be bound to a non-default network.
3451 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3452 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3453 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3454
3455 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3456 sendProxyBroadcast(getDefaultProxy());
3457 }
3458 }
3459
Robert Greenwalt434203a2010-10-11 16:00:27 -07003460 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003461 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3462 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003463 if (!TextUtils.isEmpty(proxy)) {
3464 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003465 if (data.length == 0) {
3466 return;
3467 }
3468
Robert Greenwalt434203a2010-10-11 16:00:27 -07003469 String proxyHost = data[0];
3470 int proxyPort = 8080;
3471 if (data.length > 1) {
3472 try {
3473 proxyPort = Integer.parseInt(data[1]);
3474 } catch (NumberFormatException e) {
3475 return;
3476 }
3477 }
Jason Monk207900c2014-04-25 15:00:09 -04003478 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003479 setGlobalProxy(p);
3480 }
3481 }
3482
Jason Monk207900c2014-04-25 15:00:09 -04003483 private void sendProxyBroadcast(ProxyInfo proxy) {
3484 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003485 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003486 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003487 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003488 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3489 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003490 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003491 final long ident = Binder.clearCallingIdentity();
3492 try {
3493 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3494 } finally {
3495 Binder.restoreCallingIdentity(ident);
3496 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003497 }
3498
3499 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003500 final private HashMap<Uri, Integer> mUriEventMap;
3501 final private Context mContext;
3502 final private Handler mHandler;
3503
3504 SettingsObserver(Context context, Handler handler) {
3505 super(null);
3506 mUriEventMap = new HashMap<Uri, Integer>();
3507 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003508 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003509 }
3510
Erik Klineda4bfa82015-04-30 12:58:40 +09003511 void observe(Uri uri, int what) {
3512 mUriEventMap.put(uri, what);
3513 final ContentResolver resolver = mContext.getContentResolver();
3514 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003515 }
3516
3517 @Override
3518 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003519 Slog.wtf(TAG, "Should never be reached.");
3520 }
3521
3522 @Override
3523 public void onChange(boolean selfChange, Uri uri) {
3524 final Integer what = mUriEventMap.get(uri);
3525 if (what != null) {
3526 mHandler.obtainMessage(what.intValue()).sendToTarget();
3527 } else {
3528 loge("No matching event to send for URI=" + uri);
3529 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003530 }
3531 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003532
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003533 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003534 Slog.d(TAG, s);
3535 }
3536
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003537 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003538 Slog.e(TAG, s);
3539 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003540
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003541 private static void loge(String s, Throwable t) {
3542 Slog.e(TAG, s, t);
3543 }
3544
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003545 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003546 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003547 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3548 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3549 *
3550 * @param oldPackage Package name of the application which currently controls VPN, which will
3551 * be replaced. If there is no such application, this should should either be
3552 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3553 * @param newPackage Package name of the application which should gain control of VPN, or
3554 * {@code null} to disable.
3555 * @param userId User for whom to prepare the new VPN.
3556 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003557 * @hide
3558 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003559 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003560 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3561 int userId) {
3562 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003563
Hugo Benichi20035e02017-04-26 14:53:28 +09003564 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003565 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003566 Vpn vpn = mVpns.get(userId);
3567 if (vpn != null) {
3568 return vpn.prepare(oldPackage, newPackage);
3569 } else {
3570 return false;
3571 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003572 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003573 }
3574
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003575 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003576 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3577 * This method is used by system-privileged apps.
3578 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3579 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3580 *
3581 * @param packageName The package for which authorization state should change.
3582 * @param userId User for whom {@code packageName} is installed.
3583 * @param authorized {@code true} if this app should be able to start a VPN connection without
3584 * explicit user approval, {@code false} if not.
3585 *
Jeff Davidson05542602014-08-11 14:07:27 -07003586 * @hide
3587 */
3588 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003589 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3590 enforceCrossUserPermission(userId);
3591
Hugo Benichi20035e02017-04-26 14:53:28 +09003592 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003593 Vpn vpn = mVpns.get(userId);
3594 if (vpn != null) {
3595 vpn.setPackageAuthorization(packageName, authorized);
3596 }
Jeff Davidson05542602014-08-11 14:07:27 -07003597 }
3598 }
3599
3600 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003601 * Configure a TUN interface and return its file descriptor. Parameters
3602 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003603 * and not available in ConnectivityManager. Permissions are checked in
3604 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003605 * @hide
3606 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003607 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003608 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003609 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003610 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003611 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003612 return mVpns.get(user).establish(config);
3613 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003614 }
3615
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003616 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003617 * Start legacy VPN, controlling native daemons as needed. Creates a
3618 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003619 */
3620 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003621 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003622 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003623 final LinkProperties egress = getActiveLinkProperties();
3624 if (egress == null) {
3625 throw new IllegalStateException("Missing active network connection");
3626 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003627 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003628 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003629 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3630 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003631 }
3632
3633 /**
3634 * Return the information of the ongoing legacy VPN. This method is used
3635 * by VpnSettings and not available in ConnectivityManager. Permissions
3636 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003637 */
3638 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003639 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3640 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003641
Hugo Benichi20035e02017-04-26 14:53:28 +09003642 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003643 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003644 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003645 }
3646
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003647 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003648 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3649 * and not available in ConnectivityManager.
3650 */
3651 @Override
3652 public VpnInfo[] getAllVpnInfo() {
3653 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003654 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003655 if (mLockdownEnabled) {
3656 return new VpnInfo[0];
3657 }
3658
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003659 List<VpnInfo> infoList = new ArrayList<>();
3660 for (int i = 0; i < mVpns.size(); i++) {
3661 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3662 if (info != null) {
3663 infoList.add(info);
3664 }
3665 }
3666 return infoList.toArray(new VpnInfo[infoList.size()]);
3667 }
3668 }
3669
3670 /**
3671 * @return VPN information for accounting, or null if we can't retrieve all required
3672 * information, e.g primary underlying iface.
3673 */
3674 @Nullable
3675 private VpnInfo createVpnInfo(Vpn vpn) {
3676 VpnInfo info = vpn.getVpnInfo();
3677 if (info == null) {
3678 return null;
3679 }
3680 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3681 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3682 // the underlyingNetworks list.
3683 if (underlyingNetworks == null) {
3684 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3685 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3686 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3687 }
3688 } else if (underlyingNetworks.length > 0) {
3689 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3690 if (linkProperties != null) {
3691 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3692 }
3693 }
3694 return info.primaryUnderlyingIface == null ? null : info;
3695 }
3696
3697 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003698 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3699 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003700 * Permissions are checked in Vpn class.
3701 * @hide
3702 */
3703 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003704 public VpnConfig getVpnConfig(int userId) {
3705 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003706 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003707 Vpn vpn = mVpns.get(userId);
3708 if (vpn != null) {
3709 return vpn.getVpnConfig();
3710 } else {
3711 return null;
3712 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003713 }
3714 }
3715
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003716 @Override
3717 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003718 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3719 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3720 return false;
3721 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003722
Hugo Benichi69744342017-11-27 10:57:16 +09003723 synchronized (mVpns) {
3724 // Tear down existing lockdown if profile was removed
3725 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3726 if (mLockdownEnabled) {
3727 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3728 if (profileTag == null) {
3729 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3730 return false;
3731 }
3732 String profileName = new String(profileTag);
3733 final VpnProfile profile = VpnProfile.decode(
3734 profileName, mKeyStore.get(Credentials.VPN + profileName));
3735 if (profile == null) {
3736 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3737 setLockdownTracker(null);
3738 return true;
3739 }
3740 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003741 Vpn vpn = mVpns.get(user);
3742 if (vpn == null) {
3743 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3744 return false;
3745 }
3746 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003747 } else {
3748 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003749 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003750 }
3751
3752 return true;
3753 }
3754
3755 /**
3756 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3757 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3758 */
Hugo Benichi69744342017-11-27 10:57:16 +09003759 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003760 private void setLockdownTracker(LockdownVpnTracker tracker) {
3761 // Shutdown any existing tracker
3762 final LockdownVpnTracker existing = mLockdownTracker;
3763 mLockdownTracker = null;
3764 if (existing != null) {
3765 existing.shutdown();
3766 }
3767
Robin Leec3736bc2017-03-10 16:19:54 +00003768 if (tracker != null) {
3769 mLockdownTracker = tracker;
3770 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003771 }
3772 }
3773
Hugo Benichi69744342017-11-27 10:57:16 +09003774 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003775 private void throwIfLockdownEnabled() {
3776 if (mLockdownEnabled) {
3777 throw new IllegalStateException("Unavailable in lockdown mode");
3778 }
3779 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003780
Robin Lee244ce8e2016-01-05 18:03:46 +00003781 /**
Robin Lee17e61832016-05-09 13:46:28 +01003782 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3783 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003784 *
Robin Lee17e61832016-05-09 13:46:28 +01003785 * @return {@code true} if the service was started, the service was already connected, or there
3786 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003787 */
Robin Lee17e61832016-05-09 13:46:28 +01003788 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003789 synchronized (mVpns) {
3790 Vpn vpn = mVpns.get(userId);
3791 if (vpn == null) {
3792 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3793 // exists already.
3794 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3795 return false;
3796 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003797
Robin Lee812800c2016-05-13 15:38:08 +01003798 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003799 }
3800 }
3801
3802 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003803 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3804 enforceSettingsPermission();
3805 enforceCrossUserPermission(userId);
3806
3807 synchronized (mVpns) {
3808 Vpn vpn = mVpns.get(userId);
3809 if (vpn == null) {
3810 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3811 return false;
3812 }
3813 return vpn.isAlwaysOnPackageSupported(packageName);
3814 }
3815 }
3816
3817 @Override
Robin Leedc679712016-05-03 13:23:03 +01003818 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003819 enforceConnectivityInternalPermission();
3820 enforceCrossUserPermission(userId);
3821
Robin Lee244ce8e2016-01-05 18:03:46 +00003822 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003823 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3824 if (LockdownVpnTracker.isEnabled()) {
3825 return false;
3826 }
3827
Robin Lee244ce8e2016-01-05 18:03:46 +00003828 Vpn vpn = mVpns.get(userId);
3829 if (vpn == null) {
3830 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3831 return false;
3832 }
Robin Lee17e61832016-05-09 13:46:28 +01003833 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003834 return false;
3835 }
Robin Lee17e61832016-05-09 13:46:28 +01003836 if (!startAlwaysOnVpn(userId)) {
3837 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003838 return false;
3839 }
3840 }
3841 return true;
3842 }
3843
3844 @Override
3845 public String getAlwaysOnVpnPackage(int userId) {
3846 enforceConnectivityInternalPermission();
3847 enforceCrossUserPermission(userId);
3848
3849 synchronized (mVpns) {
3850 Vpn vpn = mVpns.get(userId);
3851 if (vpn == null) {
3852 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3853 return null;
3854 }
3855 return vpn.getAlwaysOnPackage();
3856 }
3857 }
3858
Wink Savilleab9321d2013-06-29 21:10:57 -07003859 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003860 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003861 // TODO: Remove? Any reason to trigger a provisioning check?
3862 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003863 }
3864
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003865 /** Location to an updatable file listing carrier provisioning urls.
3866 * An example:
3867 *
3868 * <?xml version="1.0" encoding="utf-8"?>
3869 * <provisioningUrls>
3870 * <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 -07003871 * </provisioningUrls>
3872 */
3873 private static final String PROVISIONING_URL_PATH =
3874 "/data/misc/radio/provisioning_urls.xml";
3875 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003876
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003877 /** XML tag for root element. */
3878 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3879 /** XML tag for individual url */
3880 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003881 /** XML attribute for mcc */
3882 private static final String ATTR_MCC = "mcc";
3883 /** XML attribute for mnc */
3884 private static final String ATTR_MNC = "mnc";
3885
Paul Jensen434dde82015-06-11 09:43:30 -04003886 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003887 FileReader fileReader = null;
3888 XmlPullParser parser = null;
3889 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003890
3891 try {
3892 fileReader = new FileReader(mProvisioningUrlFile);
3893 parser = Xml.newPullParser();
3894 parser.setInput(fileReader);
3895 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3896
3897 while (true) {
3898 XmlUtils.nextElement(parser);
3899
3900 String element = parser.getName();
3901 if (element == null) break;
3902
Paul Jensen434dde82015-06-11 09:43:30 -04003903 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003904 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3905 try {
3906 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3907 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3908 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3909 parser.next();
3910 if (parser.getEventType() == XmlPullParser.TEXT) {
3911 return parser.getText();
3912 }
3913 }
3914 }
3915 } catch (NumberFormatException e) {
3916 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3917 }
3918 }
3919 }
3920 return null;
3921 } catch (FileNotFoundException e) {
3922 loge("Carrier Provisioning Urls file not found");
3923 } catch (XmlPullParserException e) {
3924 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3925 } catch (IOException e) {
3926 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3927 } finally {
3928 if (fileReader != null) {
3929 try {
3930 fileReader.close();
3931 } catch (IOException e) {}
3932 }
3933 }
3934 return null;
3935 }
3936
Wink Saville42d4f082013-07-20 20:31:59 -07003937 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003938 public String getMobileProvisioningUrl() {
3939 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003940 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003941 if (TextUtils.isEmpty(url)) {
3942 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003943 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003944 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003945 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003946 }
Wink Saville8cf35602013-07-10 23:00:07 -07003947 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003948 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003949 String phoneNumber = mTelephonyManager.getLine1Number();
3950 if (TextUtils.isEmpty(phoneNumber)) {
3951 phoneNumber = "0000000000";
3952 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003953 url = String.format(url,
3954 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3955 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003956 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003957 }
3958
Wink Savilleab9321d2013-06-29 21:10:57 -07003959 return url;
3960 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003961
Wink Saville948282b2013-08-29 08:55:16 -07003962 @Override
3963 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003964 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003965 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003966 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3967 return;
3968 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003969 final long ident = Binder.clearCallingIdentity();
3970 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003971 // Concatenate the range of types onto the range of NetIDs.
3972 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3973 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003974 } finally {
3975 Binder.restoreCallingIdentity(ident);
3976 }
Wink Saville948282b2013-08-29 08:55:16 -07003977 }
Wink Saville7788c612013-08-29 14:57:08 -07003978
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003979 @Override
3980 public void setAirplaneMode(boolean enable) {
3981 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003982 final long ident = Binder.clearCallingIdentity();
3983 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003984 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003985 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003986 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3987 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003988 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003989 } finally {
3990 Binder.restoreCallingIdentity(ident);
3991 }
3992 }
3993
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003994 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003995 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003996 Vpn userVpn = mVpns.get(userId);
3997 if (userVpn != null) {
3998 loge("Starting user already has a VPN");
3999 return;
4000 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004001 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004002 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004003 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4004 updateLockdownVpn();
4005 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004006 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004007 }
4008
4009 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004010 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004011 Vpn userVpn = mVpns.get(userId);
4012 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004013 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004014 return;
4015 }
Robin Lee17e61832016-05-09 13:46:28 +01004016 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004017 mVpns.delete(userId);
4018 }
4019 }
4020
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004021 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004022 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004023 final int vpnsSize = mVpns.size();
4024 for (int i = 0; i < vpnsSize; i++) {
4025 Vpn vpn = mVpns.valueAt(i);
4026 vpn.onUserAdded(userId);
4027 }
4028 }
4029 }
4030
4031 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004032 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004033 final int vpnsSize = mVpns.size();
4034 for (int i = 0; i < vpnsSize; i++) {
4035 Vpn vpn = mVpns.valueAt(i);
4036 vpn.onUserRemoved(userId);
4037 }
4038 }
4039 }
4040
Robin Lee89e7a692016-02-29 14:38:17 +00004041 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004042 synchronized (mVpns) {
4043 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4044 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4045 updateLockdownVpn();
4046 } else {
4047 startAlwaysOnVpn(userId);
4048 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004049 }
4050 }
4051
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004052 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4053 @Override
4054 public void onReceive(Context context, Intent intent) {
4055 final String action = intent.getAction();
4056 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4057 if (userId == UserHandle.USER_NULL) return;
4058
Robin Lee323f29d2016-05-04 16:38:06 +01004059 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004060 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004061 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004062 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004063 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4064 onUserAdded(userId);
4065 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4066 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004067 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4068 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004069 }
4070 }
4071 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004072
Robin Lee95204e02017-01-27 11:59:22 +00004073 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4074 @Override
4075 public void onReceive(Context context, Intent intent) {
4076 // Try creating lockdown tracker, since user present usually means
4077 // unlocked keystore.
4078 updateLockdownVpn();
4079 mContext.unregisterReceiver(this);
4080 }
4081 };
4082
Robert Greenwalta67be032014-05-16 15:49:14 -07004083 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4084 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004085 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4086 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004087
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004088 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4089 // Map from UID to number of NetworkRequests that UID has filed.
4090 @GuardedBy("mUidToNetworkRequestCount")
4091 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4092
Robert Greenwalta67be032014-05-16 15:49:14 -07004093 private static class NetworkFactoryInfo {
4094 public final String name;
4095 public final Messenger messenger;
4096 public final AsyncChannel asyncChannel;
4097
4098 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4099 this.name = name;
4100 this.messenger = messenger;
4101 this.asyncChannel = asyncChannel;
4102 }
4103 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004104
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004105 private void ensureNetworkRequestHasType(NetworkRequest request) {
4106 if (request.type == NetworkRequest.Type.NONE) {
4107 throw new IllegalArgumentException(
4108 "All NetworkRequests in ConnectivityService must have a type");
4109 }
4110 }
4111
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004112 /**
4113 * Tracks info about the requester.
4114 * Also used to notice when the calling process dies so we can self-expire
4115 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004116 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004117 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004118 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004119 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004120 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004121 final int mPid;
4122 final int mUid;
4123 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004124
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004125 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004126 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004127 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004128 mPendingIntent = pi;
4129 messenger = null;
4130 mBinder = null;
4131 mPid = getCallingPid();
4132 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004133 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004134 }
4135
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004136 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004137 super();
4138 messenger = m;
4139 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004140 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004141 mBinder = binder;
4142 mPid = getCallingPid();
4143 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004144 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004145 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004146
4147 try {
4148 mBinder.linkToDeath(this, 0);
4149 } catch (RemoteException e) {
4150 binderDied();
4151 }
4152 }
4153
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004154 private void enforceRequestCountLimit() {
4155 synchronized (mUidToNetworkRequestCount) {
4156 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4157 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004158 throw new ServiceSpecificException(
4159 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004160 }
4161 mUidToNetworkRequestCount.put(mUid, networkRequests);
4162 }
4163 }
4164
Robert Greenwalt9258c642014-03-26 16:47:06 -07004165 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004166 if (mBinder != null) {
4167 mBinder.unlinkToDeath(this, 0);
4168 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004169 }
4170
4171 public void binderDied() {
4172 log("ConnectivityService NetworkRequestInfo binderDied(" +
4173 request + ", " + mBinder + ")");
4174 releaseNetworkRequest(request);
4175 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004176
4177 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004178 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004179 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004180 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004181 }
4182
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004183 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4184 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4185 if (badCapability != null) {
4186 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004187 }
4188 }
4189
Erik Kline9d598e12015-07-13 16:37:51 +09004190 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004191 final SortedSet<Integer> thresholds = new TreeSet();
4192 synchronized (nai) {
4193 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4194 if (nri.request.networkCapabilities.hasSignalStrength() &&
4195 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4196 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4197 }
4198 }
4199 }
Erik Kline9d598e12015-07-13 16:37:51 +09004200 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004201 }
4202
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004203 private void updateSignalStrengthThresholds(
4204 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4205 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004206 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004207 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4208
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004209 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004210 String detail;
4211 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4212 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4213 } else {
4214 detail = reason;
4215 }
4216 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4217 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4218 }
4219
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004220 nai.asyncChannel.sendMessage(
4221 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004222 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004223 }
4224
Etan Cohen859748f2017-04-03 17:42:34 -07004225 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4226 if (nc == null) {
4227 return;
4228 }
4229 NetworkSpecifier ns = nc.getNetworkSpecifier();
4230 if (ns == null) {
4231 return;
4232 }
4233 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4234 ns.assertValidFromUid(Binder.getCallingUid());
4235 }
4236
Robert Greenwalt9258c642014-03-26 16:47:06 -07004237 @Override
4238 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004239 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004240 final NetworkRequest.Type type = (networkCapabilities == null)
4241 ? NetworkRequest.Type.TRACK_DEFAULT
4242 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004243 // If the requested networkCapabilities is null, take them instead from
4244 // the default network request. This allows callers to keep track of
4245 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004246 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004247 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004248 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004249 enforceAccessPermission();
4250 } else {
4251 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4252 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004253 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4254 // of the app when the request is filed, but we never change the request if the app
4255 // changes network state. http://b/29964605
4256 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004257 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004258 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004259 // Set the UID range for this request to the single UID of the requester, or to an empty
4260 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004261 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4262 // are no visible methods to set the UIDs, an app could use reflection to try and get
4263 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004264 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004265
Etan Cohenba07c8c2017-02-05 10:42:27 -08004266 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004267 throw new IllegalArgumentException("Bad timeout specified");
4268 }
Etan Cohen859748f2017-04-03 17:42:34 -07004269 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004270
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004271 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004272 nextNetworkRequestId(), type);
4273 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004274 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004275
4276 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004277 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004278 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004279 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004280 }
4281 return networkRequest;
4282 }
4283
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004284 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004285 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004286 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004287 } else {
4288 enforceChangePermission();
4289 }
4290 }
4291
fenglub15e72b2015-03-20 11:29:56 -07004292 @Override
fengludb571472015-04-21 17:12:05 -07004293 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004294 enforceAccessPermission();
4295 NetworkAgentInfo nai = null;
4296 if (network == null) {
4297 return false;
4298 }
4299 synchronized (mNetworkForNetId) {
4300 nai = mNetworkForNetId.get(network.netId);
4301 }
4302 if (nai != null) {
4303 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4304 return true;
4305 }
4306 return false;
4307 }
4308
Felipe Lemeee27cab2016-06-20 16:36:29 -07004309 private boolean isSystem(int uid) {
4310 return uid < Process.FIRST_APPLICATION_UID;
4311 }
fenglub15e72b2015-03-20 11:29:56 -07004312
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004313 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004314 final int uid = Binder.getCallingUid();
4315 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004316 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004317 return;
4318 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004319 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4320 // Policy already enforced.
4321 return;
4322 }
4323 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4324 // If UID is restricted, don't allow them to bring up metered APNs.
4325 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004326 }
4327 }
4328
Robert Greenwalt9258c642014-03-26 16:47:06 -07004329 @Override
4330 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4331 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004332 checkNotNull(operation, "PendingIntent cannot be null.");
4333 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4334 enforceNetworkRequestPermissions(networkCapabilities);
4335 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004336 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004337 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004338 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004339
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004340 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004341 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4342 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004343 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004344 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4345 nri));
4346 return networkRequest;
4347 }
4348
Jeremy Joslin79294842014-12-03 17:15:28 -08004349 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4350 mHandler.sendMessageDelayed(
4351 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4352 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4353 }
4354
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004355 @Override
4356 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004357 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004358 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4359 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004360 }
4361
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004362 // In order to implement the compatibility measure for pre-M apps that call
4363 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4364 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4365 // This ensures it has permission to do so.
4366 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4367 if (nc == null) {
4368 return false;
4369 }
4370 int[] transportTypes = nc.getTransportTypes();
4371 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4372 return false;
4373 }
4374 try {
4375 mContext.enforceCallingOrSelfPermission(
4376 android.Manifest.permission.ACCESS_WIFI_STATE,
4377 "ConnectivityService");
4378 } catch (SecurityException e) {
4379 return false;
4380 }
4381 return true;
4382 }
4383
Robert Greenwalt9258c642014-03-26 16:47:06 -07004384 @Override
4385 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4386 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004387 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4388 enforceAccessPermission();
4389 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004390
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004391 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004392 restrictRequestUidsForCaller(nc);
Chalard Jean1d738002018-03-20 19:13:57 +09004393 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4394 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4395 // onLost and onAvailable callbacks when networks move in and out of the background.
4396 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4397 // can't request networks.
4398 restrictBackgroundRequestForCaller(nc);
4399 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004400
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004401 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004402 NetworkRequest.Type.LISTEN);
4403 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004404 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004405
4406 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4407 return networkRequest;
4408 }
4409
4410 @Override
4411 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4412 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004413 checkNotNull(operation, "PendingIntent cannot be null.");
4414 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4415 enforceAccessPermission();
4416 }
Etan Cohen859748f2017-04-03 17:42:34 -07004417 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004418
Chalard Jeandda156a2018-01-10 21:19:32 +09004419 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004420 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004421
4422 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004423 NetworkRequest.Type.LISTEN);
4424 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004425 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004426
4427 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004428 }
4429
Erik Klineacdd6392016-07-07 16:50:58 +09004430 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004431 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004432 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004433 mHandler.sendMessage(mHandler.obtainMessage(
4434 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004435 }
4436
4437 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004438 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004439 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004440 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4441 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004442 }
4443
Robert Greenwalta67be032014-05-16 15:49:14 -07004444 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004445 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004446 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4447 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4448 }
4449
4450 @Override
4451 public void unregisterNetworkFactory(Messenger messenger) {
4452 enforceConnectivityInternalPermission();
4453 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4454 }
4455
4456 private void handleUnregisterNetworkFactory(Messenger messenger) {
4457 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4458 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004459 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004460 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004461 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004462 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004463 }
4464
Robert Greenwalt7b816022014-04-18 15:25:25 -07004465 /**
4466 * NetworkAgentInfo supporting a request by requestId.
4467 * These have already been vetted (their Capabilities satisfy the request)
4468 * and the are the highest scored network available.
4469 * the are keyed off the Requests requestId.
4470 */
Hugo Benichicd952782017-09-20 11:20:14 +09004471 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4472 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004473 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4474 new SparseArray<NetworkAgentInfo>();
4475
Paul Jensen31a94f42015-02-13 14:18:39 -05004476 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4477 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004478 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4479 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004480 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4481 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4482 // there may not be a strict 1:1 correlation between the two.
4483 @GuardedBy("mNetworkForNetId")
4484 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004485
Robert Greenwalt7b816022014-04-18 15:25:25 -07004486 // NetworkAgentInfo keyed off its connecting messenger
4487 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004488 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004489 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4490 new HashMap<Messenger, NetworkAgentInfo>();
4491
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004492 @GuardedBy("mBlockedAppUids")
4493 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4494
Paul Jensen2c311d62014-11-17 12:34:51 -05004495 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004496 private final NetworkRequest mDefaultRequest;
4497
Erik Klineda4bfa82015-04-30 12:58:40 +09004498 // Request used to optionally keep mobile data active even when higher
4499 // priority networks like Wi-Fi are active.
4500 private final NetworkRequest mDefaultMobileDataRequest;
4501
Hugo Benichicd952782017-09-20 11:20:14 +09004502 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4503 synchronized (mNetworkForRequestId) {
4504 return mNetworkForRequestId.get(requestId);
4505 }
4506 }
4507
4508 private void clearNetworkForRequest(int requestId) {
4509 synchronized (mNetworkForRequestId) {
4510 mNetworkForRequestId.remove(requestId);
4511 }
4512 }
4513
4514 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4515 synchronized (mNetworkForRequestId) {
4516 mNetworkForRequestId.put(requestId, nai);
4517 }
4518 }
4519
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004520 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004521 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004522 }
4523
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004524 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004525 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004526 }
4527
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004528 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4529 return nri.request.requestId == mDefaultRequest.requestId;
4530 }
4531
Paul Jensen31a94f42015-02-13 14:18:39 -05004532 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004533 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004534 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004535 enforceConnectivityInternalPermission();
4536
Rubin Xu1bb5c082017-09-05 18:40:49 +01004537 LinkProperties lp = new LinkProperties(linkProperties);
4538 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004539 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4540 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004541 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004542 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004543 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004544 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004545 // Make sure the network capabilities reflect what the agent info says.
4546 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004547 synchronized (this) {
4548 nai.networkMonitor.systemReady = mSystemReady;
4549 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004550 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4551 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004552 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004553 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004554 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004555 }
4556
Erik Klinee5dac902018-03-04 21:01:01 +09004557 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004558 if (VDBG) log("Got NetworkAgent Messenger");
Erik Klinee5dac902018-03-04 21:01:01 +09004559 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004560 synchronized (mNetworkForNetId) {
Erik Klinee5dac902018-03-04 21:01:01 +09004561 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004562 }
Erik Klinee5dac902018-03-04 21:01:01 +09004563 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4564 NetworkInfo networkInfo = nai.networkInfo;
4565 nai.networkInfo = null;
4566 updateNetworkInfo(nai, networkInfo);
4567 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004568 }
4569
4570 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4571 LinkProperties newLp = networkAgent.linkProperties;
4572 int netId = networkAgent.network.netId;
4573
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004574 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4575 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004576 if (networkAgent.clatd != null) {
4577 networkAgent.clatd.fixupLinkProperties(oldLp);
4578 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004579
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004580 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004581 updateMtu(newLp, oldLp);
4582 // TODO - figure out what to do for clat
4583// for (LinkProperties lp : newLp.getStackedLinks()) {
4584// updateMtu(lp, null);
4585// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004586 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004587
Erik Kline94887872016-04-05 13:30:49 +09004588 updateRoutes(newLp, oldLp, netId);
4589 updateDnses(newLp, oldLp, netId);
dalyk7301aa42018-03-05 12:42:22 -05004590 // Make sure LinkProperties represents the latest private DNS status.
4591 // This does not need to be done before updateDnses because the
4592 // LinkProperties are not the source of the private DNS configuration.
4593 // updateDnses will fetch the private DNS configuration from DnsManager.
4594 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004595
Hugo Benichib577d652017-06-27 15:13:20 +09004596 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004597 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004598 if (isDefaultNetwork(networkAgent)) {
4599 handleApplyDefaultProxy(newLp.getHttpProxy());
4600 } else {
4601 updateProxy(newLp, oldLp, networkAgent);
4602 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004603 // TODO - move this check to cover the whole function
4604 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004605 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004606 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4607 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004608
4609 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004610 }
4611
Joel Scherpelz668370b2017-06-08 15:35:21 +09004612 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004613 // Marks are only available on WiFi interaces. Checking for
4614 // marks on unsupported interfaces is harmless.
4615 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4616 return;
4617 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004618
Joel Scherpelz668370b2017-06-08 15:35:21 +09004619 int mark = mContext.getResources().getInteger(
4620 com.android.internal.R.integer.config_networkWakeupPacketMark);
4621 int mask = mContext.getResources().getInteger(
4622 com.android.internal.R.integer.config_networkWakeupPacketMask);
4623
4624 // Mask/mark of zero will not detect anything interesting.
4625 // Don't install rules unless both values are nonzero.
4626 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004627 return;
4628 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004629
4630 final String prefix = "iface:" + iface;
4631 try {
4632 if (add) {
4633 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4634 } else {
4635 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4636 }
4637 } catch (Exception e) {
4638 loge("Exception modifying wakeup packet monitoring: " + e);
4639 }
4640
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004641 }
4642
4643 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4644 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004645 CompareResult<String> interfaceDiff = new CompareResult<String>(
4646 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4647 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004648 for (String iface : interfaceDiff.added) {
4649 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004650 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004651 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004652 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004653 } catch (Exception e) {
4654 loge("Exception adding interface: " + e);
4655 }
4656 }
4657 for (String iface : interfaceDiff.removed) {
4658 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004659 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004660 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004661 mNetd.removeInterfaceFromNetwork(iface, netId);
4662 } catch (Exception e) {
4663 loge("Exception removing interface: " + e);
4664 }
4665 }
4666 }
4667
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004668 /**
4669 * Have netd update routes from oldLp to newLp.
4670 * @return true if routes changed between oldLp and newLp
4671 */
4672 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004673 // Compare the route diff to determine which routes should be added and removed.
4674 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4675 oldLp != null ? oldLp.getAllRoutes() : null,
4676 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004677
4678 // add routes before removing old in case it helps with continuous connectivity
4679
4680 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4681 for (RouteInfo route : routeDiff.added) {
4682 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004683 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004684 try {
4685 mNetd.addRoute(netId, route);
4686 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004687 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4688 loge("Exception in addRoute for non-gateway: " + e);
4689 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004690 }
4691 }
4692 for (RouteInfo route : routeDiff.added) {
4693 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004694 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004695 try {
4696 mNetd.addRoute(netId, route);
4697 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004698 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4699 loge("Exception in addRoute for gateway: " + e);
4700 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004701 }
4702 }
4703
4704 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004705 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004706 try {
4707 mNetd.removeRoute(netId, route);
4708 } catch (Exception e) {
4709 loge("Exception in removeRoute: " + e);
4710 }
4711 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004712 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004713 }
Erik Kline41368502015-06-17 13:19:54 +09004714
Erik Kline94887872016-04-05 13:30:49 +09004715 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4716 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4717 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004718 }
Erik Kline94887872016-04-05 13:30:49 +09004719
Erik Kline1742fe12017-12-13 19:40:49 +09004720 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4721 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4722
Erik Klinea24d4592018-01-11 21:07:29 +09004723 if (DBG) {
4724 final Collection<InetAddress> dnses = newLp.getDnsServers();
4725 log("Setting DNS servers for network " + netId + " to " + dnses);
4726 }
Erik Kline94887872016-04-05 13:30:49 +09004727 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004728 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004729 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004730 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004731 }
Erik Kline4edba012017-04-07 15:29:29 +09004732 }
4733
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004734 private String getNetworkPermission(NetworkCapabilities nc) {
4735 // TODO: make these permission strings AIDL constants instead.
4736 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4737 return NetworkManagementService.PERMISSION_SYSTEM;
4738 }
4739 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4740 return NetworkManagementService.PERMISSION_NETWORK;
4741 }
4742 return null;
4743 }
4744
Paul Jensen3d194ea2015-06-16 14:27:36 -04004745 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004746 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4747 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4748 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004749 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004750 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004751 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004752 if (nai.everConnected &&
4753 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4754 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichibae105a2017-08-16 13:19:04 +09004755 // does not cause any request (that is not a listen) currently matching that agent to
4756 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004757 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichieae7a222017-07-25 11:40:56 +09004758 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004759 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004760 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004761 }
4762
Paul Jensen3d194ea2015-06-16 14:27:36 -04004763 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004764 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004765 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004766 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004767 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004768 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004769 }
Paul Jensene0988542015-06-25 15:30:08 -04004770 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004771 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004772 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004773 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004774 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004775 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004776 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004777 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004778 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004779 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004780 if (nai.isSuspended()) {
4781 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4782 } else {
4783 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4784 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004785
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004786 return newNc;
4787 }
4788
4789 /**
4790 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4791 *
4792 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4793 * capabilities we manage and store in {@code nai}, such as validated status and captive
4794 * portal status)
4795 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4796 * potentially triggers rematches.
4797 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4798 * change.)
4799 *
4800 * @param oldScore score of the network before any of the changes that prompted us
4801 * to call this function.
4802 * @param nai the network having its capabilities updated.
4803 * @param nc the new network capabilities.
4804 */
4805 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4806 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4807
4808 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004809
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004810 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004811 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004812 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004813 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004814 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004815 } catch (RemoteException e) {
4816 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004817 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004818 }
4819
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004820 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004821 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004822 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004823 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004824 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004825
Chalard Jeanf213ca12018-01-16 18:43:05 +09004826 updateUids(nai, prevNc, newNc);
4827
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004828 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004829 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4830 // the change we're processing can't affect any requests, it can only affect the listens
4831 // on this network. We might have been called by rematchNetworkAndRequests when a
4832 // network changed foreground state.
4833 processListenRequests(nai, true);
4834 } else {
4835 // If the requestable capabilities have changed or the score changed, we can't have been
4836 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004837 rematchAllNetworksAndRequests(nai, oldScore);
4838 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004839 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004840
4841 // Report changes that are interesting for network statistics tracking.
4842 if (prevNc != null) {
4843 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004844 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004845 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004846 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004847 if (meteredChanged || roamingChanged) {
4848 notifyIfacesChangedForNetworkStats();
4849 }
4850 }
4851
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004852 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004853 // Tell VPNs about updated capabilities, since they may need to
4854 // bubble those changes through.
4855 synchronized (mVpns) {
4856 for (int i = 0; i < mVpns.size(); i++) {
4857 final Vpn vpn = mVpns.valueAt(i);
4858 vpn.updateCapabilities();
4859 }
4860 }
4861 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004862 }
4863
Chalard Jeanf213ca12018-01-16 18:43:05 +09004864 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4865 NetworkCapabilities newNc) {
4866 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4867 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4868 if (null == prevRanges) prevRanges = new ArraySet<>();
4869 if (null == newRanges) newRanges = new ArraySet<>();
4870 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4871
4872 prevRanges.removeAll(newRanges);
4873 newRanges.removeAll(prevRangesCopy);
4874
4875 try {
4876 if (!newRanges.isEmpty()) {
4877 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4878 newRanges.toArray(addedRangesArray);
4879 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4880 }
4881 if (!prevRanges.isEmpty()) {
4882 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4883 prevRanges.toArray(removedRangesArray);
4884 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4885 }
4886 } catch (Exception e) {
4887 // Never crash!
4888 loge("Exception in updateUids: " + e);
4889 }
4890 }
4891
Hugo Benichief502882017-09-01 01:23:32 +00004892 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline736353a2018-03-21 07:18:33 -07004893 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004894 // Ignore updates for disconnected networks
4895 return;
4896 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004897 // newLp is already a defensive copy.
4898 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004899 if (VDBG) {
4900 log("Update of LinkProperties for " + nai.name() +
4901 "; created=" + nai.created +
4902 "; everConnected=" + nai.everConnected);
4903 }
4904 LinkProperties oldLp = nai.linkProperties;
4905 synchronized (nai) {
4906 nai.linkProperties = newLp;
4907 }
4908 if (nai.everConnected) {
4909 updateLinkProperties(nai, oldLp);
4910 }
4911 }
4912
Paul Jensenc8b9a742014-09-30 15:37:41 -04004913 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004914 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4915 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004916 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004917 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004918 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4919 }
4920 }
4921
Robert Greenwalt7b816022014-04-18 15:25:25 -07004922 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4923 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004924 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004925 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4926 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004927 }
4928 }
4929
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004930 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4931 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004932 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004933 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004934 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4935 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004936 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004937 sendIntent(nri.mPendingIntent, intent);
4938 }
4939 // else not handled
4940 }
4941
4942 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4943 mPendingIntentWakeLock.acquire();
4944 try {
4945 if (DBG) log("Sending " + pendingIntent);
4946 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4947 } catch (PendingIntent.CanceledException e) {
4948 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4949 mPendingIntentWakeLock.release();
4950 releasePendingNetworkRequest(pendingIntent);
4951 }
4952 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4953 }
4954
4955 @Override
4956 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4957 String resultData, Bundle resultExtras) {
4958 if (DBG) log("Finished sending " + pendingIntent);
4959 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004960 // Release with a delay so the receiving client has an opportunity to put in its
4961 // own request.
4962 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004963 }
4964
Chalard Jeanf19db372018-01-26 19:24:40 +09004965 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004966 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004967 if (nri.messenger == null) {
4968 return; // Default request has no msgr
4969 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004970 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004971 // TODO: check if defensive copies of data is needed.
4972 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004973 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004974 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4975 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004976 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004977 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09004978 case ConnectivityManager.CALLBACK_AVAILABLE: {
4979 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
4980 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
4981 break;
4982 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004983 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004984 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004985 break;
4986 }
4987 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09004988 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb552c462018-02-21 18:43:54 +09004989 final NetworkCapabilities nc = networkCapabilitiesWithoutUidsUnlessAllowed(
4990 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09004991 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004992 break;
4993 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004994 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004995 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004996 break;
4997 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004998 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004999 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005000 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005001 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005002 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005003 String notification = ConnectivityManager.getCallbackName(notificationType);
5004 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005005 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005006 nri.messenger.send(msg);
5007 } catch (RemoteException e) {
5008 // may occur naturally in the race of binder death.
5009 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5010 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005011 }
5012
Hugo Benichidba33db2017-03-23 22:40:44 +09005013 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5014 bundle.putParcelable(t.getClass().getSimpleName(), t);
5015 }
5016
Paul Jensenc8b9a742014-09-30 15:37:41 -04005017 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005018 if (nai.numRequestNetworkRequests() != 0) {
5019 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5020 NetworkRequest nr = nai.requestAt(i);
5021 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005022 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005023 loge("Dead network still had at least " + nr);
5024 break;
5025 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005026 }
5027 nai.asyncChannel.disconnect();
5028 }
5029
Robert Greenwalt7b816022014-04-18 15:25:25 -07005030 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5031 if (oldNetwork == null) {
5032 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5033 return;
5034 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005035 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005036
5037 // If we get here it means that the last linger timeout for this network expired. So there
5038 // must be no other active linger timers, and we must stop lingering.
5039 oldNetwork.clearLingerState();
5040
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005041 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005042 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005043 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005044 } else {
5045 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005046 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5047 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005048 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005049 }
5050
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005051 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005052 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005053 setupDataActivityTracking(newNetwork);
5054 try {
5055 mNetd.setDefaultNetId(newNetwork.network.netId);
5056 } catch (Exception e) {
5057 loge("Exception setting default network :" + e);
5058 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005059
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005060 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005061 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005062 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005063 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005064 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005065 }
5066
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005067 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005068 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5069 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5070 NetworkRequest nr = nri.request;
5071 if (!nr.isListen()) continue;
5072 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5073 nai.removeRequest(nri.request.requestId);
5074 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5075 }
5076 }
5077
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005078 if (capabilitiesChanged) {
5079 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5080 }
5081
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005082 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5083 NetworkRequest nr = nri.request;
5084 if (!nr.isListen()) continue;
5085 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5086 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005087 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005088 }
5089 }
5090 }
5091
Paul Jensen2161a8e2014-09-11 11:00:39 -04005092 // Handles a network appearing or improving its score.
5093 //
5094 // - Evaluates all current NetworkRequests that can be
5095 // satisfied by newNetwork, and reassigns to newNetwork
5096 // any such requests for which newNetwork is the best.
5097 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005098 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005099 // needed. A network is needed if it is the best network for
5100 // one or more NetworkRequests, or if it is a VPN.
5101 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005102 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005103 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005104 //
5105 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5106 // networks that have no chance (i.e. even if validated)
5107 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005108 //
5109 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5110 // it does not remove NetworkRequests that other Networks could better satisfy.
5111 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5112 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5113 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005114 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005115 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005116 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5117 // performed to tear down unvalidated networks that have no chance (i.e. even if
5118 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005119 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005120 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005121 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005122 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005123 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005124 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005125
5126 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5127 final int score = newNetwork.getCurrentScore();
5128
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005129 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005130
Paul Jensen2161a8e2014-09-11 11:00:39 -04005131 // Find and migrate to this Network any NetworkRequests for
5132 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005133 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005134 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005135 NetworkCapabilities nc = newNetwork.networkCapabilities;
5136 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005137 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005138 // Process requests in the first pass and listens in the second pass. This allows us to
5139 // change a network's capabilities depending on which requests it has. This is only
5140 // correct if the change in capabilities doesn't affect whether the network satisfies
5141 // requests or not, and doesn't affect the network's score.
5142 if (nri.request.isListen()) continue;
5143
Hugo Benichicd952782017-09-20 11:20:14 +09005144 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005145 final boolean satisfies = newNetwork.satisfies(nri.request);
5146 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005147 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005148 log("Network " + newNetwork.name() + " was already satisfying" +
5149 " request " + nri.request.requestId + ". No change.");
5150 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005151 keep = true;
5152 continue;
5153 }
5154
5155 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005156 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005157 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005158 // next check if it's better than any current network we're using for
5159 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005160 if (VDBG) {
5161 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005162 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005163 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005164 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005165 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005166 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005167 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005168 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005169 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005170 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005171 affectedNetworks.add(currentNetwork);
5172 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005173 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005174 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005175 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005176 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005177 if (!newNetwork.addRequest(nri.request)) {
5178 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5179 }
5180 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005181 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005182 // Tell NetworkFactories about the new score, so they can stop
5183 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005184 // TODO - this could get expensive if we have alot of requests for this
5185 // network. Think about if there is a way to reduce this. Push
5186 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005187 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005188 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005189 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005190 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005191 if (currentNetwork != null) {
5192 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5193 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005194 }
5195 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005196 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005197 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5198 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005199 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005200 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5201 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5202 // This means this code doesn't have to handle the case where "currentNetwork" no
5203 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5204 if (DBG) {
5205 log("Network " + newNetwork.name() + " stopped satisfying" +
5206 " request " + nri.request.requestId);
5207 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005208 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005209 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005210 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005211 sendUpdatedScoreToFactories(nri.request, 0);
5212 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005213 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5214 newNetwork.name() +
5215 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005216 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005217 // TODO: Technically, sending CALLBACK_LOST here is
5218 // incorrect if there is a replacement network currently
5219 // connected that can satisfy nri, which is a request
5220 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005221 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5222 // so this code is only incorrect for a network that loses
5223 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005224 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005225 }
5226 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005227 if (isNewDefault) {
5228 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005229 makeDefault(newNetwork);
5230 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005231 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005232 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005233 // Have a new default network, release the transition wakelock in
5234 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005235 }
5236
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005237 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5238 Slog.wtf(TAG, String.format(
5239 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005240 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005241 }
5242 if (newNetwork.getCurrentScore() != score) {
5243 Slog.wtf(TAG, String.format(
5244 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005245 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005246 }
5247
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005248 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005249 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5250 // If the network went from background to foreground or vice versa, we need to update
5251 // its foreground state. It is safe to do this after rematching the requests because
5252 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5253 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005254 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005255 } else {
5256 processListenRequests(newNetwork, false);
5257 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005258
Paul Jensencf4c2c62015-07-01 14:16:32 -04005259 // do this after the default net is switched, but
5260 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005261 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005262
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005263 // Linger any networks that are no longer needed. This should be done after sending the
5264 // available callback for newNetwork.
5265 for (NetworkAgentInfo nai : affectedNetworks) {
5266 updateLingerState(nai, now);
5267 }
5268 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5269 // does not need to be done in any particular order.
5270 updateLingerState(newNetwork, now);
5271
Paul Jensencf4c2c62015-07-01 14:16:32 -04005272 if (isNewDefault) {
5273 // Maintain the illusion: since the legacy API only
5274 // understands one network at a time, we must pretend
5275 // that the current default network disconnected before
5276 // the new one connected.
5277 if (oldDefaultNetwork != null) {
5278 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5279 oldDefaultNetwork, true);
5280 }
5281 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5282 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5283 notifyLockdownVpn(newNetwork);
5284 }
5285
Robert Greenwalt7b816022014-04-18 15:25:25 -07005286 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005287 // Notify battery stats service about this network, both the normal
5288 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005289 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005290 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005291 final IBatteryStats bs = BatteryStatsService.getService();
5292 final int type = newNetwork.networkInfo.getType();
5293
5294 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5295 bs.noteNetworkInterfaceType(baseIface, type);
5296 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5297 final String stackedIface = stacked.getInterfaceName();
5298 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005299 }
5300 } catch (RemoteException ignored) {
5301 }
5302
Robert Greenwalt152ed372014-12-17 17:19:53 -08005303 // This has to happen after the notifyNetworkCallbacks as that tickles each
5304 // ConnectivityManager instance so that legacy requests correctly bind dns
5305 // requests to this network. The legacy users are listening for this bcast
5306 // and will generally do a dns request so they can ensureRouteToHost and if
5307 // they do that before the callbacks happen they'll use the default network.
5308 //
5309 // TODO: Is there still a race here? We send the broadcast
5310 // after sending the callback, but if the app can receive the
5311 // broadcast before the callback, it might still break.
5312 //
5313 // This *does* introduce a race where if the user uses the new api
5314 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5315 // they may get old info. Reverse this after the old startUsing api is removed.
5316 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005317 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5318 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005319 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005320 // legacy type tracker filters out repeat adds
5321 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5322 }
5323 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005324
5325 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5326 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5327 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5328 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5329 if (newNetwork.isVPN()) {
5330 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5331 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005332 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005333 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5334 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005335 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005336 if (nai.getLingerExpiry() > 0) {
5337 // This network has active linger timers and no requests, but is not
5338 // lingering. Linger it.
5339 //
5340 // One way (the only way?) this can happen if this network is unvalidated
5341 // and became unneeded due to another network improving its score to the
5342 // point where this network will no longer be able to satisfy any requests
5343 // even if it validates.
5344 updateLingerState(nai, now);
5345 } else {
5346 if (DBG) log("Reaping " + nai.name());
5347 teardownUnneededNetwork(nai);
5348 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005349 }
5350 }
5351 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005352 }
5353
Paul Jensen1c7ba022015-06-16 14:27:36 -04005354 /**
5355 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5356 * being disconnected.
5357 * @param changed If only one Network's score or capabilities have been modified since the last
5358 * time this function was called, pass this Network in this argument, otherwise pass
5359 * null.
5360 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5361 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5362 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5363 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5364 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005365 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005366 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005367 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5368 // to avoid the slowness. It is not simply enough to process just "changed", for
5369 // example in the case where "changed"'s score decreases and another network should begin
5370 // satifying a NetworkRequest that "changed" currently satisfies.
5371
5372 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5373 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5374 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005375 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005376 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005377 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005378 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005379 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5380 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5381 // Rematch higher scoring networks first to prevent requests first matching a lower
5382 // scoring network and then a higher scoring network, which could produce multiple
5383 // callbacks and inadvertently unlinger networks.
5384 Arrays.sort(nais);
5385 for (NetworkAgentInfo nai : nais) {
5386 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005387 // Only reap the last time through the loop. Reaping before all rematching
5388 // is complete could incorrectly teardown a network that hasn't yet been
5389 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005390 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005391 : ReapUnvalidatedNetworks.REAP,
5392 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005393 }
5394 }
5395 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005396
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005397 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005398 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005399 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005400 // For now only update icons for default connection.
5401 // TODO: Update WiFi and cellular icons separately. b/17237507
5402 if (!isDefaultNetwork(nai)) return;
5403
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005404 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005405 // Don't repeat publish.
5406 if (newInetCondition == mDefaultInetConditionPublished) return;
5407
5408 mDefaultInetConditionPublished = newInetCondition;
5409 sendInetConditionBroadcast(nai.networkInfo);
5410 }
5411
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005412 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005413 synchronized (mVpns) {
5414 if (mLockdownTracker != null) {
5415 if (nai != null && nai.isVPN()) {
5416 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5417 } else {
5418 mLockdownTracker.onNetworkInfoChanged();
5419 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005420 }
5421 }
5422 }
5423
Robert Greenwalt7b816022014-04-18 15:25:25 -07005424 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005425 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005426 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005427 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005428 synchronized (networkAgent) {
5429 oldInfo = networkAgent.networkInfo;
5430 networkAgent.networkInfo = newInfo;
5431 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005432 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005433
Robert Greenwalt7b816022014-04-18 15:25:25 -07005434 if (DBG) {
5435 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5436 (oldInfo == null ? "null" : oldInfo.getState()) +
5437 " to " + state);
5438 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005439
Robin Lee585e2482016-05-01 23:00:00 +01005440 if (!networkAgent.created
5441 && (state == NetworkInfo.State.CONNECTED
5442 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005443
5444 // A network that has just connected has zero requests and is thus a foreground network.
5445 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5446
Robert Greenwalt7b816022014-04-18 15:25:25 -07005447 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005448 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005449 if (networkAgent.isVPN()) {
5450 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005451 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5452 (networkAgent.networkMisc == null ||
5453 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005454 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005455 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005456 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005457 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005458 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005459 loge("Error creating network " + networkAgent.network.netId + ": "
5460 + e.getMessage());
5461 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005462 }
Paul Jenseneec75412014-08-04 12:21:19 -04005463 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005464 }
5465
5466 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5467 networkAgent.everConnected = true;
5468
Lorenzo Colitti2df4c7d2018-02-27 22:47:01 +09005469 if (networkAgent.linkProperties == null) {
5470 Slog.wtf(TAG, networkAgent.name() + " connected with null LinkProperties");
5471 }
5472
Erik Kline736353a2018-03-21 07:18:33 -07005473 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005474 updateLinkProperties(networkAgent, null);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005475
Paul Jensenca8f16a2014-05-09 12:47:55 -04005476 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005477 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005478
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005479 if (networkAgent.isVPN()) {
5480 // Temporarily disable the default proxy (not global).
5481 synchronized (mProxyLock) {
5482 if (!mDefaultProxyDisabled) {
5483 mDefaultProxyDisabled = true;
5484 if (mGlobalProxy == null && mDefaultProxy != null) {
5485 sendProxyBroadcast(null);
5486 }
5487 }
5488 }
5489 // TODO: support proxy per network.
5490 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005491
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005492 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5493 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5494 // capabilities, so it only needs to be done once on initial connect, not every time the
5495 // network's capabilities change. Note that we do this before rematching the network,
5496 // so we could decide to tear it down immediately afterwards. That's fine though - on
5497 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5498 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005499 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005500
Paul Jensen2161a8e2014-09-11 11:00:39 -04005501 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005502 final long now = SystemClock.elapsedRealtime();
5503 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005504
5505 // This has to happen after matching the requests, because callbacks are just requests.
5506 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005507 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005508 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005509 if (networkAgent.isVPN()) {
5510 synchronized (mProxyLock) {
5511 if (mDefaultProxyDisabled) {
5512 mDefaultProxyDisabled = false;
5513 if (mGlobalProxy == null && mDefaultProxy != null) {
5514 sendProxyBroadcast(mDefaultProxy);
5515 }
5516 }
5517 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005518 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005519 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005520 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5521 state == NetworkInfo.State.SUSPENDED) {
5522 // going into or coming out of SUSPEND: rescore and notify
5523 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005524 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005525 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005526 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5527 networkAgent.networkCapabilities);
5528 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5529 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005530 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5531 ConnectivityManager.CALLBACK_SUSPENDED :
5532 ConnectivityManager.CALLBACK_RESUMED));
5533 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005534 }
5535 }
5536
Robert Greenwaltac96c522014-06-03 16:43:57 -07005537 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005538 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005539 if (score < 0) {
5540 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5541 "). Bumping score to min of 0");
5542 score = 0;
5543 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005544
Paul Jensen2161a8e2014-09-11 11:00:39 -04005545 final int oldScore = nai.getCurrentScore();
5546 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005547
Paul Jensen85cf78e2015-06-25 13:25:07 -04005548 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005549
Paul Jensenc8b9a742014-09-30 15:37:41 -04005550 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005551 }
5552
Erik Klinec75d4fa2017-02-15 19:59:17 +09005553 // Notify only this one new request of the current state. Transfer all the
5554 // current state by calling NetworkCapabilities and LinkProperties callbacks
5555 // so that callers can be guaranteed to have as close to atomicity in state
5556 // transfer as can be supported by this current API.
5557 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005558 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005559 if (nri.mPendingIntent != null) {
5560 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5561 // Attempt no subsequent state pushes where intents are involved.
5562 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005563 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005564
5565 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005566 }
5567
Robert Greenwalt8d482522015-06-24 13:23:42 -07005568 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005569 // The NetworkInfo we actually send out has no bearing on the real
5570 // state of affairs. For example, if the default connection is mobile,
5571 // and a request for HIPRI has just gone away, we need to pretend that
5572 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5573 // the state to DISCONNECTED, even though the network is of type MOBILE
5574 // and is still connected.
5575 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5576 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005577 if (state != DetailedState.DISCONNECTED) {
5578 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005579 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005580 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005581 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005582 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5583 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5584 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5585 if (info.isFailover()) {
5586 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5587 nai.networkInfo.setFailover(false);
5588 }
5589 if (info.getReason() != null) {
5590 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5591 }
5592 if (info.getExtraInfo() != null) {
5593 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5594 }
5595 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005596 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005597 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005598 if (newDefaultAgent != null) {
5599 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5600 newDefaultAgent.networkInfo);
5601 } else {
5602 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5603 }
5604 }
5605 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5606 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005607 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005608 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005609 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005610 }
5611 }
5612 }
5613
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005614 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005615 if (VDBG) {
5616 String notification = ConnectivityManager.getCallbackName(notifyType);
5617 log("notifyType " + notification + " for " + networkAgent.name());
5618 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005619 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5620 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005621 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5622 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005623 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5624 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005625 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005626 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005627 } else {
5628 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5629 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005630 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005631 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005632
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005633 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5634 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5635 }
5636
Jeff Sharkey69736342014-12-08 14:50:12 -08005637 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005638 * Returns the list of all interfaces that could be used by network traffic that does not
5639 * explicitly specify a network. This includes the default network, but also all VPNs that are
5640 * currently connected.
5641 *
5642 * Must be called on the handler thread.
5643 */
5644 private Network[] getDefaultNetworks() {
5645 ArrayList<Network> defaultNetworks = new ArrayList<>();
5646 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5647 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5648 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5649 defaultNetworks.add(nai.network);
5650 }
5651 }
5652 return defaultNetworks.toArray(new Network[0]);
5653 }
5654
5655 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005656 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5657 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005658 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005659 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005660 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005661 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005662 } catch (Exception ignored) {
5663 }
5664 }
5665
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005666 @Override
5667 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005668 int user = UserHandle.getUserId(Binder.getCallingUid());
5669 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005670 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005671 return mVpns.get(user).addAddress(address, prefixLength);
5672 }
5673 }
5674
5675 @Override
5676 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005677 int user = UserHandle.getUserId(Binder.getCallingUid());
5678 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005679 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005680 return mVpns.get(user).removeAddress(address, prefixLength);
5681 }
5682 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005683
5684 @Override
5685 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005686 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005687 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005688 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005689 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005690 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005691 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005692 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005693 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005694 }
5695 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005696 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005697
5698 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005699 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005700 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005701 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005702 }
5703
5704 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005705 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5706 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5707 enforceKeepalivePermission();
5708 mKeepaliveTracker.startNattKeepalive(
5709 getNetworkAgentInfoForNetwork(network),
5710 intervalSeconds, messenger, binder,
5711 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5712 }
5713
5714 @Override
5715 public void stopKeepalive(Network network, int slot) {
5716 mHandler.sendMessage(mHandler.obtainMessage(
5717 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5718 }
5719
5720 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005721 public void factoryReset() {
5722 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005723
5724 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5725 return;
5726 }
5727
Robin Lee3b3dd942015-05-12 18:14:58 +01005728 final int userId = UserHandle.getCallingUserId();
5729
Stuart Scottf1fb3972015-04-02 18:00:02 -07005730 // Turn airplane mode off
5731 setAirplaneMode(false);
5732
Stuart Scotte3e314d2015-04-20 14:07:45 -07005733 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5734 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005735 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005736 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005737 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005738 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005739 }
5740
Stuart Scotte3e314d2015-04-20 14:07:45 -07005741 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005742 // Remove always-on package
5743 synchronized (mVpns) {
5744 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5745 if (alwaysOnPackage != null) {
5746 setAlwaysOnVpnPackage(userId, null, false);
5747 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5748 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005749
Hugo Benichi69744342017-11-27 10:57:16 +09005750 // Turn Always-on VPN off
5751 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5752 final long ident = Binder.clearCallingIdentity();
5753 try {
5754 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5755 mLockdownEnabled = false;
5756 setLockdownTracker(null);
5757 } finally {
5758 Binder.restoreCallingIdentity(ident);
5759 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005760 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005761
Hugo Benichi69744342017-11-27 10:57:16 +09005762 // Turn VPN off
5763 VpnConfig vpnConfig = getVpnConfig(userId);
5764 if (vpnConfig != null) {
5765 if (vpnConfig.legacy) {
5766 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5767 } else {
5768 // Prevent this app (packagename = vpnConfig.user) from initiating
5769 // VPN connections in the future without user intervention.
5770 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005771
Hugo Benichi69744342017-11-27 10:57:16 +09005772 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5773 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005774 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005775 }
5776 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005777
5778 Settings.Global.putString(mContext.getContentResolver(),
5779 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005780 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005781
5782 @VisibleForTesting
5783 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5784 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5785 return new NetworkMonitor(context, handler, nai, defaultRequest);
5786 }
Erik Kline48f12f22016-04-14 17:30:59 +09005787
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005788 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005789 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5790 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005791 }
5792
5793 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005794 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5795 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5796 }
5797
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005798 @VisibleForTesting
5799 public boolean hasService(String name) {
5800 return ServiceManager.checkService(name) != null;
5801 }
5802
Hugo Benichi64901e52017-10-19 14:42:40 +09005803 @VisibleForTesting
5804 protected IpConnectivityMetrics.Logger metricsLogger() {
5805 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5806 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005807 }
5808
5809 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005810 int[] transports = nai.networkCapabilities.getTransportTypes();
5811 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005812 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005813
5814 private static boolean toBool(int encodedBoolean) {
5815 return encodedBoolean != 0; // Only 0 means false.
5816 }
5817
5818 private static int encodeBool(boolean b) {
5819 return b ? 1 : 0;
5820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821}