blob: 079d81559983eccf8095fdc02cb2809ca62d2a53 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Chalard Jeanb552c462018-02-21 18:43:54 +090020import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090023import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070024import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070025import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070026import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070027import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040028import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090030import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
32import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060033import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090034import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060037import static android.net.NetworkCapabilities.TRANSPORT_VPN;
38
Hugo Benichia0385682017-03-22 17:07:57 +090039import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060040
Wenchao Tongf5ea3402015-03-04 13:26:38 -080041import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080042import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090043import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070044import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070045import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.ContentResolver;
47import android.content.Context;
48import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070049import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070051import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090053import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
dalyk1fcb7392018-03-05 12:42:22 -050055import android.net.IIpConnectivityMetrics;
56import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070057import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070058import android.net.INetworkPolicyListener;
59import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070060import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080061import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070062import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010063import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070064import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070065import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070067import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070069import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070070import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090071import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070072import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070073import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070074import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070075import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070076import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000077import android.net.NetworkWatchlistManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070078import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040079import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070080import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040081import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040082import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060083import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090084import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090085import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090086import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080088import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070089import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040090import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070092import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070093import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070094import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Looper;
96import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070097import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070098import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090099import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700100import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700101import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700102import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800103import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900104import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900105import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700106import android.os.ShellCallback;
107import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900108import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700109import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400110import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700112import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700113import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700114import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700115import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900116import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700117import android.util.LocalLog;
118import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600119import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800120import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700121import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500122import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700123import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700124import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
Wink Savilleab9321d2013-06-29 21:10:57 -0700126import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400127import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400128import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700129import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700130import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700131import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700132import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800133import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700134import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700135import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600136import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700137import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900138import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900139import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700140import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700141import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400142import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900143import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900144import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
dalyk1fcb7392018-03-05 12:42:22 -0500145import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900146import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900147import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100148import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700149import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900150import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700151import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600152import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400153import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900154import com.android.server.connectivity.NetworkNotificationManager;
155import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400156import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700157import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800158import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700159import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100160import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk1fcb7392018-03-05 12:42:22 -0500161import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700162import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700163import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900164import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700165import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600166
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700167import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700168
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700169import org.xmlpull.v1.XmlPullParser;
170import org.xmlpull.v1.XmlPullParserException;
171
172import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700174import java.io.FileNotFoundException;
175import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700176import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700178import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700179import java.net.InetAddress;
180import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700181import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700182import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700183import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700184import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700185import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700186import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700187import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700188import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700189import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900190import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600191import java.util.SortedSet;
192import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194/**
195 * @hide
196 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800197public class ConnectivityService extends IConnectivityManager.Stub
198 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900199 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Erik Kline7747fd42017-05-12 16:52:48 +0900201 public static final String DIAG_ARG = "--diag";
202 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900203 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900204
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900205 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700206 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
Jake Hamby786e71a2014-02-06 14:43:50 -0800208 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900209 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210
Jeff Sharkey899223b2012-08-04 15:24:58 -0700211 // TODO: create better separation between radio types and network types
212
Robert Greenwalt42acef32009-08-12 16:08:25 -0700213 // how long to wait before switching back to a radio's default network
214 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
215 // system property that can override the above value
216 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
217 "android.telephony.apn-restore";
218
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900219 // How long to wait before putting up a "This network doesn't have an Internet connection,
220 // connect anyway?" dialog after the user selects a network that doesn't validate.
221 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
222
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900223 // Default to 30s linger time-out. Modifiable only for testing.
224 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
225 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
226 @VisibleForTesting
227 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
228
Jeremy Joslin79294842014-12-03 17:15:28 -0800229 // How long to delay to removal of a pending intent based request.
230 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
231 private final int mReleasePendingIntentDelayMs;
232
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900233 private MockableSystemProperties mSystemProperties;
234
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800235 private Tethering mTethering;
236
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700237 private final PermissionMonitor mPermissionMonitor;
238
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700239 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700240
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700241 @GuardedBy("mVpns")
242 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700243
Hugo Benichi69744342017-11-27 10:57:16 +0900244 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
245 // a direct call to LockdownVpnTracker.isEnabled().
246 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700247 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900248 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700249 private LockdownVpnTracker mLockdownTracker;
250
Erik Klineda4bfa82015-04-30 12:58:40 +0900251 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700253 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700254 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700257 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700259 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800260 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700261 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900262 private NetworkPolicyManagerInternal mPolicyManagerInternal;
dalyk1fcb7392018-03-05 12:42:22 -0500263 private IIpConnectivityMetrics mIpConnectivityMetrics;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700264
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700265 private String mCurrentTcpBufferSizes;
266
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700267 private static final int ENABLED = 1;
268 private static final int DISABLED = 0;
269
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900270 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900271 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
272 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900273
Paul Jensenb10e37f2014-11-25 12:33:08 -0500274 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400275 // Tear down networks that have no chance (e.g. even if validated) of becoming
276 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500277 // all networks have been rematched against all NetworkRequests.
278 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400279 // Don't reap networks. This should be passed when some networks have not yet been
280 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500281 DONT_REAP
282 };
283
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900284 private enum UnneededFor {
285 LINGER, // Determine whether this network is unneeded and should be lingered.
286 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
287 }
288
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700289 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700290 * used internally to change our mobile data enabled flag
291 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700292 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700293
294 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700295 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700296 * from one net to another. Clear happens when we get a new
297 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
298 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700299 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700300 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700301
Robert Greenwalt434203a2010-10-11 16:00:27 -0700302 /**
303 * used internally to reload global proxy settings
304 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700305 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700306
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700307 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400308 * PAC manager has received new port.
309 */
310 private static final int EVENT_PROXY_HAS_CHANGED = 16;
311
Robert Greenwalte049c232014-04-11 15:53:27 -0700312 /**
313 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700314 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700315 */
316 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
317
Robert Greenwalt7b816022014-04-18 15:25:25 -0700318 /**
319 * used internally when registering NetworkAgents
320 * obj = Messenger
321 */
322 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
323
Robert Greenwalt9258c642014-03-26 16:47:06 -0700324 /**
325 * used to add a network request
326 * includes a NetworkRequestInfo
327 */
328 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
329
330 /**
331 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900332 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700333 * cancel it.
334 * includes a NetworkRequestInfo
335 */
336 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
337
338 /**
339 * used to add a network listener - no request
340 * includes a NetworkRequestInfo
341 */
342 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
343
344 /**
345 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400346 * arg1 = UID of caller
347 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700348 */
349 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
350
Robert Greenwalta67be032014-05-16 15:49:14 -0700351 /**
352 * used internally when registering NetworkFactories
353 * obj = Messenger
354 */
355 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
356
Robert Greenwalt27711812014-06-25 16:45:57 -0700357 /**
358 * used internally to expire a wakelock when transitioning
359 * from one net to another. Expire happens when we fail to find
360 * a new network (typically after 1 minute) -
361 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
362 * a replacement network.
363 */
364 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
365
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700366 /**
367 * Used internally to indicate the system is ready.
368 */
369 private static final int EVENT_SYSTEM_READY = 25;
370
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800371 /**
372 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400373 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800374 */
375 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
376
377 /**
378 * used to remove a pending intent and its associated network request.
379 * arg1 = UID of caller
380 * obj = PendingIntent
381 */
382 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
383
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900384 /**
385 * used to specify whether a network should be used even if unvalidated.
386 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
387 * arg2 = whether to remember this choice in the future (1 or 0)
388 * obj = network
389 */
390 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
391
392 /**
393 * used to ask the user to confirm a connection to an unvalidated network.
394 * obj = network
395 */
396 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700397
Erik Klineda4bfa82015-04-30 12:58:40 +0900398 /**
399 * used internally to (re)configure mobile data always-on settings.
400 */
401 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
402
Paul Jensen694f2b82015-06-17 14:15:39 -0400403 /**
404 * used to add a network listener with a pending intent
405 * obj = NetworkRequestInfo
406 */
407 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
408
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900409 /**
410 * used to specify whether a network should not be penalized when it becomes unvalidated.
411 */
412 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
413
414 /**
415 * used to trigger revalidation of a network.
416 */
417 private static final int EVENT_REVALIDATE_NETWORK = 36;
418
Erik Klinea24d4592018-01-11 21:07:29 +0900419 // Handle changes in Private DNS settings.
420 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
421
dalyk1fcb7392018-03-05 12:42:22 -0500422 // Handle private DNS validation status updates.
423 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
424
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900425 private static String eventName(int what) {
426 return sMagicDecoderRing.get(what, Integer.toString(what));
427 }
428
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900429 /** Handler thread used for both of the handlers below. */
430 @VisibleForTesting
431 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700432 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700433 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700434 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700435 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900436 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700437
Mike Lockwood0f79b542009-08-14 14:18:49 -0400438 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800439 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400440
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700441 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700442 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800443 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700444
Robert Greenwalt434203a2010-10-11 16:00:27 -0700445 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400446 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700447 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700448 private boolean mDefaultProxyDisabled = false;
449
Robert Greenwalt434203a2010-10-11 16:00:27 -0700450 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400451 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700452
Jason Monk602b2322013-07-03 17:04:33 -0400453 private PacManager mPacManager = null;
454
Erik Klineda4bfa82015-04-30 12:58:40 +0900455 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700456
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400457 private UserManager mUserManager;
458
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700459 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700460 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700461
Robert Greenwalt50393202011-06-21 17:26:14 -0700462 // the set of network types that can only be enabled by system/sig apps
463 List mProtectedNetworks;
464
John Spurlockbf991a82013-06-24 14:20:23 -0400465 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700466
Wink Savilleab9321d2013-06-29 21:10:57 -0700467 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400468
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900469 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900470 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900471 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900472
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700473 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800474 private static final int MIN_NET_ID = 100; // some reserved marks
475 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700476 private int mNextNetId = MIN_NET_ID;
477
Robert Greenwalt34524f02014-05-18 16:22:10 -0700478 // sequence number of NetworkRequests
479 private int mNextNetworkRequestId = 1;
480
Erik Kline7523eb32015-07-09 18:24:03 +0900481 // NetworkRequest activity String log entries.
482 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
483 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
484
Hugo Benichic2ae2872016-07-11 11:05:12 +0900485 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900486 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900487 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
488
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900489 private static final int MAX_WAKELOCK_LOGS = 20;
490 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900491 private int mTotalWakelockAcquisitions = 0;
492 private int mTotalWakelockReleases = 0;
493 private long mTotalWakelockDurationMs = 0;
494 private long mMaxWakelockDurationMs = 0;
495 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900496
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700497 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
498 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400499 private static class ValidationLog {
500 final Network mNetwork;
501 final String mNetworkExtraInfo;
502 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700503
Paul Jensen0808eb82016-06-03 13:51:21 -0400504 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
505 mNetwork = network;
506 mNetworkExtraInfo = networkExtraInfo;
507 mLog = log;
508 }
509 }
510 private final ArrayDeque<ValidationLog> mValidationLogs =
511 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
512
513 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900514 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700515 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
516 mValidationLogs.removeLast();
517 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400518 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700519 }
520 }
521
Hugo Benichif9fdf872016-07-28 17:53:06 +0900522 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900523
Erik Kline065ab6e2016-10-02 18:02:14 +0900524 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900525 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900526
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900527 @VisibleForTesting
528 final MultipathPolicyTracker mMultipathPolicyTracker;
529
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700530 /**
531 * Implements support for the legacy "one network per network type" model.
532 *
533 * We used to have a static array of NetworkStateTrackers, one for each
534 * network type, but that doesn't work any more now that we can have,
535 * for example, more that one wifi network. This class stores all the
536 * NetworkAgentInfo objects that support a given type, but the legacy
537 * API will only see the first one.
538 *
539 * It serves two main purposes:
540 *
541 * 1. Provide information about "the network for a given type" (since this
542 * API only supports one).
543 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
544 * the first network for a given type changes, or if the default network
545 * changes.
546 */
547 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900548
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900549 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900550 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900551
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700552 /**
553 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
554 * Each list holds references to all NetworkAgentInfos that are used to
555 * satisfy requests for that network type.
556 *
557 * This array is built out at startup such that an unsupported network
558 * doesn't get an ArrayList instance, making this a tristate:
559 * unsupported, supported but not active and active.
560 *
561 * The actual lists are populated when we scan the network types that
562 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900563 *
564 * Threading model:
565 * - addSupportedType() is only called in the constructor
566 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
567 * They are therefore not thread-safe with respect to each other.
568 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
569 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
570 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700571 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900572 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700573
574 public LegacyTypeTracker() {
575 mTypeLists = (ArrayList<NetworkAgentInfo>[])
576 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
577 }
578
579 public void addSupportedType(int type) {
580 if (mTypeLists[type] != null) {
581 throw new IllegalStateException(
582 "legacy list for type " + type + "already initialized");
583 }
584 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
585 }
586
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700587 public boolean isTypeSupported(int type) {
588 return isNetworkTypeValid(type) && mTypeLists[type] != null;
589 }
590
591 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900592 synchronized (mTypeLists) {
593 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
594 return mTypeLists[type].get(0);
595 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900597 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700598 }
599
Robert Greenwalt8d482522015-06-24 13:23:42 -0700600 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900601 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900602 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700603 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900604 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900605 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606 }
607 }
608
609 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700610 public void add(int type, NetworkAgentInfo nai) {
611 if (!isTypeSupported(type)) {
612 return; // Invalid network type.
613 }
614 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
615
616 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
617 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700618 return;
619 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900620 synchronized (mTypeLists) {
621 list.add(nai);
622 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900623
624 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900625 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900626 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700627 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
628 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700629 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 }
631
Lorenzo Colittia793a672014-07-31 23:20:17 +0900632 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900633 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900634 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
635 if (list == null || list.isEmpty()) {
636 return;
637 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900638 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900639
Hugo Benichi78caa2582016-06-21 09:48:07 +0900640 synchronized (mTypeLists) {
641 if (!list.remove(nai)) {
642 return;
643 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900644 }
645
Robert Greenwalt8d482522015-06-24 13:23:42 -0700646 final DetailedState state = DetailedState.DISCONNECTED;
647
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900648 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700649 maybeLogBroadcast(nai, state, type, wasDefault);
650 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651 }
652
653 if (!list.isEmpty() && wasFirstNetwork) {
654 if (DBG) log("Other network available for type " + type +
655 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900656 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700657 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
658 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900659 }
660 }
661
662 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900663 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
664 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700665 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900666 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700667 }
668 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700669
Robert Greenwalt8d482522015-06-24 13:23:42 -0700670 // send out another legacy broadcast - currently only used for suspend/unsuspend
671 // toggle
672 public void update(NetworkAgentInfo nai) {
673 final boolean isDefault = isDefaultNetwork(nai);
674 final DetailedState state = nai.networkInfo.getDetailedState();
675 for (int type = 0; type < mTypeLists.length; type++) {
676 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700677 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900678 final boolean isFirst = contains && (nai == list.get(0));
679 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700680 maybeLogBroadcast(nai, state, type, isDefault);
681 sendLegacyNetworkBroadcast(nai, state, type);
682 }
683 }
684 }
685
Lorenzo Colittia793a672014-07-31 23:20:17 +0900686 private String naiToString(NetworkAgentInfo nai) {
687 String name = (nai != null) ? nai.name() : "null";
688 String state = (nai.networkInfo != null) ?
689 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
690 "???/???";
691 return name + " " + state;
692 }
693
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700694 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900695 pw.println("mLegacyTypeTracker:");
696 pw.increaseIndent();
697 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700698 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900699 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700700 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900701 pw.println();
702 pw.println("Current state:");
703 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900704 synchronized (mTypeLists) {
705 for (int type = 0; type < mTypeLists.length; type++) {
706 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
707 for (NetworkAgentInfo nai : mTypeLists[type]) {
708 pw.println(type + " " + naiToString(nai));
709 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900710 }
711 }
712 pw.decreaseIndent();
713 pw.decreaseIndent();
714 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700715 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700716 }
717 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
718
Vishnu Nair5c010902017-10-26 10:08:50 -0700719 /**
720 * Helper class which parses out priority arguments and dumps sections according to their
721 * priority. If priority arguments are omitted, function calls the legacy dump command.
722 */
723 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
724 @Override
725 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
726 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
727 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
728 }
729
730 @Override
731 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
732 doDump(fd, pw, args, asProto);
733 }
734
735 @Override
736 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
737 doDump(fd, pw, args, asProto);
738 }
739 };
740
Jeff Sharkey899223b2012-08-04 15:24:58 -0700741 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700742 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900743 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
744 }
745
746 @VisibleForTesting
747 protected ConnectivityService(Context context, INetworkManagementService netManager,
748 INetworkStatsService statsService, INetworkPolicyManager policyManager,
749 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800750 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800751
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900752 mSystemProperties = getSystemProperties();
753
Hugo Benichif9fdf872016-07-28 17:53:06 +0900754 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900755 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900756 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900757 mNetworkRequests.put(mDefaultRequest, defaultNRI);
758 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900759
Chalard Jeandda156a2018-01-10 21:19:32 +0900760 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900761 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700762
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900763 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900764 mHandlerThread.start();
765 mHandler = new InternalHandler(mHandlerThread.getLooper());
766 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700767
Jeremy Joslin79294842014-12-03 17:15:28 -0800768 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
769 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
770
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900771 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900772
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700773 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700774 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800775 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700776 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900777 mPolicyManagerInternal = checkNotNull(
778 LocalServices.getService(NetworkPolicyManagerInternal.class),
779 "missing NetworkPolicyManagerInternal");
780
Jeff Sharkey82f85212012-08-24 11:17:25 -0700781 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700782 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700783
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700784 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900785 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700786 } catch (RemoteException e) {
787 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700788 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700789 }
790
791 final PowerManager powerManager = (PowerManager) context.getSystemService(
792 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700793 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
794 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
795 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800796 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700797
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700798 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700799
Wink Saville51f456f2013-04-23 14:26:51 -0700800 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900801 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700802 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700803 String[] naStrings = context.getResources().getStringArray(
804 com.android.internal.R.array.networkAttributes);
805 for (String naString : naStrings) {
806 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700807 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700808 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700809 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800810 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700811 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700812 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700813 }
Wink Saville51f456f2013-04-23 14:26:51 -0700814 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
815 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
816 n.type);
817 continue;
818 }
Wink Saville975c8482011-04-07 14:23:45 -0700819 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800820 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700821 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700822 continue;
823 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700824 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700825
Wink Saville975c8482011-04-07 14:23:45 -0700826 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700827 mNetworksDefined++;
828 } catch(Exception e) {
829 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700830 }
831 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700832
833 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
834 if (mNetConfigs[TYPE_VPN] == null) {
835 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
836 // don't need to add TYPE_VPN to mNetConfigs.
837 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
838 mNetworksDefined++; // used only in the log() statement below.
839 }
840
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900841 // Do the same for Ethernet, since it's often not specified in the configs, although many
842 // devices can use it via USB host adapters.
843 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
844 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
845 mNetworksDefined++;
846 }
847
Wink Saville5e56bc52013-07-29 15:00:57 -0700848 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700849
Robert Greenwalt50393202011-06-21 17:26:14 -0700850 mProtectedNetworks = new ArrayList<Integer>();
851 int[] protectedNetworks = context.getResources().getIntArray(
852 com.android.internal.R.array.config_protectedNetworks);
853 for (int p : protectedNetworks) {
854 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
855 mProtectedNetworks.add(p);
856 } else {
857 if (DBG) loge("Ignoring protectedNetwork " + p);
858 }
859 }
860
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900861 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
862 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700863
Erik Kline47222fc2017-04-30 19:36:15 +0900864 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800865
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700866 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
867
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700868 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700869 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100870 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700871 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700872 intentFilter.addAction(Intent.ACTION_USER_ADDED);
873 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000874 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700875 mContext.registerReceiverAsUser(
876 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000877 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
878 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900879
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700880 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700881 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700882 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700883 } catch (RemoteException e) {
884 loge("Error registering observer :" + e);
885 }
886
Erik Klineda4bfa82015-04-30 12:58:40 +0900887 mSettingsObserver = new SettingsObserver(mContext, mHandler);
888 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800889
John Spurlockbf991a82013-06-24 14:20:23 -0400890 mDataConnectionStats = new DataConnectionStats(mContext);
891 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400892
Jason Monkdecd2952013-10-10 14:02:51 -0400893 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700894
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400895 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900896
897 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900898 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
899 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900900
901 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
902 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
903 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
904 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
905 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
906 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
907 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900908
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900909 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900910 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900911 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900912
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900913 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
914
Erik Kline1742fe12017-12-13 19:40:49 +0900915 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900916 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700918
Erik Kline47222fc2017-04-30 19:36:15 +0900919 private Tethering makeTethering() {
920 // TODO: Move other elements into @Overridden getters.
Erik Kline7a26ba32018-03-09 14:18:02 +0900921 final TetheringDependencies deps = new TetheringDependencies() {
922 @Override
923 public boolean isTetheringSupported() {
924 return ConnectivityService.this.isTetheringSupported();
925 }
926 };
Erik Kline47222fc2017-04-30 19:36:15 +0900927 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
928 IoThread.get().getLooper(), new MockableSystemProperties(),
929 deps);
930 }
931
Chalard Jeandda156a2018-01-10 21:19:32 +0900932 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900933 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900934 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900935 netCap.addCapability(NET_CAPABILITY_INTERNET);
936 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900937 if (transportType > -1) {
938 netCap.addTransportType(transportType);
939 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900940 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900941 }
942
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900943 // Used only for testing.
944 // TODO: Delete this and either:
Erik Kline79c6d052018-03-21 07:18:33 -0700945 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900946 // changing ContentResolver to make registerContentObserver non-final).
947 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
948 // by subclassing SettingsObserver.
949 @VisibleForTesting
950 void updateMobileDataAlwaysOn() {
951 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
952 }
953
Erik Kline79c6d052018-03-21 07:18:33 -0700954 // See FakeSettingsProvider comment above.
955 @VisibleForTesting
956 void updatePrivateDnsSettings() {
957 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
958 }
959
Erik Klineda4bfa82015-04-30 12:58:40 +0900960 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900961 final boolean enable = toBool(Settings.Global.getInt(
962 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900963 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
964 if (enable == isEnabled) {
965 return; // Nothing to do.
966 }
967
968 if (enable) {
969 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900970 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900971 } else {
972 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
973 }
974 }
975
976 private void registerSettingsCallbacks() {
977 // Watch for global HTTP proxy changes.
978 mSettingsObserver.observe(
979 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
980 EVENT_APPLY_GLOBAL_HTTP_PROXY);
981
982 // Watch for whether or not to keep mobile data always on.
983 mSettingsObserver.observe(
984 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
985 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
986 }
987
Erik Klinea24d4592018-01-11 21:07:29 +0900988 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline79c6d052018-03-21 07:18:33 -0700989 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
990 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +0900991 }
992 }
993
Robert Greenwalt34524f02014-05-18 16:22:10 -0700994 private synchronized int nextNetworkRequestId() {
995 return mNextNetworkRequestId++;
996 }
997
Paul Jensen67b0b072015-06-10 11:22:17 -0400998 @VisibleForTesting
999 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001000 synchronized (mNetworkForNetId) {
1001 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1002 int netId = mNextNetId;
1003 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1004 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001005 if (!mNetIdInUse.get(netId)) {
1006 mNetIdInUse.put(netId, true);
1007 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001008 }
1009 }
1010 }
1011 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001012 }
1013
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001014 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001016 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1017 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001019 state = nai.getNetworkState();
1020 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001021 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001022 final NetworkInfo info = new NetworkInfo(networkType, 0,
1023 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001024 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1025 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001026 final NetworkCapabilities capabilities = new NetworkCapabilities();
1027 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1028 !info.isRoaming());
1029 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001030 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001031 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001032 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001033 return state;
1034 } else {
1035 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001036 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001037 }
1038
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001039 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1040 if (network == null) {
1041 return null;
1042 }
Erik Kline79c6d052018-03-21 07:18:33 -07001043 return getNetworkAgentInfoForNetId(network.netId);
1044 }
1045
1046 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 synchronized (mNetworkForNetId) {
Erik Kline79c6d052018-03-21 07:18:33 -07001048 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001049 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001050 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001051
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001052 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001053 synchronized (mVpns) {
1054 if (!mLockdownEnabled) {
1055 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001056 Vpn vpn = mVpns.get(user);
1057 if (vpn != null && vpn.appliesToUid(uid)) {
1058 return vpn.getUnderlyingNetworks();
1059 }
1060 }
1061 }
1062 return null;
1063 }
1064
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001065 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001066 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001067
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001068 final Network[] networks = getVpnUnderlyingNetworks(uid);
1069 if (networks != null) {
1070 // getUnderlyingNetworks() returns:
1071 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1072 // empty array => the VPN explicitly said "no default network".
1073 // non-empty array => the VPN specified one or more default networks; we use the
1074 // first one.
1075 if (networks.length > 0) {
1076 nai = getNetworkAgentInfoForNetwork(networks[0]);
1077 } else {
1078 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001079 }
1080 }
1081
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001082 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001083 return nai.getNetworkState();
1084 } else {
1085 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001086 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001087 }
1088
1089 /**
1090 * Check if UID should be blocked from using the network with the given LinkProperties.
1091 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001092 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1093 boolean ignoreBlocked) {
1094 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001095 if (ignoreBlocked) {
1096 return false;
1097 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001098 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001099 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1100 if (isSystem(uid)) {
1101 return false;
1102 }
Robin Lee17e61832016-05-09 13:46:28 +01001103 synchronized (mVpns) {
1104 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1105 if (vpn != null && vpn.isBlockingUid(uid)) {
1106 return true;
1107 }
1108 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001109 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001110 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001111 }
1112
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001113 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001114 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1115 return;
1116 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001117 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001118 synchronized (mBlockedAppUids) {
1119 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001120 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001121 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001122 blocked = false;
1123 } else {
1124 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001125 }
1126 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001127 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1128 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1129 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001130 }
1131
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001132 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001133 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1134 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001135 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001136 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001137 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001138 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1139
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001140 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001141 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001142 }
Hugo Benichi69744342017-11-27 10:57:16 +09001143 synchronized (mVpns) {
1144 if (mLockdownTracker != null) {
1145 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1146 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001147 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001148 }
1149
1150 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 * Return NetworkInfo for the active (i.e., connected) network interface.
1152 * It is assumed that at most one network is active at a time. If more
1153 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001154 * @return the info for the active network, or {@code null} if none is
1155 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 enforceAccessPermission();
1160 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001161 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001162 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001163 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1164 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
1166
Paul Jensen31a94f42015-02-13 14:18:39 -05001167 @Override
1168 public Network getActiveNetwork() {
1169 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001170 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001171 }
1172
1173 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001174 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001175 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001176 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001177 }
1178
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001179 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001180 final int user = UserHandle.getUserId(uid);
1181 int vpnNetId = NETID_UNSET;
1182 synchronized (mVpns) {
1183 final Vpn vpn = mVpns.get(user);
1184 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1185 }
1186 NetworkAgentInfo nai;
1187 if (vpnNetId != NETID_UNSET) {
Erik Kline79c6d052018-03-21 07:18:33 -07001188 nai = getNetworkAgentInfoForNetId(vpnNetId);
Paul Jensen31a94f42015-02-13 14:18:39 -05001189 if (nai != null) return nai.network;
1190 }
1191 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001192 if (nai != null
1193 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1194 nai = null;
1195 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001196 return nai != null ? nai.network : null;
1197 }
1198
Lorenzo Colitti18660282016-07-04 12:55:44 +09001199 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001200 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1201 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001202 final int uid = Binder.getCallingUid();
1203 NetworkState state = getUnfilteredActiveNetworkState(uid);
1204 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001205 }
1206
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001207 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001208 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001209 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001210 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001211 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001212 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001213 }
1214
1215 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 public NetworkInfo getNetworkInfo(int networkType) {
1217 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001218 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001219 if (getVpnUnderlyingNetworks(uid) != null) {
1220 // A VPN is active, so we may need to return one of its underlying networks. This
1221 // information is not available in LegacyTypeTracker, so we have to get it from
1222 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001223 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001224 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001225 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001226 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001227 }
1228 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001229 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001230 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
1232
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001233 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001234 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001235 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001236 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001237 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001238 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001239 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001240 return state.networkInfo;
1241 } else {
1242 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001243 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001244 }
1245
1246 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 public NetworkInfo[] getAllNetworkInfo() {
1248 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001249 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001250 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1251 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001252 NetworkInfo info = getNetworkInfo(networkType);
1253 if (info != null) {
1254 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001257 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 }
1259
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001260 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001261 public Network getNetworkForType(int networkType) {
1262 enforceAccessPermission();
1263 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001264 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1265 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001266 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001267 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001268 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001269 }
1270
1271 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001272 public Network[] getAllNetworks() {
1273 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001274 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001275 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001276 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001277 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001278 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001279 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001280 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001281 }
1282
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001283 @Override
1284 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1285 // The basic principle is: if an app's traffic could possibly go over a
1286 // network, without the app doing anything multinetwork-specific,
1287 // (hence, by "default"), then include that network's capabilities in
1288 // the array.
1289 //
1290 // In the normal case, app traffic only goes over the system's default
1291 // network connection, so that's the only network returned.
1292 //
1293 // With a VPN in force, some app traffic may go into the VPN, and thus
1294 // over whatever underlying networks the VPN specifies, while other app
1295 // traffic may go over the system default network (e.g.: a split-tunnel
1296 // VPN, or an app disallowed by the VPN), so the set of networks
1297 // returned includes the VPN's underlying networks and the system
1298 // default.
1299 enforceAccessPermission();
1300
1301 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1302
1303 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001304 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001305 if (nc != null) {
1306 result.put(nai.network, nc);
1307 }
1308
Hugo Benichi69744342017-11-27 10:57:16 +09001309 synchronized (mVpns) {
1310 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001311 Vpn vpn = mVpns.get(userId);
1312 if (vpn != null) {
1313 Network[] networks = vpn.getUnderlyingNetworks();
1314 if (networks != null) {
1315 for (Network network : networks) {
1316 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001317 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001318 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001319 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001320 }
1321 }
1322 }
1323 }
1324 }
1325 }
1326
1327 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1328 out = result.values().toArray(out);
1329 return out;
1330 }
1331
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001332 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001333 public boolean isNetworkSupported(int networkType) {
1334 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001335 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001336 }
1337
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001338 /**
1339 * Return LinkProperties for the active (i.e., connected) default
1340 * network interface. It is assumed that at most one default network
1341 * is active at a time. If more than one is active, it is indeterminate
1342 * which will be returned.
1343 * @return the ip properties for the active network, or {@code null} if
1344 * none is active
1345 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001346 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001347 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001348 enforceAccessPermission();
1349 final int uid = Binder.getCallingUid();
1350 NetworkState state = getUnfilteredActiveNetworkState(uid);
1351 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001352 }
1353
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001354 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001355 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001356 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001357 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1358 if (nai != null) {
1359 synchronized (nai) {
1360 return new LinkProperties(nai.linkProperties);
1361 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001362 }
1363 return null;
1364 }
1365
Robert Greenwalt12e67352014-05-13 21:41:06 -07001366 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001367 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001368 public LinkProperties getLinkProperties(Network network) {
1369 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001370 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1371 }
1372
1373 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1374 if (nai == null) {
1375 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001376 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001377 synchronized (nai) {
1378 return new LinkProperties(nai.linkProperties);
1379 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001380 }
1381
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001382 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001383 if (nai != null) {
1384 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001385 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001386 return networkCapabilitiesRestrictedForCallerPermissions(
1387 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001388 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001389 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001390 }
1391 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001392 return null;
1393 }
1394
1395 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001396 public NetworkCapabilities getNetworkCapabilities(Network network) {
1397 enforceAccessPermission();
1398 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1399 }
1400
Chalard Jeanb03a6222018-04-11 21:09:10 +09001401 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001402 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001403 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
1404 if (!checkSettingsPermission(callerPid, callerUid)) newNc.setUids(null);
1405 if (!checkNetworkStackPermission(callerPid, callerUid)) newNc.setSSID(null);
1406 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001407 }
1408
Chalard Jeanb552c462018-02-21 18:43:54 +09001409 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1410 if (!checkSettingsPermission()) {
1411 nc.setSingleUid(Binder.getCallingUid());
1412 }
1413 }
1414
Chalard Jean26aa91a2018-03-20 19:13:57 +09001415 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1416 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1417 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1418 }
1419 }
1420
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001421 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001422 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001423 // Require internal since we're handing out IMSI details
1424 enforceConnectivityInternalPermission();
1425
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001426 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001427 for (Network network : getAllNetworks()) {
1428 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1429 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001430 // TODO (b/73321673) : NetworkState contains a copy of the
1431 // NetworkCapabilities, which may contain UIDs of apps to which the
1432 // network applies. Should the UIDs be cleared so as not to leak or
1433 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001434 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001435 }
1436 }
1437 return result.toArray(new NetworkState[result.size()]);
1438 }
1439
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001440 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001441 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001442 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001443 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1444 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1445 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001446 }
1447
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001448 @Override
1449 public boolean isActiveNetworkMetered() {
1450 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001451
Eric Enslenc81ef192018-02-07 18:03:53 -08001452 final int uid = Binder.getCallingUid();
1453 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001454 if (caps != null) {
1455 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1456 } else {
1457 // Always return the most conservative value
1458 return true;
1459 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001460 }
1461
Jeff Sharkey216c1812012-08-05 14:29:23 -07001462 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1463 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001464 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001465 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001466 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001467 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001468 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001469
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001470 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 * Ensure that a network route exists to deliver traffic to the specified
1472 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001473 * @param networkType the type of the network over which traffic to the
1474 * specified host is to be routed
1475 * @param hostAddress the IP address of the host to which the route is
1476 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 * @return {@code true} on success, {@code false} on failure
1478 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001479 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001480 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001482 if (mProtectedNetworks.contains(networkType)) {
1483 enforceConnectivityInternalPermission();
1484 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001485
Chad Brubakerc0234532014-02-14 13:24:29 -08001486 InetAddress addr;
1487 try {
1488 addr = InetAddress.getByAddress(hostAddress);
1489 } catch (UnknownHostException e) {
1490 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1491 return false;
1492 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001495 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 return false;
1497 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001498
1499 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1500 if (nai == null) {
1501 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1502 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1503 } else {
1504 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1505 }
1506 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001507 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001508
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001509 DetailedState netState;
1510 synchronized (nai) {
1511 netState = nai.networkInfo.getDetailedState();
1512 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001513
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001514 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001515 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001516 log("requestRouteToHostAddress on down network "
1517 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001518 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001519 }
1520 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001522
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001523 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001524 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001525 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001526 LinkProperties lp;
1527 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001528 synchronized (nai) {
1529 lp = nai.linkProperties;
1530 netId = nai.network.netId;
1531 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001532 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001533 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1534 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001535 } finally {
1536 Binder.restoreCallingIdentity(token);
1537 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001538 }
1539
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001540 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001541 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001542 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001543 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001544 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001545 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001546 if (bestRoute.getGateway().equals(addr)) {
1547 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001548 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001549 } else {
1550 // if we will connect to this through another route, add a direct route
1551 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001552 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001553 }
1554 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001555 if (DBG) log("Adding legacy route " + bestRoute +
1556 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001557 try {
1558 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1559 } catch (Exception e) {
1560 // never crash - catch them all
1561 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001562 return false;
1563 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001564 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
1566
dalyk1fcb7392018-03-05 12:42:22 -05001567 @VisibleForTesting
1568 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1569 @Override
1570 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1571 String hostname, boolean validated) {
1572 try {
1573 mHandler.sendMessage(mHandler.obtainMessage(
1574 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1575 new PrivateDnsValidationUpdate(netId,
1576 InetAddress.parseNumericAddress(ipAddress),
1577 hostname, validated)));
1578 } catch (IllegalArgumentException e) {
1579 loge("Error parsing ip address in validation event");
1580 }
1581 }
1582 };
1583
1584 @VisibleForTesting
1585 protected void registerNetdEventCallback() {
1586 mIpConnectivityMetrics =
1587 (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1588 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1589 if (mIpConnectivityMetrics == null) {
1590 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
1591 }
1592
1593 try {
1594 mIpConnectivityMetrics.addNetdEventCallback(
1595 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1596 mNetdEventCallback);
1597 } catch (Exception e) {
1598 loge("Error registering netd callback: " + e);
1599 }
1600 }
1601
Jeff Sharkey75d31892018-01-18 22:01:59 +09001602 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001603 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001604 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001605 // TODO: notify UID when it has requested targeted updates
1606 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001607 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001608 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001609 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001610 if (restrictBackground) {
1611 log("onRestrictBackgroundChanged(true): disabling tethering");
1612 mTethering.untetherAll();
1613 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001614 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001615 };
1616
Robin Lee3b3dd942015-05-12 18:14:58 +01001617 /**
1618 * Require that the caller is either in the same user or has appropriate permission to interact
1619 * across users.
1620 *
1621 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1622 */
1623 private void enforceCrossUserPermission(int userId) {
1624 if (userId == UserHandle.getCallingUserId()) {
1625 // Not a cross-user call.
1626 return;
1627 }
1628 mContext.enforceCallingOrSelfPermission(
1629 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1630 "ConnectivityService");
1631 }
1632
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001633 private void enforceInternetPermission() {
1634 mContext.enforceCallingOrSelfPermission(
1635 android.Manifest.permission.INTERNET,
1636 "ConnectivityService");
1637 }
1638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001640 mContext.enforceCallingOrSelfPermission(
1641 android.Manifest.permission.ACCESS_NETWORK_STATE,
1642 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644
1645 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001646 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
1648
Charles He36738632017-05-15 17:07:18 +01001649 private void enforceSettingsPermission() {
1650 mContext.enforceCallingOrSelfPermission(
1651 android.Manifest.permission.NETWORK_SETTINGS,
1652 "ConnectivityService");
1653 }
1654
Chalard Jeanb552c462018-02-21 18:43:54 +09001655 private boolean checkSettingsPermission() {
1656 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1657 android.Manifest.permission.NETWORK_SETTINGS);
1658 }
1659
1660 private boolean checkSettingsPermission(int pid, int uid) {
1661 return PERMISSION_GRANTED == mContext.checkPermission(
1662 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1663 }
1664
Chalard Jeanb03a6222018-04-11 21:09:10 +09001665 private boolean checkNetworkStackPermission(int pid, int uid) {
1666 return PERMISSION_GRANTED == mContext.checkPermission(
1667 android.Manifest.permission.NETWORK_STACK, pid, uid);
1668 }
1669
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001670 private void enforceTetherAccessPermission() {
1671 mContext.enforceCallingOrSelfPermission(
1672 android.Manifest.permission.ACCESS_NETWORK_STATE,
1673 "ConnectivityService");
1674 }
1675
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001676 private void enforceConnectivityInternalPermission() {
1677 mContext.enforceCallingOrSelfPermission(
1678 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1679 "ConnectivityService");
1680 }
1681
Hugo Benichi514da602016-07-19 15:59:27 +09001682 private void enforceConnectivityRestrictedNetworksPermission() {
1683 try {
1684 mContext.enforceCallingOrSelfPermission(
1685 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1686 "ConnectivityService");
1687 return;
1688 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1689 enforceConnectivityInternalPermission();
1690 }
1691
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001692 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001693 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001694 }
1695
Lorenzo Colitti18660282016-07-04 12:55:44 +09001696 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001697 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001698 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001699 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001700 }
1701
1702 private void sendInetConditionBroadcast(NetworkInfo info) {
1703 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1704 }
1705
Wink Saville628b0852011-08-04 15:01:58 -07001706 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001707 synchronized (mVpns) {
1708 if (mLockdownTracker != null) {
1709 info = new NetworkInfo(info);
1710 mLockdownTracker.augmentNetworkInfo(info);
1711 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001712 }
1713
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001714 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001715 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001716 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 if (info.isFailover()) {
1718 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1719 info.setFailover(false);
1720 }
1721 if (info.getReason() != null) {
1722 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1723 }
1724 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001725 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1726 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001728 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001729 return intent;
1730 }
1731
1732 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1733 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1734 }
1735
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001736 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001737 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1738 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1739 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001740 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001741 final long ident = Binder.clearCallingIdentity();
1742 try {
1743 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1744 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1745 } finally {
1746 Binder.restoreCallingIdentity(ident);
1747 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001748 }
1749
Mike Lockwood0f79b542009-08-14 14:18:49 -04001750 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001751 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001752 if (!mSystemReady) {
1753 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001754 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001755 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001756 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001757 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001758 }
1759
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001760 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001761 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001762 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001763 final NetworkInfo ni = intent.getParcelableExtra(
1764 ConnectivityManager.EXTRA_NETWORK_INFO);
1765 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1766 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1767 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001768 } else {
1769 BroadcastOptions opts = BroadcastOptions.makeBasic();
1770 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1771 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001772 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001773 final IBatteryStats bs = BatteryStatsService.getService();
1774 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001775 bs.noteConnectivityChanged(intent.getIntExtra(
1776 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1777 ni != null ? ni.getState().toString() : "?");
1778 } catch (RemoteException e) {
1779 }
Chad Brubakerac925012018-03-08 10:37:09 -08001780 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001781 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001782 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001783 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001784 } finally {
1785 Binder.restoreCallingIdentity(ident);
1786 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001787 }
1788 }
1789
1790 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001791 loadGlobalProxy();
dalyk1fcb7392018-03-05 12:42:22 -05001792 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001793
Hugo Benichi20035e02017-04-26 14:53:28 +09001794 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001795 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001796 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001797 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001798 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001799 }
1800 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001801 // load the global proxy at startup
1802 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001803
Robin Lee244ce8e2016-01-05 18:03:46 +00001804 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1805 // for user to unlock device too.
1806 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001807
Erik Klineda4bfa82015-04-30 12:58:40 +09001808 // Configure whether mobile data is always on.
1809 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1810
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001811 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001812
1813 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 }
1815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001817 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001818 *
1819 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001820 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001821 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001822 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1823 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001824
1825 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001826 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001827
Robert Greenwalt7b816022014-04-18 15:25:25 -07001828 if (networkAgent.networkCapabilities.hasTransport(
1829 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001830 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1831 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001832 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001833 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001834 } else if (networkAgent.networkCapabilities.hasTransport(
1835 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001836 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1837 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001838 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001839 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001840 } else {
1841 // do not track any other networks
1842 timeout = 0;
1843 }
1844
Robert Greenwalt7b816022014-04-18 15:25:25 -07001845 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001846 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001847 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001848 } catch (Exception e) {
1849 // You shall not crash!
1850 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001851 }
1852 }
1853 }
1854
1855 /**
1856 * Remove data activity tracking when network disconnects.
1857 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001858 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1859 final String iface = networkAgent.linkProperties.getInterfaceName();
1860 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001861
Robert Greenwalt7b816022014-04-18 15:25:25 -07001862 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1863 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001864 try {
1865 // the call fails silently if no idletimer setup for this interface
1866 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001867 } catch (Exception e) {
1868 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001869 }
1870 }
1871 }
1872
1873 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001874 * Reads the network specific MTU size from reources.
1875 * and set it on it's iface.
1876 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001877 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1878 final String iface = newLp.getInterfaceName();
1879 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001880 if (oldLp == null && mtu == 0) {
1881 // Silently ignore unset MTU value.
1882 return;
1883 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001884 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1885 if (VDBG) log("identical MTU - not setting");
1886 return;
1887 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001888 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001889 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001890 return;
1891 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001892
w1997615afd812014-08-05 15:18:11 -07001893 // Cannot set MTU without interface name
1894 if (TextUtils.isEmpty(iface)) {
1895 loge("Setting MTU size with null iface.");
1896 return;
1897 }
1898
Robert Greenwalt7b816022014-04-18 15:25:25 -07001899 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001900 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001901 mNetd.setMtu(iface, mtu);
1902 } catch (Exception e) {
1903 Slog.e(TAG, "exception in setMtu()" + e);
1904 }
1905 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001906
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001907 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001908 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1909
1910 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001911 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001912 protected MockableSystemProperties getSystemProperties() {
1913 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001914 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001915
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001916 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1917 if (isDefaultNetwork(nai) == false) {
1918 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001919 }
1920
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001921 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1922 String[] values = null;
1923 if (tcpBufferSizes != null) {
1924 values = tcpBufferSizes.split(",");
1925 }
1926
1927 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001928 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001929 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1930 values = tcpBufferSizes.split(",");
1931 }
1932
1933 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1934
1935 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001936 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001937
1938 final String prefix = "/sys/kernel/ipv4/tcp_";
1939 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1940 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1941 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1942 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1943 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1944 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1945 mCurrentTcpBufferSizes = tcpBufferSizes;
1946 } catch (IOException e) {
1947 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001948 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001949
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001950 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001951 Settings.Global.TCP_DEFAULT_INIT_RWND,
1952 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001953 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1954 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001955 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001956 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001957 }
1958
Robert Greenwalt562cc542014-05-15 18:07:26 -07001959 @Override
1960 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001961 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001962 NETWORK_RESTORE_DELAY_PROP_NAME);
1963 if(restoreDefaultNetworkDelayStr != null &&
1964 restoreDefaultNetworkDelayStr.length() != 0) {
1965 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001966 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001967 } catch (NumberFormatException e) {
1968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001970 // if the system property isn't set, use the value for the apn type
1971 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1972
1973 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1974 (mNetConfigs[networkType] != null)) {
1975 ret = mNetConfigs[networkType].restoreTime;
1976 }
1977 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001980 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001981 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001982 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001983 }
1984 return false;
1985 }
1986
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001987 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1988 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1989 final long DIAG_TIME_MS = 5000;
1990 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1991 // Start gathering diagnostic information.
1992 netDiags.add(new NetworkDiagnostics(
1993 nai.network,
1994 new LinkProperties(nai.linkProperties), // Must be a copy.
1995 DIAG_TIME_MS));
1996 }
1997
1998 for (NetworkDiagnostics netDiag : netDiags) {
1999 pw.println();
2000 netDiag.waitForMeasurements();
2001 netDiag.dump(pw);
2002 }
2003 }
2004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002006 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002007 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2008 }
2009
2010 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002011 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002012 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002013 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002014
Erik Kline7747fd42017-05-12 16:52:48 +09002015 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002016 dumpNetworkDiagnostics(pw);
2017 return;
Erik Klineee363c42017-05-29 09:11:03 +09002018 } else if (argsContain(args, TETHERING_ARG)) {
2019 mTethering.dump(fd, pw, args);
2020 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002021 }
Erik Kline379747a2015-06-05 17:47:34 +09002022
Lorenzo Colittie3805462015-06-03 11:18:24 +09002023 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002024 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002025 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002026 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002027 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002028 pw.println();
2029
Paul Jensen85cf78e2015-06-25 13:25:07 -04002030 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002031 pw.print("Active default network: ");
2032 if (defaultNai == null) {
2033 pw.println("none");
2034 } else {
2035 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002037 pw.println();
2038
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002039 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002040 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002041 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2042 pw.println(nai.toString());
2043 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002044 pw.println(String.format(
2045 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2046 nai.numForegroundNetworkRequests(),
2047 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2048 nai.numBackgroundNetworkRequests(),
2049 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002050 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002051 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2052 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002053 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002054 pw.decreaseIndent();
2055 pw.println("Lingered:");
2056 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002057 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002058 pw.decreaseIndent();
2059 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002060 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002061 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002062 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002063
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002064 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002065 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002066 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2067 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002068 }
2069 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002070 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002071
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002072 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002073
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002074 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002075 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002076
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002077 pw.println();
2078 mKeepaliveTracker.dump(pw);
2079
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002080 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002081 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002082
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002083 pw.println();
2084 mMultipathPolicyTracker.dump(pw);
2085
Erik Kline7747fd42017-05-12 16:52:48 +09002086 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002087 pw.println();
2088 synchronized (mValidationLogs) {
2089 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002090 for (ValidationLog p : mValidationLogs) {
2091 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002092 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002093 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002094 pw.decreaseIndent();
2095 }
2096 }
Erik Kline7523eb32015-07-09 18:24:03 +09002097
2098 pw.println();
2099 pw.println("mNetworkRequestInfoLogs (most recent first):");
2100 pw.increaseIndent();
2101 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2102 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002103
2104 pw.println();
2105 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2106 pw.increaseIndent();
2107 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2108 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002109
2110 pw.println();
2111 pw.println("NetTransition WakeLock activity (most recent first):");
2112 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002113 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2114 pw.println("total releases: " + mTotalWakelockReleases);
2115 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2116 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2117 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2118 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2119 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2120 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002121 mWakelockLogs.reverseDump(fd, pw, args);
2122 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 }
2125
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002126 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002127 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002128 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002129 if (officialNai != null && officialNai.equals(nai)) return true;
2130 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002131 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002132 " - " + nai);
2133 }
2134 return false;
2135 }
2136
Robert Greenwalt42acef32009-08-12 16:08:25 -07002137 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002138 private class NetworkStateTrackerHandler extends Handler {
2139 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002140 super(looper);
2141 }
2142
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002143 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002145 default:
2146 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002147 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002148 handleAsyncChannelHalfConnect(msg);
2149 break;
2150 }
2151 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2152 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2153 if (nai != null) nai.asyncChannel.disconnect();
2154 break;
2155 }
2156 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2157 handleAsyncChannelDisconnected(msg);
2158 break;
2159 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002160 }
2161 return true;
2162 }
2163
2164 private void maybeHandleNetworkAgentMessage(Message msg) {
2165 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2166 if (nai == null) {
2167 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002168 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002169 }
2170 return;
2171 }
2172
2173 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002174 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002175 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2176 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002177 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2178 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002179 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002180 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002181 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002182 break;
2183 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002184 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002185 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002186 break;
2187 }
2188 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002189 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002190 updateNetworkInfo(nai, info);
2191 break;
2192 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002193 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002194 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002195 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002196 break;
2197 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002198 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002199 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2200 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002201 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002202 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002203 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002204 break;
2205 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002206 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002207 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2208 break;
2209 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002210 }
2211 }
2212
2213 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2214 switch (msg.what) {
2215 default:
2216 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002217 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002218 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002219 if (nai == null) break;
2220
2221 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2222 final boolean wasValidated = nai.lastValidated;
2223 final boolean wasDefault = isDefaultNetwork(nai);
2224
Erik Klinea24d4592018-01-11 21:07:29 +09002225 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2226
Erik Klinea24d4592018-01-11 21:07:29 +09002227 if (DBG) {
Erik Kline79c6d052018-03-21 07:18:33 -07002228 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2229 ? " with redirect to " + redirectUrl
2230 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002231 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2232 }
Erik Klinea24d4592018-01-11 21:07:29 +09002233 if (valid != nai.lastValidated) {
2234 if (wasDefault) {
2235 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2236 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002237 }
Erik Klinea24d4592018-01-11 21:07:29 +09002238 final int oldScore = nai.getCurrentScore();
2239 nai.lastValidated = valid;
2240 nai.everValidated |= valid;
2241 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2242 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2243 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2244 }
2245 updateInetCondition(nai);
2246 // Let the NetworkAgent know the state of its network
2247 Bundle redirectUrlBundle = new Bundle();
2248 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2249 nai.asyncChannel.sendMessage(
2250 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2251 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2252 0, redirectUrlBundle);
2253 if (wasValidated && !nai.lastValidated) {
2254 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002255 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002256 break;
2257 }
Paul Jensen869868be2014-05-15 10:33:05 -04002258 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002259 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002260 final boolean visible = toBool(msg.arg1);
Erik Kline79c6d052018-03-21 07:18:33 -07002261 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002262 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002263 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002264 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002265 nai.lastCaptivePortalDetected = visible;
2266 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002267 if (nai.lastCaptivePortalDetected &&
2268 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2269 if (DBG) log("Avoiding captive portal network: " + nai.name());
2270 nai.asyncChannel.sendMessage(
2271 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2272 teardownUnneededNetwork(nai);
2273 break;
2274 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002275 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002276 }
2277 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002278 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002279 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002280 if (nai == null) {
2281 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2282 break;
2283 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002284 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002285 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002286 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002287 }
Paul Jensen869868be2014-05-15 10:33:05 -04002288 }
Paul Jensen869868be2014-05-15 10:33:05 -04002289 break;
2290 }
Erik Klinea24d4592018-01-11 21:07:29 +09002291 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002292 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002293 if (nai == null) break;
2294
Erik Kline79c6d052018-03-21 07:18:33 -07002295 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002296 break;
2297 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002298 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002299 return true;
2300 }
2301
Calvin Onbe96da12016-10-11 15:10:46 -07002302 private int getCaptivePortalMode() {
2303 return Settings.Global.getInt(mContext.getContentResolver(),
2304 Settings.Global.CAPTIVE_PORTAL_MODE,
2305 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2306 }
2307
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002308 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2309 switch (msg.what) {
2310 default:
2311 return false;
2312 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2313 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2314 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2315 handleLingerComplete(nai);
2316 }
2317 break;
2318 }
2319 }
2320 return true;
2321 }
2322
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002323 @Override
2324 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002325 if (!maybeHandleAsyncChannelMessage(msg) &&
2326 !maybeHandleNetworkMonitorMessage(msg) &&
2327 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002328 maybeHandleNetworkAgentMessage(msg);
2329 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002330 }
2331 }
2332
Erik Kline79c6d052018-03-21 07:18:33 -07002333 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2334 return NetworkMonitor.isValidationRequired(
2335 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2336 }
2337
Erik Klinea24d4592018-01-11 21:07:29 +09002338 private void handlePrivateDnsSettingsChanged() {
2339 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2340
2341 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline79c6d052018-03-21 07:18:33 -07002342 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk1fcb7392018-03-05 12:42:22 -05002343 if (networkRequiresValidation(nai)) {
2344 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2345 }
Erik Klinea24d4592018-01-11 21:07:29 +09002346 }
2347 }
2348
Erik Kline79c6d052018-03-21 07:18:33 -07002349 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2350 // Private DNS only ever applies to networks that might provide
2351 // Internet access and therefore also require validation.
2352 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002353
Erik Kline79c6d052018-03-21 07:18:33 -07002354 // Notify the NetworkMonitor thread in case it needs to cancel or
2355 // schedule DNS resolutions. If a DNS resolution is required the
2356 // result will be sent back to us.
2357 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2358
2359 // With Private DNS bypass support, we can proceed to update the
2360 // Private DNS config immediately, even if we're in strict mode
2361 // and have not yet resolved the provider name into a set of IPs.
2362 updatePrivateDns(nai, cfg);
2363 }
2364
2365 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2366 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002367 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002368 }
2369
dalyk1fcb7392018-03-05 12:42:22 -05002370 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2371 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2372 if (nai == null) {
2373 return;
2374 }
2375 mDnsManager.updatePrivateDnsValidation(update);
2376 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2377 }
2378
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002379 private void updateLingerState(NetworkAgentInfo nai, long now) {
2380 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2381 // 2. If the network was lingering and there are now requests, unlinger it.
2382 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2383 // one lingered request, start lingering.
2384 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002385 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002386 if (DBG) log("Unlingering " + nai.name());
2387 nai.unlinger();
2388 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002389 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002390 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002391 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002392 nai.linger();
2393 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2394 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2395 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002396 }
2397
Robert Greenwalt7b816022014-04-18 15:25:25 -07002398 private void handleAsyncChannelHalfConnect(Message msg) {
2399 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002400 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002401 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2402 if (VDBG) log("NetworkFactory connected");
2403 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002404 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002405 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002406 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002407 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002408 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002409 }
2410 } else {
2411 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002412 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002413 }
2414 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2415 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2416 if (VDBG) log("NetworkAgent connected");
2417 // A network agent has requested a connection. Establish the connection.
2418 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2419 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2420 } else {
2421 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002422 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002423 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002424 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002425 synchronized (mNetworkForNetId) {
2426 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002427 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002428 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002429 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002430 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002431 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002432 }
2433 }
2434 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002435
Robert Greenwalt7b816022014-04-18 15:25:25 -07002436 private void handleAsyncChannelDisconnected(Message msg) {
2437 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2438 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002439 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002440 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002441 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002442 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002443 // TODO - if we move the logic to the network agent (have them disconnect
2444 // because they lost all their requests or because their score isn't good)
2445 // then they would disconnect organically, report their new state and then
2446 // disconnect the channel.
2447 if (nai.networkInfo.isConnected()) {
2448 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2449 null, null);
2450 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002451 final boolean wasDefault = isDefaultNetwork(nai);
2452 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002453 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002454 // Log default network disconnection before required book-keeping.
2455 // Let rematchAllNetworksAndRequests() below record a new default network event
2456 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2457 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002458 long now = SystemClock.elapsedRealtime();
2459 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002460 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002461 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002462 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2463 // by other networks that are already connected. Perhaps that can be done by
2464 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2465 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002466 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002467 mKeepaliveTracker.handleStopAllKeepalives(nai,
2468 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002469 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2470 // Disable wakeup packet monitoring for each interface.
2471 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2472 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002473 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002474 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002475 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002476 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002477 // Remove the NetworkAgent, but don't mark the netId as
2478 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002479 mNetworkForNetId.remove(nai.network.netId);
2480 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002481 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002482 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2483 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002484 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002485 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002486 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002487 sendUpdatedScoreToFactories(request, 0);
2488 }
2489 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002490 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002491 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002492 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002493 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002494 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002495 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002496 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002497 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002498 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002499 if (nai.created) {
2500 // Tell netd to clean up the configuration for this network
2501 // (routing rules, DNS, etc).
2502 // This may be slow as it requires a lot of netd shelling out to ip and
2503 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2504 // after we've rematched networks with requests which should make a potential
2505 // fallback network the default or requested a new network from the
2506 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2507 // long time.
2508 try {
2509 mNetd.removeNetwork(nai.network.netId);
2510 } catch (Exception e) {
2511 loge("Exception removing network: " + e);
2512 }
Erik Klinea24d4592018-01-11 21:07:29 +09002513 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002514 }
2515 synchronized (mNetworkForNetId) {
2516 mNetIdInUse.delete(nai.network.netId);
2517 }
2518 } else {
2519 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2520 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002521 }
2522 }
2523
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002524 // If this method proves to be too slow then we can maintain a separate
2525 // pendingIntent => NetworkRequestInfo map.
2526 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2527 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2528 Intent intent = pendingIntent.getIntent();
2529 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2530 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2531 if (existingPendingIntent != null &&
2532 existingPendingIntent.getIntent().filterEquals(intent)) {
2533 return entry.getValue();
2534 }
2535 }
2536 return null;
2537 }
2538
2539 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2540 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2541
2542 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2543 if (existingRequest != null) { // remove the existing request.
2544 if (DBG) log("Replacing " + existingRequest.request + " with "
2545 + nri.request + " because their intents matched.");
2546 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2547 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002548 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002549 }
2550
Erik Klineda4bfa82015-04-30 12:58:40 +09002551 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002552 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002553 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002554 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002555 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002556 if (nri.request.networkCapabilities.hasSignalStrength() &&
2557 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2558 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002559 }
2560 }
2561 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002562 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002563 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002564 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002565 }
2566 }
2567
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002568 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2569 int callingUid) {
2570 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2571 if (nri != null) {
2572 handleReleaseNetworkRequest(nri.request, callingUid);
2573 }
2574 }
2575
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002576 // Determines whether the network is the best (or could become the best, if it validated), for
2577 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2578 // on the value of reason:
2579 //
2580 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2581 // then it should be torn down.
2582 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2583 // then it should be lingered.
2584 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2585 final int numRequests;
2586 switch (reason) {
2587 case TEARDOWN:
2588 numRequests = nai.numRequestNetworkRequests();
2589 break;
2590 case LINGER:
2591 numRequests = nai.numForegroundNetworkRequests();
2592 break;
2593 default:
2594 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2595 return true;
2596 }
2597
2598 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002599 return false;
2600 }
Paul Jensene0988542015-06-25 15:30:08 -04002601 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002602 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2603 // Background requests don't affect lingering.
2604 continue;
2605 }
2606
Paul Jensene0988542015-06-25 15:30:08 -04002607 // If this Network is already the highest scoring Network for a request, or if
2608 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002609 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002610 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002611 // Note that this catches two important cases:
2612 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2613 // is currently satisfying the request. This is desirable when
2614 // cellular ends up validating but WiFi does not.
2615 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002616 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002617 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002618 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002619 nai.getCurrentScoreAsValidated())) {
2620 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002621 }
2622 }
Paul Jensene0988542015-06-25 15:30:08 -04002623 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002624 }
2625
Erik Klineacdd6392016-07-07 16:50:58 +09002626 private NetworkRequestInfo getNriForAppRequest(
2627 NetworkRequest request, int callingUid, String requestedOperation) {
2628 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2629
Robert Greenwalt9258c642014-03-26 16:47:06 -07002630 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002631 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002632 log(String.format("UID %d attempted to %s for unowned request %s",
2633 callingUid, requestedOperation, nri));
2634 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002635 }
Erik Klineacdd6392016-07-07 16:50:58 +09002636 }
2637
2638 return nri;
2639 }
2640
Erik Kline57faba92015-11-25 12:49:38 +09002641 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002642 if (mNetworkRequests.get(nri.request) == null) {
2643 return;
Erik Kline57faba92015-11-25 12:49:38 +09002644 }
Hugo Benichicd952782017-09-20 11:20:14 +09002645 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002646 return;
2647 }
2648 if (VDBG || (DBG && nri.request.isRequest())) {
2649 log("releasing " + nri.request + " (timeout)");
2650 }
2651 handleRemoveNetworkRequest(nri);
2652 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002653 }
2654
Erik Klineacdd6392016-07-07 16:50:58 +09002655 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002656 final NetworkRequestInfo nri =
2657 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2658 if (nri == null) {
2659 return;
Erik Kline57faba92015-11-25 12:49:38 +09002660 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002661 if (VDBG || (DBG && nri.request.isRequest())) {
2662 log("releasing " + nri.request + " (release request)");
2663 }
2664 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002665 }
Erik Klineacdd6392016-07-07 16:50:58 +09002666
Hugo Benichidba33db2017-03-23 22:40:44 +09002667 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002668 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002669 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002670
Erik Klineacdd6392016-07-07 16:50:58 +09002671 synchronized (mUidToNetworkRequestCount) {
2672 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2673 if (requests < 1) {
2674 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2675 nri.mUid);
2676 } else if (requests == 1) {
2677 mUidToNetworkRequestCount.removeAt(
2678 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2679 } else {
2680 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2681 }
2682 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002683
Erik Klineacdd6392016-07-07 16:50:58 +09002684 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2685 if (nri.request.isRequest()) {
2686 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002687 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002688 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002689 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002690 nai.removeRequest(nri.request.requestId);
2691 if (VDBG) {
2692 log(" Removing from current network " + nai.name() +
2693 ", leaving " + nai.numNetworkRequests() + " requests.");
2694 }
2695 // If there are still lingered requests on this network, don't tear it down,
2696 // but resume lingering instead.
2697 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002698 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002699 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2700 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002701 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002702 wasKept = true;
2703 }
Hugo Benichicd952782017-09-20 11:20:14 +09002704 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002705 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2706 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002707 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002708 }
Erik Klineacdd6392016-07-07 16:50:58 +09002709 }
2710
2711 // TODO: remove this code once we know that the Slog.wtf is never hit.
2712 //
2713 // Find all networks that are satisfying this request and remove the request
2714 // from their request lists.
2715 // TODO - it's my understanding that for a request there is only a single
2716 // network satisfying it, so this loop is wasteful
2717 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2718 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2719 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2720 otherNai.name() + ", but mNetworkAgentInfos says " +
2721 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002722 }
2723 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002724
Erik Klineacdd6392016-07-07 16:50:58 +09002725 // Maintain the illusion. When this request arrived, we might have pretended
2726 // that a network connected to serve it, even though the network was already
2727 // connected. Now that this request has gone away, we might have to pretend
2728 // that the network disconnected. LegacyTypeTracker will generate that
2729 // phantom disconnect for this type.
2730 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2731 boolean doRemove = true;
2732 if (wasKept) {
2733 // check if any of the remaining requests for this network are for the
2734 // same legacy type - if so, don't remove the nai
2735 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2736 NetworkRequest otherRequest = nai.requestAt(i);
2737 if (otherRequest.legacyType == nri.request.legacyType &&
2738 otherRequest.isRequest()) {
2739 if (DBG) log(" still have other legacy request - leaving");
2740 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002741 }
2742 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002743 }
2744
Erik Klineacdd6392016-07-07 16:50:58 +09002745 if (doRemove) {
2746 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002747 }
2748 }
Erik Klineacdd6392016-07-07 16:50:58 +09002749
2750 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2751 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2752 nri.request);
2753 }
2754 } else {
2755 // listens don't have a singular affectedNetwork. Check all networks to see
2756 // if this listen request applies and remove it.
2757 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2758 nai.removeRequest(nri.request.requestId);
2759 if (nri.request.networkCapabilities.hasSignalStrength() &&
2760 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2761 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2762 }
2763 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002764 }
2765 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002766
Lorenzo Colitti18660282016-07-04 12:55:44 +09002767 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002768 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2769 enforceConnectivityInternalPermission();
2770 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002771 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002772 }
2773
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002774 @Override
2775 public void setAvoidUnvalidated(Network network) {
2776 enforceConnectivityInternalPermission();
2777 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2778 }
2779
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002780 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2781 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2782 " accept=" + accept + " always=" + always);
2783
2784 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2785 if (nai == null) {
2786 // Nothing to do.
2787 return;
2788 }
2789
2790 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002791 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002792 return;
2793 }
2794
2795 if (!nai.networkMisc.explicitlySelected) {
2796 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2797 }
2798
2799 if (accept != nai.networkMisc.acceptUnvalidated) {
2800 int oldScore = nai.getCurrentScore();
2801 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002802 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002803 sendUpdatedScoreToFactories(nai);
2804 }
2805
2806 if (always) {
2807 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002808 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002809 }
2810
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002811 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002812 // Tell the NetworkAgent to not automatically reconnect to the network.
2813 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2814 // Teardown the nework.
2815 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002816 }
2817
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002818 }
2819
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002820 private void handleSetAvoidUnvalidated(Network network) {
2821 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2822 if (nai == null || nai.lastValidated) {
2823 // Nothing to do. The network either disconnected or revalidated.
2824 return;
2825 }
2826 if (!nai.avoidUnvalidated) {
2827 int oldScore = nai.getCurrentScore();
2828 nai.avoidUnvalidated = true;
2829 rematchAllNetworksAndRequests(nai, oldScore);
2830 sendUpdatedScoreToFactories(nai);
2831 }
2832 }
2833
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002834 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002835 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002836 mHandler.sendMessageDelayed(
2837 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2838 PROMPT_UNVALIDATED_DELAY_MS);
2839 }
2840
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002841 @Override
2842 public void startCaptivePortalApp(Network network) {
2843 enforceConnectivityInternalPermission();
2844 mHandler.post(() -> {
2845 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2846 if (nai == null) return;
2847 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2848 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2849 });
2850 }
2851
Hugo Benichic8e9e122016-09-14 23:23:08 +00002852 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002853 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002854 }
2855
Erik Kline065ab6e2016-10-02 18:02:14 +09002856 private void rematchForAvoidBadWifiUpdate() {
2857 rematchAllNetworksAndRequests(null, 0);
2858 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2859 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2860 sendUpdatedScoreToFactories(nai);
2861 }
2862 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002863 }
2864
Erik Kline065ab6e2016-10-02 18:02:14 +09002865 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002866 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002867 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002868 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002869 if (!configRestrict) {
2870 pw.println("Bad Wi-Fi avoidance: unrestricted");
2871 return;
2872 }
2873
2874 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2875 pw.increaseIndent();
2876 pw.println("Config restrict: " + configRestrict);
2877
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002878 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002879 String description;
2880 // Can't use a switch statement because strings are legal case labels, but null is not.
2881 if ("0".equals(value)) {
2882 description = "get stuck";
2883 } else if (value == null) {
2884 description = "prompt";
2885 } else if ("1".equals(value)) {
2886 description = "avoid";
2887 } else {
2888 description = value + " (?)";
2889 }
2890 pw.println("User setting: " + description);
2891 pw.println("Network overrides:");
2892 pw.increaseIndent();
2893 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2894 if (nai.avoidUnvalidated) {
2895 pw.println(nai.name());
2896 }
2897 }
2898 pw.decreaseIndent();
2899 pw.decreaseIndent();
2900 }
2901
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002902 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2903 final String action;
2904 switch (type) {
2905 case NO_INTERNET:
2906 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2907 break;
2908 case LOST_INTERNET:
2909 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2910 break;
2911 default:
2912 Slog.wtf(TAG, "Unknown notification type " + type);
2913 return;
2914 }
2915
2916 Intent intent = new Intent(action);
2917 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2918 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2919 intent.setClassName("com.android.settings",
2920 "com.android.settings.wifi.WifiNoInternetDialog");
2921
2922 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2923 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2924 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2925 }
2926
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002927 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002928 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002929 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2930
2931 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2932 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002933 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002934 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002935 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2936 return;
2937 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002938 showValidationNotification(nai, NotificationType.NO_INTERNET);
2939 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002940
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002941 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2942 NetworkCapabilities nc = nai.networkCapabilities;
2943 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002944
Erik Kline065ab6e2016-10-02 18:02:14 +09002945 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002946 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002947 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2948 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002949 }
2950
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002951 @Override
2952 public int getMultipathPreference(Network network) {
2953 enforceAccessPermission();
2954
2955 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002956 if (nai != null && nai.networkCapabilities
2957 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002958 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2959 }
2960
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002961 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
2962 if (networkPreference != null) {
2963 return networkPreference;
2964 }
2965
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002966 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2967 }
2968
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002969 private class InternalHandler extends Handler {
2970 public InternalHandler(Looper looper) {
2971 super(looper);
2972 }
2973
2974 @Override
2975 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002976 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002977 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002978 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002979 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002980 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002981 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002982 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002983 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002984 break;
2985 }
Jason Monkdecd2952013-10-10 14:02:51 -04002986 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002987 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002988 break;
2989 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002990 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002991 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2992 break;
2993 }
2994 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2995 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002996 break;
2997 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002998 case EVENT_REGISTER_NETWORK_AGENT: {
2999 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3000 break;
3001 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003002 case EVENT_REGISTER_NETWORK_REQUEST:
3003 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003004 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003005 break;
3006 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003007 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3008 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003009 handleRegisterNetworkRequestWithIntent(msg);
3010 break;
3011 }
Erik Kline57faba92015-11-25 12:49:38 +09003012 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3013 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3014 handleTimedOutNetworkRequest(nri);
3015 break;
3016 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003017 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3018 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3019 break;
3020 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003021 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003022 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003023 break;
3024 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003025 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003026 Network network = (Network) msg.obj;
3027 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003028 break;
3029 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003030 case EVENT_SET_AVOID_UNVALIDATED: {
3031 handleSetAvoidUnvalidated((Network) msg.obj);
3032 break;
3033 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003034 case EVENT_PROMPT_UNVALIDATED: {
3035 handlePromptUnvalidated((Network) msg.obj);
3036 break;
3037 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003038 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3039 handleMobileDataAlwaysOn();
3040 break;
3041 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003042 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3043 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3044 mKeepaliveTracker.handleStartKeepalive(msg);
3045 break;
3046 }
3047 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3048 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3049 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3050 int slot = msg.arg1;
3051 int reason = msg.arg2;
3052 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3053 break;
3054 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003055 case EVENT_SYSTEM_READY: {
3056 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3057 nai.networkMonitor.systemReady = true;
3058 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003059 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003060 break;
3061 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003062 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003063 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003064 break;
3065 }
Erik Klinea24d4592018-01-11 21:07:29 +09003066 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3067 handlePrivateDnsSettingsChanged();
3068 break;
dalyk1fcb7392018-03-05 12:42:22 -05003069 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3070 handlePrivateDnsValidationUpdate(
3071 (PrivateDnsValidationUpdate) msg.obj);
3072 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 }
3074 }
3075 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003076
3077 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003078 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003079 public int tether(String iface, String callerPkg) {
3080 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003081 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003082 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003083 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003084 } else {
3085 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3086 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003087 }
3088
3089 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003090 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003091 public int untether(String iface, String callerPkg) {
3092 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003093
3094 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003095 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003096 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003097 } else {
3098 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3099 }
3100 }
3101
3102 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003103 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003104 public int getLastTetherError(String iface) {
3105 enforceTetherAccessPermission();
3106
3107 if (isTetheringSupported()) {
3108 return mTethering.getLastTetherError(iface);
3109 } else {
3110 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3111 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003112 }
3113
3114 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003115 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003116 public String[] getTetherableUsbRegexs() {
3117 enforceTetherAccessPermission();
3118 if (isTetheringSupported()) {
3119 return mTethering.getTetherableUsbRegexs();
3120 } else {
3121 return new String[0];
3122 }
3123 }
3124
Lorenzo Colitti18660282016-07-04 12:55:44 +09003125 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003126 public String[] getTetherableWifiRegexs() {
3127 enforceTetherAccessPermission();
3128 if (isTetheringSupported()) {
3129 return mTethering.getTetherableWifiRegexs();
3130 } else {
3131 return new String[0];
3132 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003133 }
3134
Lorenzo Colitti18660282016-07-04 12:55:44 +09003135 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003136 public String[] getTetherableBluetoothRegexs() {
3137 enforceTetherAccessPermission();
3138 if (isTetheringSupported()) {
3139 return mTethering.getTetherableBluetoothRegexs();
3140 } else {
3141 return new String[0];
3142 }
3143 }
3144
Lorenzo Colitti18660282016-07-04 12:55:44 +09003145 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003146 public int setUsbTethering(boolean enable, String callerPkg) {
3147 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003148 if (isTetheringSupported()) {
3149 return mTethering.setUsbTethering(enable);
3150 } else {
3151 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3152 }
3153 }
3154
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003155 // TODO - move iface listing, queries, etc to new module
3156 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003157 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003158 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003159 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003160 return mTethering.getTetherableIfaces();
3161 }
3162
Lorenzo Colitti18660282016-07-04 12:55:44 +09003163 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003164 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003165 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003166 return mTethering.getTetheredIfaces();
3167 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003168
Lorenzo Colitti18660282016-07-04 12:55:44 +09003169 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003170 public String[] getTetheringErroredIfaces() {
3171 enforceTetherAccessPermission();
3172 return mTethering.getErroredIfaces();
3173 }
3174
Lorenzo Colitti18660282016-07-04 12:55:44 +09003175 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003176 public String[] getTetheredDhcpRanges() {
3177 enforceConnectivityInternalPermission();
3178 return mTethering.getTetheredDhcpRanges();
3179 }
3180
Udam Saini0e94c362017-06-07 12:06:28 -07003181 @Override
3182 public boolean isTetheringSupported(String callerPkg) {
3183 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3184 return isTetheringSupported();
3185 }
3186
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003187 // if ro.tether.denied = true we default to no tethering
3188 // gservices could set the secure setting to 1 though to enable it on a build where it
3189 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003190 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003191 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3192 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3193 Settings.Global.TETHER_SUPPORTED, defaultVal));
3194 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003195 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003196
3197 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3198 boolean adminUser = false;
3199 final long token = Binder.clearCallingIdentity();
3200 try {
3201 adminUser = mUserManager.isAdminUser();
3202 } finally {
3203 Binder.restoreCallingIdentity(token);
3204 }
3205
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003206 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003207 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003208
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003209 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003210 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3211 String callerPkg) {
3212 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003213 if (!isTetheringSupported()) {
3214 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3215 return;
3216 }
3217 mTethering.startTethering(type, receiver, showProvisioningUi);
3218 }
3219
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003220 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003221 public void stopTethering(int type, String callerPkg) {
3222 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003223 mTethering.stopTethering(type);
3224 }
3225
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003226 // Called when we lose the default network and have no replacement yet.
3227 // This will automatically be cleared after X seconds or a new default network
3228 // becomes CONNECTED, whichever happens first. The timer is started by the
3229 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003230 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003231 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003232 if (mNetTransitionWakeLock.isHeld()) {
3233 return;
3234 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003235 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003236 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3237 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003238 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003239 mWakelockLogs.log("ACQUIRE for " + forWhom);
3240 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3241 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003242 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003243
Hugo Benichi4c31b342017-03-30 23:18:10 +09003244 // Called when we gain a new default network to release the network transition wakelock in a
3245 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3246 // message is cancelled.
3247 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003248 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003249 if (!mNetTransitionWakeLock.isHeld()) {
3250 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003251 }
3252 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003253 // Cancel self timeout on wakelock hold.
3254 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3255 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3256 mHandler.sendMessageDelayed(msg, 1000);
3257 }
3258
3259 // Called when either message of ensureNetworkTransitionWakelock or
3260 // scheduleReleaseNetworkTransitionWakelock is processed.
3261 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3262 String event = eventName(eventId);
3263 synchronized (this) {
3264 if (!mNetTransitionWakeLock.isHeld()) {
3265 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3266 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3267 return;
3268 }
3269 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003270 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3271 mTotalWakelockDurationMs += lockDuration;
3272 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3273 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003274 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003275 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003276 }
3277
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003278 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003279 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003280 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003281 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003282 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003283 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003284 }
3285
Lorenzo Colitti18660282016-07-04 12:55:44 +09003286 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003287 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003288 enforceAccessPermission();
3289 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003290 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003291 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003292 mHandler.sendMessage(
3293 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3294 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003295
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003296 private void handleReportNetworkConnectivity(
3297 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003298 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003299 if (network == null) {
3300 nai = getDefaultNetwork();
3301 } else {
3302 nai = getNetworkAgentInfoForNetwork(network);
3303 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003304 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3305 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3306 return;
3307 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003308 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003309 if (hasConnectivity == nai.lastValidated) {
3310 return;
3311 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003312 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003313 int netid = nai.network.netId;
3314 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003315 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003316 // Validating a network that has not yet connected could result in a call to
3317 // rematchNetworkAndRequests() which is not meant to work on such networks.
3318 if (!nai.everConnected) {
3319 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003320 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003321 LinkProperties lp = getLinkProperties(nai);
3322 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3323 return;
3324 }
Erik Kline79c6d052018-03-21 07:18:33 -07003325 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003326 }
3327
Paul Jensencee9b512015-05-06 07:32:40 -04003328 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003329 // this information is already available as a world read/writable jvm property
3330 // so this API change wouldn't have a benifit. It also breaks the passing
3331 // of proxy info to all the JVMs.
3332 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003333 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003334 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003335 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3336 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003337 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003338 }
3339
Lorenzo Colitti18660282016-07-04 12:55:44 +09003340 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003341 public ProxyInfo getProxyForNetwork(Network network) {
3342 if (network == null) return getDefaultProxy();
3343 final ProxyInfo globalProxy = getGlobalProxy();
3344 if (globalProxy != null) return globalProxy;
3345 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3346 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3347 // caller may not have.
3348 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3349 if (nai == null) return null;
3350 synchronized (nai) {
3351 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3352 if (proxyInfo == null) return null;
3353 return new ProxyInfo(proxyInfo);
3354 }
3355 }
3356
Paul Jensene0bef712014-12-10 15:12:18 -05003357 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3358 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3359 // proxy is null then there is no proxy in place).
3360 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3361 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3362 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3363 proxy = null;
3364 }
3365 return proxy;
3366 }
3367
3368 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3369 // better for determining if a new proxy broadcast is necessary:
3370 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3371 // avoid unnecessary broadcasts.
3372 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3373 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3374 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3375 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3376 // all set.
3377 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3378 a = canonicalizeProxyInfo(a);
3379 b = canonicalizeProxyInfo(b);
3380 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3381 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3382 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3383 }
3384
Jason Monk207900c2014-04-25 15:00:09 -04003385 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003386 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003387
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003388 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003389 if (proxyProperties == mGlobalProxy) return;
3390 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3391 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3392
3393 String host = "";
3394 int port = 0;
3395 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003396 String pacFileUrl = "";
3397 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003398 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003399 if (!proxyProperties.isValid()) {
3400 if (DBG)
3401 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3402 return;
3403 }
Jason Monk207900c2014-04-25 15:00:09 -04003404 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003405 host = mGlobalProxy.getHost();
3406 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003407 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003408 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003409 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003410 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003411 } else {
3412 mGlobalProxy = null;
3413 }
3414 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003415 final long token = Binder.clearCallingIdentity();
3416 try {
3417 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3418 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3419 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3420 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003421 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003422 } finally {
3423 Binder.restoreCallingIdentity(token);
3424 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003425
Jason Monkcf0f97a2014-10-02 15:39:38 -04003426 if (mGlobalProxy == null) {
3427 proxyProperties = mDefaultProxy;
3428 }
3429 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003430 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003431 }
3432
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003433 private void loadGlobalProxy() {
3434 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003435 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3436 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3437 String exclList = Settings.Global.getString(res,
3438 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003439 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3440 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003441 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003442 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003443 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003444 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003445 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003446 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003447 if (!proxyProperties.isValid()) {
3448 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3449 return;
3450 }
3451
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003452 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003453 mGlobalProxy = proxyProperties;
3454 }
3455 }
3456 }
3457
Jason Monk207900c2014-04-25 15:00:09 -04003458 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003459 // this information is already available as a world read/writable jvm property
3460 // so this API change wouldn't have a benifit. It also breaks the passing
3461 // of proxy info to all the JVMs.
3462 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003463 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003464 return mGlobalProxy;
3465 }
3466 }
3467
Jason Monk207900c2014-04-25 15:00:09 -04003468 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003469 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003470 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003471 proxy = null;
3472 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003473 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003474 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003475 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003476 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003477 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3478 return;
3479 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003480
3481 // This call could be coming from the PacManager, containing the port of the local
3482 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3483 // global (to get the correct local port), and send a broadcast.
3484 // TODO: Switch PacManager to have its own message to send back rather than
3485 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003486 if ((mGlobalProxy != null) && (proxy != null)
3487 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003488 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3489 mGlobalProxy = proxy;
3490 sendProxyBroadcast(mGlobalProxy);
3491 return;
3492 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003493 mDefaultProxy = proxy;
3494
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003495 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003496 if (!mDefaultProxyDisabled) {
3497 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003498 }
3499 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003500 }
3501
Paul Jensene0bef712014-12-10 15:12:18 -05003502 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3503 // This method gets called when any network changes proxy, but the broadcast only ever contains
3504 // the default proxy (even if it hasn't changed).
3505 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3506 // world where an app might be bound to a non-default network.
3507 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3508 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3509 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3510
3511 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3512 sendProxyBroadcast(getDefaultProxy());
3513 }
3514 }
3515
Robert Greenwalt434203a2010-10-11 16:00:27 -07003516 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003517 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3518 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003519 if (!TextUtils.isEmpty(proxy)) {
3520 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003521 if (data.length == 0) {
3522 return;
3523 }
3524
Robert Greenwalt434203a2010-10-11 16:00:27 -07003525 String proxyHost = data[0];
3526 int proxyPort = 8080;
3527 if (data.length > 1) {
3528 try {
3529 proxyPort = Integer.parseInt(data[1]);
3530 } catch (NumberFormatException e) {
3531 return;
3532 }
3533 }
Jason Monk207900c2014-04-25 15:00:09 -04003534 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003535 setGlobalProxy(p);
3536 }
3537 }
3538
Jason Monk207900c2014-04-25 15:00:09 -04003539 private void sendProxyBroadcast(ProxyInfo proxy) {
3540 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003541 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003542 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003543 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003544 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3545 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003546 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003547 final long ident = Binder.clearCallingIdentity();
3548 try {
3549 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3550 } finally {
3551 Binder.restoreCallingIdentity(ident);
3552 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003553 }
3554
3555 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003556 final private HashMap<Uri, Integer> mUriEventMap;
3557 final private Context mContext;
3558 final private Handler mHandler;
3559
3560 SettingsObserver(Context context, Handler handler) {
3561 super(null);
3562 mUriEventMap = new HashMap<Uri, Integer>();
3563 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003564 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003565 }
3566
Erik Klineda4bfa82015-04-30 12:58:40 +09003567 void observe(Uri uri, int what) {
3568 mUriEventMap.put(uri, what);
3569 final ContentResolver resolver = mContext.getContentResolver();
3570 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003571 }
3572
3573 @Override
3574 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003575 Slog.wtf(TAG, "Should never be reached.");
3576 }
3577
3578 @Override
3579 public void onChange(boolean selfChange, Uri uri) {
3580 final Integer what = mUriEventMap.get(uri);
3581 if (what != null) {
3582 mHandler.obtainMessage(what.intValue()).sendToTarget();
3583 } else {
3584 loge("No matching event to send for URI=" + uri);
3585 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003586 }
3587 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003588
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003589 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003590 Slog.d(TAG, s);
3591 }
3592
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003593 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003594 Slog.e(TAG, s);
3595 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003596
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003597 private static void loge(String s, Throwable t) {
3598 Slog.e(TAG, s, t);
3599 }
3600
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003601 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003602 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003603 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3604 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3605 *
3606 * @param oldPackage Package name of the application which currently controls VPN, which will
3607 * be replaced. If there is no such application, this should should either be
3608 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3609 * @param newPackage Package name of the application which should gain control of VPN, or
3610 * {@code null} to disable.
3611 * @param userId User for whom to prepare the new VPN.
3612 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003613 * @hide
3614 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003615 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003616 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3617 int userId) {
3618 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003619
Hugo Benichi20035e02017-04-26 14:53:28 +09003620 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003621 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003622 Vpn vpn = mVpns.get(userId);
3623 if (vpn != null) {
3624 return vpn.prepare(oldPackage, newPackage);
3625 } else {
3626 return false;
3627 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003628 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003629 }
3630
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003631 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003632 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3633 * This method is used by system-privileged apps.
3634 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3635 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3636 *
3637 * @param packageName The package for which authorization state should change.
3638 * @param userId User for whom {@code packageName} is installed.
3639 * @param authorized {@code true} if this app should be able to start a VPN connection without
3640 * explicit user approval, {@code false} if not.
3641 *
Jeff Davidson05542602014-08-11 14:07:27 -07003642 * @hide
3643 */
3644 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003645 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3646 enforceCrossUserPermission(userId);
3647
Hugo Benichi20035e02017-04-26 14:53:28 +09003648 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003649 Vpn vpn = mVpns.get(userId);
3650 if (vpn != null) {
3651 vpn.setPackageAuthorization(packageName, authorized);
3652 }
Jeff Davidson05542602014-08-11 14:07:27 -07003653 }
3654 }
3655
3656 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003657 * Configure a TUN interface and return its file descriptor. Parameters
3658 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003659 * and not available in ConnectivityManager. Permissions are checked in
3660 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003661 * @hide
3662 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003663 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003664 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003665 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003666 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003667 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003668 return mVpns.get(user).establish(config);
3669 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003670 }
3671
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003672 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003673 * Start legacy VPN, controlling native daemons as needed. Creates a
3674 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003675 */
3676 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003677 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003678 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003679 final LinkProperties egress = getActiveLinkProperties();
3680 if (egress == null) {
3681 throw new IllegalStateException("Missing active network connection");
3682 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003683 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003684 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003685 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3686 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003687 }
3688
3689 /**
3690 * Return the information of the ongoing legacy VPN. This method is used
3691 * by VpnSettings and not available in ConnectivityManager. Permissions
3692 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003693 */
3694 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003695 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3696 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003697
Hugo Benichi20035e02017-04-26 14:53:28 +09003698 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003699 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003700 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003701 }
3702
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003703 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003704 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3705 * and not available in ConnectivityManager.
3706 */
3707 @Override
3708 public VpnInfo[] getAllVpnInfo() {
3709 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003710 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003711 if (mLockdownEnabled) {
3712 return new VpnInfo[0];
3713 }
3714
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003715 List<VpnInfo> infoList = new ArrayList<>();
3716 for (int i = 0; i < mVpns.size(); i++) {
3717 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3718 if (info != null) {
3719 infoList.add(info);
3720 }
3721 }
3722 return infoList.toArray(new VpnInfo[infoList.size()]);
3723 }
3724 }
3725
3726 /**
3727 * @return VPN information for accounting, or null if we can't retrieve all required
3728 * information, e.g primary underlying iface.
3729 */
3730 @Nullable
3731 private VpnInfo createVpnInfo(Vpn vpn) {
3732 VpnInfo info = vpn.getVpnInfo();
3733 if (info == null) {
3734 return null;
3735 }
3736 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3737 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3738 // the underlyingNetworks list.
3739 if (underlyingNetworks == null) {
3740 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3741 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3742 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3743 }
3744 } else if (underlyingNetworks.length > 0) {
3745 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3746 if (linkProperties != null) {
3747 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3748 }
3749 }
3750 return info.primaryUnderlyingIface == null ? null : info;
3751 }
3752
3753 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003754 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3755 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003756 * Permissions are checked in Vpn class.
3757 * @hide
3758 */
3759 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003760 public VpnConfig getVpnConfig(int userId) {
3761 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003762 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003763 Vpn vpn = mVpns.get(userId);
3764 if (vpn != null) {
3765 return vpn.getVpnConfig();
3766 } else {
3767 return null;
3768 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003769 }
3770 }
3771
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003772 @Override
3773 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003774 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3775 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3776 return false;
3777 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003778
Hugo Benichi69744342017-11-27 10:57:16 +09003779 synchronized (mVpns) {
3780 // Tear down existing lockdown if profile was removed
3781 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3782 if (mLockdownEnabled) {
3783 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3784 if (profileTag == null) {
3785 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3786 return false;
3787 }
3788 String profileName = new String(profileTag);
3789 final VpnProfile profile = VpnProfile.decode(
3790 profileName, mKeyStore.get(Credentials.VPN + profileName));
3791 if (profile == null) {
3792 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3793 setLockdownTracker(null);
3794 return true;
3795 }
3796 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003797 Vpn vpn = mVpns.get(user);
3798 if (vpn == null) {
3799 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3800 return false;
3801 }
3802 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003803 } else {
3804 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003805 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003806 }
3807
3808 return true;
3809 }
3810
3811 /**
3812 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3813 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3814 */
Hugo Benichi69744342017-11-27 10:57:16 +09003815 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003816 private void setLockdownTracker(LockdownVpnTracker tracker) {
3817 // Shutdown any existing tracker
3818 final LockdownVpnTracker existing = mLockdownTracker;
3819 mLockdownTracker = null;
3820 if (existing != null) {
3821 existing.shutdown();
3822 }
3823
Robin Leec3736bc2017-03-10 16:19:54 +00003824 if (tracker != null) {
3825 mLockdownTracker = tracker;
3826 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003827 }
3828 }
3829
Hugo Benichi69744342017-11-27 10:57:16 +09003830 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003831 private void throwIfLockdownEnabled() {
3832 if (mLockdownEnabled) {
3833 throw new IllegalStateException("Unavailable in lockdown mode");
3834 }
3835 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003836
Robin Lee244ce8e2016-01-05 18:03:46 +00003837 /**
Robin Lee17e61832016-05-09 13:46:28 +01003838 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3839 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003840 *
Robin Lee17e61832016-05-09 13:46:28 +01003841 * @return {@code true} if the service was started, the service was already connected, or there
3842 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003843 */
Robin Lee17e61832016-05-09 13:46:28 +01003844 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003845 synchronized (mVpns) {
3846 Vpn vpn = mVpns.get(userId);
3847 if (vpn == null) {
3848 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3849 // exists already.
3850 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3851 return false;
3852 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003853
Robin Lee812800c2016-05-13 15:38:08 +01003854 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003855 }
3856 }
3857
3858 @Override
Charles He36738632017-05-15 17:07:18 +01003859 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3860 enforceSettingsPermission();
3861 enforceCrossUserPermission(userId);
3862
3863 synchronized (mVpns) {
3864 Vpn vpn = mVpns.get(userId);
3865 if (vpn == null) {
3866 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3867 return false;
3868 }
3869 return vpn.isAlwaysOnPackageSupported(packageName);
3870 }
3871 }
3872
3873 @Override
Robin Leedc679712016-05-03 13:23:03 +01003874 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003875 enforceConnectivityInternalPermission();
3876 enforceCrossUserPermission(userId);
3877
Robin Lee244ce8e2016-01-05 18:03:46 +00003878 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003879 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3880 if (LockdownVpnTracker.isEnabled()) {
3881 return false;
3882 }
3883
Robin Lee244ce8e2016-01-05 18:03:46 +00003884 Vpn vpn = mVpns.get(userId);
3885 if (vpn == null) {
3886 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3887 return false;
3888 }
Robin Lee17e61832016-05-09 13:46:28 +01003889 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003890 return false;
3891 }
Robin Lee17e61832016-05-09 13:46:28 +01003892 if (!startAlwaysOnVpn(userId)) {
3893 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003894 return false;
3895 }
3896 }
3897 return true;
3898 }
3899
3900 @Override
3901 public String getAlwaysOnVpnPackage(int userId) {
3902 enforceConnectivityInternalPermission();
3903 enforceCrossUserPermission(userId);
3904
3905 synchronized (mVpns) {
3906 Vpn vpn = mVpns.get(userId);
3907 if (vpn == null) {
3908 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3909 return null;
3910 }
3911 return vpn.getAlwaysOnPackage();
3912 }
3913 }
3914
Wink Savilleab9321d2013-06-29 21:10:57 -07003915 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003916 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003917 // TODO: Remove? Any reason to trigger a provisioning check?
3918 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003919 }
3920
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003921 /** Location to an updatable file listing carrier provisioning urls.
3922 * An example:
3923 *
3924 * <?xml version="1.0" encoding="utf-8"?>
3925 * <provisioningUrls>
3926 * <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 -07003927 * </provisioningUrls>
3928 */
3929 private static final String PROVISIONING_URL_PATH =
3930 "/data/misc/radio/provisioning_urls.xml";
3931 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003932
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003933 /** XML tag for root element. */
3934 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3935 /** XML tag for individual url */
3936 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003937 /** XML attribute for mcc */
3938 private static final String ATTR_MCC = "mcc";
3939 /** XML attribute for mnc */
3940 private static final String ATTR_MNC = "mnc";
3941
Paul Jensen434dde82015-06-11 09:43:30 -04003942 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003943 FileReader fileReader = null;
3944 XmlPullParser parser = null;
3945 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003946
3947 try {
3948 fileReader = new FileReader(mProvisioningUrlFile);
3949 parser = Xml.newPullParser();
3950 parser.setInput(fileReader);
3951 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3952
3953 while (true) {
3954 XmlUtils.nextElement(parser);
3955
3956 String element = parser.getName();
3957 if (element == null) break;
3958
Paul Jensen434dde82015-06-11 09:43:30 -04003959 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003960 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3961 try {
3962 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3963 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3964 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3965 parser.next();
3966 if (parser.getEventType() == XmlPullParser.TEXT) {
3967 return parser.getText();
3968 }
3969 }
3970 }
3971 } catch (NumberFormatException e) {
3972 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3973 }
3974 }
3975 }
3976 return null;
3977 } catch (FileNotFoundException e) {
3978 loge("Carrier Provisioning Urls file not found");
3979 } catch (XmlPullParserException e) {
3980 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3981 } catch (IOException e) {
3982 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3983 } finally {
3984 if (fileReader != null) {
3985 try {
3986 fileReader.close();
3987 } catch (IOException e) {}
3988 }
3989 }
3990 return null;
3991 }
3992
Wink Saville42d4f082013-07-20 20:31:59 -07003993 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003994 public String getMobileProvisioningUrl() {
3995 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003996 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003997 if (TextUtils.isEmpty(url)) {
3998 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003999 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004000 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07004001 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07004002 }
Wink Saville8cf35602013-07-10 23:00:07 -07004003 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004004 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004005 String phoneNumber = mTelephonyManager.getLine1Number();
4006 if (TextUtils.isEmpty(phoneNumber)) {
4007 phoneNumber = "0000000000";
4008 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004009 url = String.format(url,
4010 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4011 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004012 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004013 }
4014
Wink Savilleab9321d2013-06-29 21:10:57 -07004015 return url;
4016 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004017
Wink Saville948282b2013-08-29 08:55:16 -07004018 @Override
4019 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004020 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004021 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004022 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4023 return;
4024 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004025 final long ident = Binder.clearCallingIdentity();
4026 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004027 // Concatenate the range of types onto the range of NetIDs.
4028 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4029 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004030 } finally {
4031 Binder.restoreCallingIdentity(ident);
4032 }
Wink Saville948282b2013-08-29 08:55:16 -07004033 }
Wink Saville7788c612013-08-29 14:57:08 -07004034
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004035 @Override
4036 public void setAirplaneMode(boolean enable) {
4037 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004038 final long ident = Binder.clearCallingIdentity();
4039 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004040 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004041 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004042 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4043 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004044 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004045 } finally {
4046 Binder.restoreCallingIdentity(ident);
4047 }
4048 }
4049
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004050 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004051 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004052 Vpn userVpn = mVpns.get(userId);
4053 if (userVpn != null) {
4054 loge("Starting user already has a VPN");
4055 return;
4056 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004057 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004058 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004059 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4060 updateLockdownVpn();
4061 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004062 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004063 }
4064
4065 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004066 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004067 Vpn userVpn = mVpns.get(userId);
4068 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004069 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004070 return;
4071 }
Robin Lee17e61832016-05-09 13:46:28 +01004072 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004073 mVpns.delete(userId);
4074 }
4075 }
4076
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004077 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004078 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004079 final int vpnsSize = mVpns.size();
4080 for (int i = 0; i < vpnsSize; i++) {
4081 Vpn vpn = mVpns.valueAt(i);
4082 vpn.onUserAdded(userId);
4083 }
4084 }
4085 }
4086
4087 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004088 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004089 final int vpnsSize = mVpns.size();
4090 for (int i = 0; i < vpnsSize; i++) {
4091 Vpn vpn = mVpns.valueAt(i);
4092 vpn.onUserRemoved(userId);
4093 }
4094 }
4095 }
4096
Robin Lee89e7a692016-02-29 14:38:17 +00004097 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004098 synchronized (mVpns) {
4099 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4100 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4101 updateLockdownVpn();
4102 } else {
4103 startAlwaysOnVpn(userId);
4104 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004105 }
4106 }
4107
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004108 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4109 @Override
4110 public void onReceive(Context context, Intent intent) {
4111 final String action = intent.getAction();
4112 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4113 if (userId == UserHandle.USER_NULL) return;
4114
Robin Lee323f29d2016-05-04 16:38:06 +01004115 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004116 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004117 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004118 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004119 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4120 onUserAdded(userId);
4121 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4122 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004123 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4124 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004125 }
4126 }
4127 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004128
Robin Lee95204e02017-01-27 11:59:22 +00004129 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4130 @Override
4131 public void onReceive(Context context, Intent intent) {
4132 // Try creating lockdown tracker, since user present usually means
4133 // unlocked keystore.
4134 updateLockdownVpn();
4135 mContext.unregisterReceiver(this);
4136 }
4137 };
4138
Robert Greenwalta67be032014-05-16 15:49:14 -07004139 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4140 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004141 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4142 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004143
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004144 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4145 // Map from UID to number of NetworkRequests that UID has filed.
4146 @GuardedBy("mUidToNetworkRequestCount")
4147 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4148
Robert Greenwalta67be032014-05-16 15:49:14 -07004149 private static class NetworkFactoryInfo {
4150 public final String name;
4151 public final Messenger messenger;
4152 public final AsyncChannel asyncChannel;
4153
4154 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4155 this.name = name;
4156 this.messenger = messenger;
4157 this.asyncChannel = asyncChannel;
4158 }
4159 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004160
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004161 private void ensureNetworkRequestHasType(NetworkRequest request) {
4162 if (request.type == NetworkRequest.Type.NONE) {
4163 throw new IllegalArgumentException(
4164 "All NetworkRequests in ConnectivityService must have a type");
4165 }
4166 }
4167
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004168 /**
4169 * Tracks info about the requester.
4170 * Also used to notice when the calling process dies so we can self-expire
4171 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004172 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004173 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004174 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004175 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004176 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004177 final int mPid;
4178 final int mUid;
4179 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004180
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004181 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004182 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004183 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004184 mPendingIntent = pi;
4185 messenger = null;
4186 mBinder = null;
4187 mPid = getCallingPid();
4188 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004189 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004190 }
4191
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004192 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004193 super();
4194 messenger = m;
4195 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004196 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004197 mBinder = binder;
4198 mPid = getCallingPid();
4199 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004200 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004201 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004202
4203 try {
4204 mBinder.linkToDeath(this, 0);
4205 } catch (RemoteException e) {
4206 binderDied();
4207 }
4208 }
4209
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004210 private void enforceRequestCountLimit() {
4211 synchronized (mUidToNetworkRequestCount) {
4212 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4213 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004214 throw new ServiceSpecificException(
4215 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004216 }
4217 mUidToNetworkRequestCount.put(mUid, networkRequests);
4218 }
4219 }
4220
Robert Greenwalt9258c642014-03-26 16:47:06 -07004221 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004222 if (mBinder != null) {
4223 mBinder.unlinkToDeath(this, 0);
4224 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004225 }
4226
4227 public void binderDied() {
4228 log("ConnectivityService NetworkRequestInfo binderDied(" +
4229 request + ", " + mBinder + ")");
4230 releaseNetworkRequest(request);
4231 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004232
4233 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004234 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004235 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004236 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004237 }
4238
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004239 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4240 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4241 if (badCapability != null) {
4242 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004243 }
4244 }
4245
Chalard Jeanb03a6222018-04-11 21:09:10 +09004246 // This checks that the passed capabilities either do not request a specific SSID, or the
4247 // calling app has permission to do so.
4248 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4249 int callerPid, int callerUid) {
4250 if (null != nc.getSSID() && !checkNetworkStackPermission(callerPid, callerUid)) {
4251 throw new SecurityException("Insufficient permissions to request a specific SSID");
4252 }
4253 }
4254
Erik Kline9d598e12015-07-13 16:37:51 +09004255 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004256 final SortedSet<Integer> thresholds = new TreeSet();
4257 synchronized (nai) {
4258 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4259 if (nri.request.networkCapabilities.hasSignalStrength() &&
4260 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4261 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4262 }
4263 }
4264 }
Erik Kline9d598e12015-07-13 16:37:51 +09004265 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004266 }
4267
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004268 private void updateSignalStrengthThresholds(
4269 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4270 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004271 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004272 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4273
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004274 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004275 String detail;
4276 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4277 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4278 } else {
4279 detail = reason;
4280 }
4281 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4282 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4283 }
4284
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004285 nai.asyncChannel.sendMessage(
4286 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004287 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004288 }
4289
Etan Cohen859748f2017-04-03 17:42:34 -07004290 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4291 if (nc == null) {
4292 return;
4293 }
4294 NetworkSpecifier ns = nc.getNetworkSpecifier();
4295 if (ns == null) {
4296 return;
4297 }
4298 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4299 ns.assertValidFromUid(Binder.getCallingUid());
4300 }
4301
Robert Greenwalt9258c642014-03-26 16:47:06 -07004302 @Override
4303 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004304 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004305 final NetworkRequest.Type type = (networkCapabilities == null)
4306 ? NetworkRequest.Type.TRACK_DEFAULT
4307 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004308 // If the requested networkCapabilities is null, take them instead from
4309 // the default network request. This allows callers to keep track of
4310 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004311 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004312 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004313 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004314 enforceAccessPermission();
4315 } else {
4316 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4317 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004318 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4319 // of the app when the request is filed, but we never change the request if the app
4320 // changes network state. http://b/29964605
4321 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004322 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004323 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004324 ensureSufficientPermissionsForRequest(networkCapabilities,
4325 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004326 // Set the UID range for this request to the single UID of the requester, or to an empty
4327 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004328 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4329 // are no visible methods to set the UIDs, an app could use reflection to try and get
4330 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004331 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004332
Etan Cohenba07c8c2017-02-05 10:42:27 -08004333 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004334 throw new IllegalArgumentException("Bad timeout specified");
4335 }
Etan Cohen859748f2017-04-03 17:42:34 -07004336 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004337
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004338 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004339 nextNetworkRequestId(), type);
4340 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004341 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004342
4343 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004344 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004345 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004346 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004347 }
4348 return networkRequest;
4349 }
4350
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004351 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004352 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004353 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004354 } else {
4355 enforceChangePermission();
4356 }
4357 }
4358
fenglub15e72b2015-03-20 11:29:56 -07004359 @Override
fengludb571472015-04-21 17:12:05 -07004360 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004361 enforceAccessPermission();
4362 NetworkAgentInfo nai = null;
4363 if (network == null) {
4364 return false;
4365 }
4366 synchronized (mNetworkForNetId) {
4367 nai = mNetworkForNetId.get(network.netId);
4368 }
4369 if (nai != null) {
4370 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4371 return true;
4372 }
4373 return false;
4374 }
4375
Felipe Lemeee27cab2016-06-20 16:36:29 -07004376 private boolean isSystem(int uid) {
4377 return uid < Process.FIRST_APPLICATION_UID;
4378 }
fenglub15e72b2015-03-20 11:29:56 -07004379
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004380 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004381 final int uid = Binder.getCallingUid();
4382 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004383 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004384 return;
4385 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004386 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4387 // Policy already enforced.
4388 return;
4389 }
4390 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4391 // If UID is restricted, don't allow them to bring up metered APNs.
4392 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004393 }
4394 }
4395
Robert Greenwalt9258c642014-03-26 16:47:06 -07004396 @Override
4397 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4398 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004399 checkNotNull(operation, "PendingIntent cannot be null.");
4400 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4401 enforceNetworkRequestPermissions(networkCapabilities);
4402 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004403 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004404 ensureSufficientPermissionsForRequest(networkCapabilities,
4405 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004406 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004407 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004408
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004409 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004410 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4411 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004412 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004413 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4414 nri));
4415 return networkRequest;
4416 }
4417
Jeremy Joslin79294842014-12-03 17:15:28 -08004418 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4419 mHandler.sendMessageDelayed(
4420 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4421 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4422 }
4423
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004424 @Override
4425 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004426 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004427 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4428 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004429 }
4430
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004431 // In order to implement the compatibility measure for pre-M apps that call
4432 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4433 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4434 // This ensures it has permission to do so.
4435 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4436 if (nc == null) {
4437 return false;
4438 }
4439 int[] transportTypes = nc.getTransportTypes();
4440 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4441 return false;
4442 }
4443 try {
4444 mContext.enforceCallingOrSelfPermission(
4445 android.Manifest.permission.ACCESS_WIFI_STATE,
4446 "ConnectivityService");
4447 } catch (SecurityException e) {
4448 return false;
4449 }
4450 return true;
4451 }
4452
Robert Greenwalt9258c642014-03-26 16:47:06 -07004453 @Override
4454 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4455 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004456 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4457 enforceAccessPermission();
4458 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004459
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004460 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004461 ensureSufficientPermissionsForRequest(networkCapabilities,
4462 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004463 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004464 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4465 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4466 // onLost and onAvailable callbacks when networks move in and out of the background.
4467 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4468 // can't request networks.
4469 restrictBackgroundRequestForCaller(nc);
4470 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004471
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004472 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004473 NetworkRequest.Type.LISTEN);
4474 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004475 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004476
4477 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4478 return networkRequest;
4479 }
4480
4481 @Override
4482 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4483 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004484 checkNotNull(operation, "PendingIntent cannot be null.");
4485 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4486 enforceAccessPermission();
4487 }
Etan Cohen859748f2017-04-03 17:42:34 -07004488 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004489 ensureSufficientPermissionsForRequest(networkCapabilities,
4490 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004491
Chalard Jeandda156a2018-01-10 21:19:32 +09004492 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004493 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004494
4495 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004496 NetworkRequest.Type.LISTEN);
4497 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004498 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004499
4500 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004501 }
4502
Erik Klineacdd6392016-07-07 16:50:58 +09004503 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004504 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004505 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004506 mHandler.sendMessage(mHandler.obtainMessage(
4507 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004508 }
4509
4510 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004511 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004512 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004513 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4514 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004515 }
4516
Robert Greenwalta67be032014-05-16 15:49:14 -07004517 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004518 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004519 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4520 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4521 }
4522
4523 @Override
4524 public void unregisterNetworkFactory(Messenger messenger) {
4525 enforceConnectivityInternalPermission();
4526 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4527 }
4528
4529 private void handleUnregisterNetworkFactory(Messenger messenger) {
4530 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4531 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004532 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004533 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004534 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004535 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004536 }
4537
Robert Greenwalt7b816022014-04-18 15:25:25 -07004538 /**
4539 * NetworkAgentInfo supporting a request by requestId.
4540 * These have already been vetted (their Capabilities satisfy the request)
4541 * and the are the highest scored network available.
4542 * the are keyed off the Requests requestId.
4543 */
Hugo Benichicd952782017-09-20 11:20:14 +09004544 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4545 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004546 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4547 new SparseArray<NetworkAgentInfo>();
4548
Paul Jensen31a94f42015-02-13 14:18:39 -05004549 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4550 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004551 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4552 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004553 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4554 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4555 // there may not be a strict 1:1 correlation between the two.
4556 @GuardedBy("mNetworkForNetId")
4557 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004558
Robert Greenwalt7b816022014-04-18 15:25:25 -07004559 // NetworkAgentInfo keyed off its connecting messenger
4560 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004561 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004562 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4563 new HashMap<Messenger, NetworkAgentInfo>();
4564
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004565 @GuardedBy("mBlockedAppUids")
4566 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4567
Paul Jensen2c311d62014-11-17 12:34:51 -05004568 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004569 private final NetworkRequest mDefaultRequest;
4570
Erik Klineda4bfa82015-04-30 12:58:40 +09004571 // Request used to optionally keep mobile data active even when higher
4572 // priority networks like Wi-Fi are active.
4573 private final NetworkRequest mDefaultMobileDataRequest;
4574
Hugo Benichicd952782017-09-20 11:20:14 +09004575 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4576 synchronized (mNetworkForRequestId) {
4577 return mNetworkForRequestId.get(requestId);
4578 }
4579 }
4580
4581 private void clearNetworkForRequest(int requestId) {
4582 synchronized (mNetworkForRequestId) {
4583 mNetworkForRequestId.remove(requestId);
4584 }
4585 }
4586
4587 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4588 synchronized (mNetworkForRequestId) {
4589 mNetworkForRequestId.put(requestId, nai);
4590 }
4591 }
4592
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004593 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004594 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004595 }
4596
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004597 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004598 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004599 }
4600
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004601 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4602 return nri.request.requestId == mDefaultRequest.requestId;
4603 }
4604
Paul Jensen31a94f42015-02-13 14:18:39 -05004605 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004606 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004607 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004608 enforceConnectivityInternalPermission();
4609
Rubin Xu1bb5c082017-09-05 18:40:49 +01004610 LinkProperties lp = new LinkProperties(linkProperties);
4611 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004612 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4613 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004614 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004615 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004616 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004617 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004618 // Make sure the network capabilities reflect what the agent info says.
4619 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004620 synchronized (this) {
4621 nai.networkMonitor.systemReady = mSystemReady;
4622 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004623 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4624 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004625 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004626 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004627 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004628 }
4629
Erik Kline117e7f32018-03-04 21:01:01 +09004630 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004631 if (VDBG) log("Got NetworkAgent Messenger");
Erik Kline117e7f32018-03-04 21:01:01 +09004632 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004633 synchronized (mNetworkForNetId) {
Erik Kline117e7f32018-03-04 21:01:01 +09004634 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004635 }
Erik Kline117e7f32018-03-04 21:01:01 +09004636 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4637 NetworkInfo networkInfo = nai.networkInfo;
4638 nai.networkInfo = null;
4639 updateNetworkInfo(nai, networkInfo);
4640 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004641 }
4642
4643 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4644 LinkProperties newLp = networkAgent.linkProperties;
4645 int netId = networkAgent.network.netId;
4646
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004647 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4648 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004649 if (networkAgent.clatd != null) {
4650 networkAgent.clatd.fixupLinkProperties(oldLp);
4651 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004652
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004653 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004654 updateMtu(newLp, oldLp);
4655 // TODO - figure out what to do for clat
4656// for (LinkProperties lp : newLp.getStackedLinks()) {
4657// updateMtu(lp, null);
4658// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004659 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004660
Erik Kline94887872016-04-05 13:30:49 +09004661 updateRoutes(newLp, oldLp, netId);
4662 updateDnses(newLp, oldLp, netId);
dalyk1fcb7392018-03-05 12:42:22 -05004663 // Make sure LinkProperties represents the latest private DNS status.
4664 // This does not need to be done before updateDnses because the
4665 // LinkProperties are not the source of the private DNS configuration.
4666 // updateDnses will fetch the private DNS configuration from DnsManager.
4667 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004668
Hugo Benichi6f62b732017-06-27 15:13:20 +09004669 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004670 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004671 if (isDefaultNetwork(networkAgent)) {
4672 handleApplyDefaultProxy(newLp.getHttpProxy());
4673 } else {
4674 updateProxy(newLp, oldLp, networkAgent);
4675 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004676 // TODO - move this check to cover the whole function
4677 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004678 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004679 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4680 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004681
4682 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004683 }
4684
Joel Scherpelz668370b2017-06-08 15:35:21 +09004685 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004686 // Marks are only available on WiFi interaces. Checking for
4687 // marks on unsupported interfaces is harmless.
4688 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4689 return;
4690 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004691
Joel Scherpelz668370b2017-06-08 15:35:21 +09004692 int mark = mContext.getResources().getInteger(
4693 com.android.internal.R.integer.config_networkWakeupPacketMark);
4694 int mask = mContext.getResources().getInteger(
4695 com.android.internal.R.integer.config_networkWakeupPacketMask);
4696
4697 // Mask/mark of zero will not detect anything interesting.
4698 // Don't install rules unless both values are nonzero.
4699 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004700 return;
4701 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004702
4703 final String prefix = "iface:" + iface;
4704 try {
4705 if (add) {
4706 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4707 } else {
4708 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4709 }
4710 } catch (Exception e) {
4711 loge("Exception modifying wakeup packet monitoring: " + e);
4712 }
4713
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004714 }
4715
4716 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4717 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004718 CompareResult<String> interfaceDiff = new CompareResult<String>(
4719 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4720 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004721 for (String iface : interfaceDiff.added) {
4722 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004723 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004724 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004725 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004726 } catch (Exception e) {
4727 loge("Exception adding interface: " + e);
4728 }
4729 }
4730 for (String iface : interfaceDiff.removed) {
4731 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004732 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004733 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004734 mNetd.removeInterfaceFromNetwork(iface, netId);
4735 } catch (Exception e) {
4736 loge("Exception removing interface: " + e);
4737 }
4738 }
4739 }
4740
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004741 /**
4742 * Have netd update routes from oldLp to newLp.
4743 * @return true if routes changed between oldLp and newLp
4744 */
4745 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004746 // Compare the route diff to determine which routes should be added and removed.
4747 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4748 oldLp != null ? oldLp.getAllRoutes() : null,
4749 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004750
4751 // add routes before removing old in case it helps with continuous connectivity
4752
4753 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4754 for (RouteInfo route : routeDiff.added) {
4755 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004756 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004757 try {
4758 mNetd.addRoute(netId, route);
4759 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004760 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4761 loge("Exception in addRoute for non-gateway: " + e);
4762 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004763 }
4764 }
4765 for (RouteInfo route : routeDiff.added) {
4766 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004767 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004768 try {
4769 mNetd.addRoute(netId, route);
4770 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004771 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4772 loge("Exception in addRoute for gateway: " + e);
4773 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004774 }
4775 }
4776
4777 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004778 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004779 try {
4780 mNetd.removeRoute(netId, route);
4781 } catch (Exception e) {
4782 loge("Exception in removeRoute: " + e);
4783 }
4784 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004785 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004786 }
Erik Kline41368502015-06-17 13:19:54 +09004787
Erik Kline94887872016-04-05 13:30:49 +09004788 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4789 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4790 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004791 }
Erik Kline94887872016-04-05 13:30:49 +09004792
Erik Kline1742fe12017-12-13 19:40:49 +09004793 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4794 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4795
Erik Klinea24d4592018-01-11 21:07:29 +09004796 if (DBG) {
4797 final Collection<InetAddress> dnses = newLp.getDnsServers();
4798 log("Setting DNS servers for network " + netId + " to " + dnses);
4799 }
Erik Kline94887872016-04-05 13:30:49 +09004800 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004801 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004802 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004803 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004804 }
Erik Kline4edba012017-04-07 15:29:29 +09004805 }
4806
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004807 private String getNetworkPermission(NetworkCapabilities nc) {
4808 // TODO: make these permission strings AIDL constants instead.
4809 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4810 return NetworkManagementService.PERMISSION_SYSTEM;
4811 }
4812 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4813 return NetworkManagementService.PERMISSION_NETWORK;
4814 }
4815 return null;
4816 }
4817
Paul Jensen3d194ea2015-06-16 14:27:36 -04004818 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004819 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4820 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4821 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004822 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004823 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004824 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004825 if (nai.everConnected &&
4826 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4827 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004828 // does not cause any request (that is not a listen) currently matching that agent to
4829 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004830 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004831 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004832 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004833 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004834 }
4835
Paul Jensen3d194ea2015-06-16 14:27:36 -04004836 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004837 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004838 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004839 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004840 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004841 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004842 }
Paul Jensene0988542015-06-25 15:30:08 -04004843 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004844 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004845 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004846 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004847 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004848 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004849 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004850 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004851 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004852 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004853 if (nai.isSuspended()) {
4854 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4855 } else {
4856 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4857 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004858
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004859 return newNc;
4860 }
4861
4862 /**
4863 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4864 *
4865 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4866 * capabilities we manage and store in {@code nai}, such as validated status and captive
4867 * portal status)
4868 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4869 * potentially triggers rematches.
4870 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4871 * change.)
4872 *
4873 * @param oldScore score of the network before any of the changes that prompted us
4874 * to call this function.
4875 * @param nai the network having its capabilities updated.
4876 * @param nc the new network capabilities.
4877 */
4878 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4879 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4880
4881 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004882
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004883 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004884 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004885 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004886 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004887 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004888 } catch (RemoteException e) {
4889 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004890 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004891 }
4892
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004893 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004894 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004895 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004896 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004897 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004898
Chalard Jeanf213ca12018-01-16 18:43:05 +09004899 updateUids(nai, prevNc, newNc);
4900
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004901 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004902 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4903 // the change we're processing can't affect any requests, it can only affect the listens
4904 // on this network. We might have been called by rematchNetworkAndRequests when a
4905 // network changed foreground state.
4906 processListenRequests(nai, true);
4907 } else {
4908 // If the requestable capabilities have changed or the score changed, we can't have been
4909 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004910 rematchAllNetworksAndRequests(nai, oldScore);
4911 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004912 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004913
4914 // Report changes that are interesting for network statistics tracking.
4915 if (prevNc != null) {
4916 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004917 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004918 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004919 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004920 if (meteredChanged || roamingChanged) {
4921 notifyIfacesChangedForNetworkStats();
4922 }
4923 }
4924
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004925 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004926 // Tell VPNs about updated capabilities, since they may need to
4927 // bubble those changes through.
4928 synchronized (mVpns) {
4929 for (int i = 0; i < mVpns.size(); i++) {
4930 final Vpn vpn = mVpns.valueAt(i);
4931 vpn.updateCapabilities();
4932 }
4933 }
4934 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004935 }
4936
Chalard Jeanf213ca12018-01-16 18:43:05 +09004937 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4938 NetworkCapabilities newNc) {
4939 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4940 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4941 if (null == prevRanges) prevRanges = new ArraySet<>();
4942 if (null == newRanges) newRanges = new ArraySet<>();
4943 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4944
4945 prevRanges.removeAll(newRanges);
4946 newRanges.removeAll(prevRangesCopy);
4947
4948 try {
4949 if (!newRanges.isEmpty()) {
4950 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4951 newRanges.toArray(addedRangesArray);
4952 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4953 }
4954 if (!prevRanges.isEmpty()) {
4955 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4956 prevRanges.toArray(removedRangesArray);
4957 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4958 }
4959 } catch (Exception e) {
4960 // Never crash!
4961 loge("Exception in updateUids: " + e);
4962 }
4963 }
4964
Hugo Benichief502882017-09-01 01:23:32 +00004965 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline79c6d052018-03-21 07:18:33 -07004966 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004967 // Ignore updates for disconnected networks
4968 return;
4969 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004970 // newLp is already a defensive copy.
4971 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004972 if (VDBG) {
4973 log("Update of LinkProperties for " + nai.name() +
4974 "; created=" + nai.created +
4975 "; everConnected=" + nai.everConnected);
4976 }
4977 LinkProperties oldLp = nai.linkProperties;
4978 synchronized (nai) {
4979 nai.linkProperties = newLp;
4980 }
4981 if (nai.everConnected) {
4982 updateLinkProperties(nai, oldLp);
4983 }
4984 }
4985
Paul Jensenc8b9a742014-09-30 15:37:41 -04004986 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004987 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4988 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004989 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004990 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004991 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4992 }
4993 }
4994
Robert Greenwalt7b816022014-04-18 15:25:25 -07004995 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4996 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004997 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004998 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4999 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005000 }
5001 }
5002
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005003 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5004 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005005 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005006 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005007 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5008 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005009 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005010 sendIntent(nri.mPendingIntent, intent);
5011 }
5012 // else not handled
5013 }
5014
5015 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5016 mPendingIntentWakeLock.acquire();
5017 try {
5018 if (DBG) log("Sending " + pendingIntent);
5019 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5020 } catch (PendingIntent.CanceledException e) {
5021 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5022 mPendingIntentWakeLock.release();
5023 releasePendingNetworkRequest(pendingIntent);
5024 }
5025 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5026 }
5027
5028 @Override
5029 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5030 String resultData, Bundle resultExtras) {
5031 if (DBG) log("Finished sending " + pendingIntent);
5032 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005033 // Release with a delay so the receiving client has an opportunity to put in its
5034 // own request.
5035 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005036 }
5037
Chalard Jeanf19db372018-01-26 19:24:40 +09005038 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005039 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005040 if (nri.messenger == null) {
5041 return; // Default request has no msgr
5042 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005043 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005044 // TODO: check if defensive copies of data is needed.
5045 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005046 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005047 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5048 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005049 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005050 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005051 case ConnectivityManager.CALLBACK_AVAILABLE: {
5052 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5053 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5054 break;
5055 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005056 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005057 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005058 break;
5059 }
5060 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005061 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005062 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005063 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005064 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005065 break;
5066 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005067 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005068 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005069 break;
5070 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005071 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005072 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005073 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005074 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005075 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005076 String notification = ConnectivityManager.getCallbackName(notificationType);
5077 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005078 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005079 nri.messenger.send(msg);
5080 } catch (RemoteException e) {
5081 // may occur naturally in the race of binder death.
5082 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5083 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005084 }
5085
Hugo Benichidba33db2017-03-23 22:40:44 +09005086 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5087 bundle.putParcelable(t.getClass().getSimpleName(), t);
5088 }
5089
Paul Jensenc8b9a742014-09-30 15:37:41 -04005090 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005091 if (nai.numRequestNetworkRequests() != 0) {
5092 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5093 NetworkRequest nr = nai.requestAt(i);
5094 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005095 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005096 loge("Dead network still had at least " + nr);
5097 break;
5098 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005099 }
5100 nai.asyncChannel.disconnect();
5101 }
5102
Robert Greenwalt7b816022014-04-18 15:25:25 -07005103 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5104 if (oldNetwork == null) {
5105 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5106 return;
5107 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005108 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005109
5110 // If we get here it means that the last linger timeout for this network expired. So there
5111 // must be no other active linger timers, and we must stop lingering.
5112 oldNetwork.clearLingerState();
5113
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005114 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005115 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005116 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005117 } else {
5118 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005119 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5120 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005121 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005122 }
5123
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005124 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005125 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005126 setupDataActivityTracking(newNetwork);
5127 try {
5128 mNetd.setDefaultNetId(newNetwork.network.netId);
5129 } catch (Exception e) {
5130 loge("Exception setting default network :" + e);
5131 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005132
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005133 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005134 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005135 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005136 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005137 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005138 }
5139
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005140 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005141 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5142 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5143 NetworkRequest nr = nri.request;
5144 if (!nr.isListen()) continue;
5145 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5146 nai.removeRequest(nri.request.requestId);
5147 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5148 }
5149 }
5150
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005151 if (capabilitiesChanged) {
5152 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5153 }
5154
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005155 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5156 NetworkRequest nr = nri.request;
5157 if (!nr.isListen()) continue;
5158 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5159 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005160 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005161 }
5162 }
5163 }
5164
Paul Jensen2161a8e2014-09-11 11:00:39 -04005165 // Handles a network appearing or improving its score.
5166 //
5167 // - Evaluates all current NetworkRequests that can be
5168 // satisfied by newNetwork, and reassigns to newNetwork
5169 // any such requests for which newNetwork is the best.
5170 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005171 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005172 // needed. A network is needed if it is the best network for
5173 // one or more NetworkRequests, or if it is a VPN.
5174 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005175 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005176 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005177 //
5178 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5179 // networks that have no chance (i.e. even if validated)
5180 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005181 //
5182 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5183 // it does not remove NetworkRequests that other Networks could better satisfy.
5184 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5185 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5186 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005187 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005188 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005189 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5190 // performed to tear down unvalidated networks that have no chance (i.e. even if
5191 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005192 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005193 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005194 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005195 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005196 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005197 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005198
5199 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5200 final int score = newNetwork.getCurrentScore();
5201
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005202 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005203
Paul Jensen2161a8e2014-09-11 11:00:39 -04005204 // Find and migrate to this Network any NetworkRequests for
5205 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005206 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005207 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005208 NetworkCapabilities nc = newNetwork.networkCapabilities;
5209 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005210 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005211 // Process requests in the first pass and listens in the second pass. This allows us to
5212 // change a network's capabilities depending on which requests it has. This is only
5213 // correct if the change in capabilities doesn't affect whether the network satisfies
5214 // requests or not, and doesn't affect the network's score.
5215 if (nri.request.isListen()) continue;
5216
Hugo Benichicd952782017-09-20 11:20:14 +09005217 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005218 final boolean satisfies = newNetwork.satisfies(nri.request);
5219 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005220 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005221 log("Network " + newNetwork.name() + " was already satisfying" +
5222 " request " + nri.request.requestId + ". No change.");
5223 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005224 keep = true;
5225 continue;
5226 }
5227
5228 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005229 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005230 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005231 // next check if it's better than any current network we're using for
5232 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005233 if (VDBG) {
5234 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005235 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005236 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005237 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005238 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005239 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005240 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005241 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005242 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005243 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005244 affectedNetworks.add(currentNetwork);
5245 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005246 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005247 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005248 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005249 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005250 if (!newNetwork.addRequest(nri.request)) {
5251 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5252 }
5253 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005254 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005255 // Tell NetworkFactories about the new score, so they can stop
5256 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005257 // TODO - this could get expensive if we have alot of requests for this
5258 // network. Think about if there is a way to reduce this. Push
5259 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005260 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005261 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005262 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005263 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005264 if (currentNetwork != null) {
5265 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5266 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005267 }
5268 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005269 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005270 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5271 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005272 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005273 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5274 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5275 // This means this code doesn't have to handle the case where "currentNetwork" no
5276 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5277 if (DBG) {
5278 log("Network " + newNetwork.name() + " stopped satisfying" +
5279 " request " + nri.request.requestId);
5280 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005281 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005282 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005283 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005284 sendUpdatedScoreToFactories(nri.request, 0);
5285 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005286 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5287 newNetwork.name() +
5288 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005289 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005290 // TODO: Technically, sending CALLBACK_LOST here is
5291 // incorrect if there is a replacement network currently
5292 // connected that can satisfy nri, which is a request
5293 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005294 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5295 // so this code is only incorrect for a network that loses
5296 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005297 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005298 }
5299 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005300 if (isNewDefault) {
5301 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005302 makeDefault(newNetwork);
5303 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005304 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005305 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005306 // Have a new default network, release the transition wakelock in
5307 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005308 }
5309
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005310 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5311 Slog.wtf(TAG, String.format(
5312 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005313 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005314 }
5315 if (newNetwork.getCurrentScore() != score) {
5316 Slog.wtf(TAG, String.format(
5317 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005318 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005319 }
5320
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005321 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005322 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5323 // If the network went from background to foreground or vice versa, we need to update
5324 // its foreground state. It is safe to do this after rematching the requests because
5325 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5326 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005327 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005328 } else {
5329 processListenRequests(newNetwork, false);
5330 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005331
Paul Jensencf4c2c62015-07-01 14:16:32 -04005332 // do this after the default net is switched, but
5333 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005334 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005335
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005336 // Linger any networks that are no longer needed. This should be done after sending the
5337 // available callback for newNetwork.
5338 for (NetworkAgentInfo nai : affectedNetworks) {
5339 updateLingerState(nai, now);
5340 }
5341 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5342 // does not need to be done in any particular order.
5343 updateLingerState(newNetwork, now);
5344
Paul Jensencf4c2c62015-07-01 14:16:32 -04005345 if (isNewDefault) {
5346 // Maintain the illusion: since the legacy API only
5347 // understands one network at a time, we must pretend
5348 // that the current default network disconnected before
5349 // the new one connected.
5350 if (oldDefaultNetwork != null) {
5351 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5352 oldDefaultNetwork, true);
5353 }
5354 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5355 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5356 notifyLockdownVpn(newNetwork);
5357 }
5358
Robert Greenwalt7b816022014-04-18 15:25:25 -07005359 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005360 // Notify battery stats service about this network, both the normal
5361 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005362 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005363 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005364 final IBatteryStats bs = BatteryStatsService.getService();
5365 final int type = newNetwork.networkInfo.getType();
5366
5367 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5368 bs.noteNetworkInterfaceType(baseIface, type);
5369 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5370 final String stackedIface = stacked.getInterfaceName();
5371 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005372 }
5373 } catch (RemoteException ignored) {
5374 }
5375
Robert Greenwalt152ed372014-12-17 17:19:53 -08005376 // This has to happen after the notifyNetworkCallbacks as that tickles each
5377 // ConnectivityManager instance so that legacy requests correctly bind dns
5378 // requests to this network. The legacy users are listening for this bcast
5379 // and will generally do a dns request so they can ensureRouteToHost and if
5380 // they do that before the callbacks happen they'll use the default network.
5381 //
5382 // TODO: Is there still a race here? We send the broadcast
5383 // after sending the callback, but if the app can receive the
5384 // broadcast before the callback, it might still break.
5385 //
5386 // This *does* introduce a race where if the user uses the new api
5387 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5388 // they may get old info. Reverse this after the old startUsing api is removed.
5389 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005390 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5391 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005392 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005393 // legacy type tracker filters out repeat adds
5394 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5395 }
5396 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005397
5398 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5399 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5400 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5401 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5402 if (newNetwork.isVPN()) {
5403 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5404 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005405 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005406 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5407 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005408 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005409 if (nai.getLingerExpiry() > 0) {
5410 // This network has active linger timers and no requests, but is not
5411 // lingering. Linger it.
5412 //
5413 // One way (the only way?) this can happen if this network is unvalidated
5414 // and became unneeded due to another network improving its score to the
5415 // point where this network will no longer be able to satisfy any requests
5416 // even if it validates.
5417 updateLingerState(nai, now);
5418 } else {
5419 if (DBG) log("Reaping " + nai.name());
5420 teardownUnneededNetwork(nai);
5421 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005422 }
5423 }
5424 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005425 }
5426
Paul Jensen1c7ba022015-06-16 14:27:36 -04005427 /**
5428 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5429 * being disconnected.
5430 * @param changed If only one Network's score or capabilities have been modified since the last
5431 * time this function was called, pass this Network in this argument, otherwise pass
5432 * null.
5433 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5434 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5435 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5436 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5437 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005438 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005439 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005440 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5441 // to avoid the slowness. It is not simply enough to process just "changed", for
5442 // example in the case where "changed"'s score decreases and another network should begin
5443 // satifying a NetworkRequest that "changed" currently satisfies.
5444
5445 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5446 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5447 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005448 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005449 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005450 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005451 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005452 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5453 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5454 // Rematch higher scoring networks first to prevent requests first matching a lower
5455 // scoring network and then a higher scoring network, which could produce multiple
5456 // callbacks and inadvertently unlinger networks.
5457 Arrays.sort(nais);
5458 for (NetworkAgentInfo nai : nais) {
5459 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005460 // Only reap the last time through the loop. Reaping before all rematching
5461 // is complete could incorrectly teardown a network that hasn't yet been
5462 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005463 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005464 : ReapUnvalidatedNetworks.REAP,
5465 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005466 }
5467 }
5468 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005469
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005470 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005471 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005472 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005473 // For now only update icons for default connection.
5474 // TODO: Update WiFi and cellular icons separately. b/17237507
5475 if (!isDefaultNetwork(nai)) return;
5476
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005477 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005478 // Don't repeat publish.
5479 if (newInetCondition == mDefaultInetConditionPublished) return;
5480
5481 mDefaultInetConditionPublished = newInetCondition;
5482 sendInetConditionBroadcast(nai.networkInfo);
5483 }
5484
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005485 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005486 synchronized (mVpns) {
5487 if (mLockdownTracker != null) {
5488 if (nai != null && nai.isVPN()) {
5489 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5490 } else {
5491 mLockdownTracker.onNetworkInfoChanged();
5492 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005493 }
5494 }
5495 }
5496
Robert Greenwalt7b816022014-04-18 15:25:25 -07005497 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005498 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005499 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005500 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005501 synchronized (networkAgent) {
5502 oldInfo = networkAgent.networkInfo;
5503 networkAgent.networkInfo = newInfo;
5504 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005505 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005506
Robert Greenwalt7b816022014-04-18 15:25:25 -07005507 if (DBG) {
5508 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5509 (oldInfo == null ? "null" : oldInfo.getState()) +
5510 " to " + state);
5511 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005512
Robin Lee585e2482016-05-01 23:00:00 +01005513 if (!networkAgent.created
5514 && (state == NetworkInfo.State.CONNECTED
5515 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005516
5517 // A network that has just connected has zero requests and is thus a foreground network.
5518 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5519
Robert Greenwalt7b816022014-04-18 15:25:25 -07005520 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005521 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005522 if (networkAgent.isVPN()) {
5523 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005524 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5525 (networkAgent.networkMisc == null ||
5526 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005527 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005528 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005529 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005530 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005531 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005532 loge("Error creating network " + networkAgent.network.netId + ": "
5533 + e.getMessage());
5534 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005535 }
Paul Jenseneec75412014-08-04 12:21:19 -04005536 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005537 }
5538
5539 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5540 networkAgent.everConnected = true;
5541
Erik Kline79c6d052018-03-21 07:18:33 -07005542 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005543 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005544 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005545
Paul Jensenca8f16a2014-05-09 12:47:55 -04005546 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005547 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005548
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005549 if (networkAgent.isVPN()) {
5550 // Temporarily disable the default proxy (not global).
5551 synchronized (mProxyLock) {
5552 if (!mDefaultProxyDisabled) {
5553 mDefaultProxyDisabled = true;
5554 if (mGlobalProxy == null && mDefaultProxy != null) {
5555 sendProxyBroadcast(null);
5556 }
5557 }
5558 }
5559 // TODO: support proxy per network.
5560 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005561
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005562 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5563 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5564 // capabilities, so it only needs to be done once on initial connect, not every time the
5565 // network's capabilities change. Note that we do this before rematching the network,
5566 // so we could decide to tear it down immediately afterwards. That's fine though - on
5567 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5568 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005569 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005570
Paul Jensen2161a8e2014-09-11 11:00:39 -04005571 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005572 final long now = SystemClock.elapsedRealtime();
5573 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005574
5575 // This has to happen after matching the requests, because callbacks are just requests.
5576 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005577 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005578 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005579 if (networkAgent.isVPN()) {
5580 synchronized (mProxyLock) {
5581 if (mDefaultProxyDisabled) {
5582 mDefaultProxyDisabled = false;
5583 if (mGlobalProxy == null && mDefaultProxy != null) {
5584 sendProxyBroadcast(mDefaultProxy);
5585 }
5586 }
5587 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005588 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005589 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005590 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5591 state == NetworkInfo.State.SUSPENDED) {
5592 // going into or coming out of SUSPEND: rescore and notify
5593 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005594 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005595 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005596 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5597 networkAgent.networkCapabilities);
5598 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5599 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005600 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5601 ConnectivityManager.CALLBACK_SUSPENDED :
5602 ConnectivityManager.CALLBACK_RESUMED));
5603 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005604 }
5605 }
5606
Robert Greenwaltac96c522014-06-03 16:43:57 -07005607 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005608 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005609 if (score < 0) {
5610 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5611 "). Bumping score to min of 0");
5612 score = 0;
5613 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005614
Paul Jensen2161a8e2014-09-11 11:00:39 -04005615 final int oldScore = nai.getCurrentScore();
5616 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005617
Paul Jensen85cf78e2015-06-25 13:25:07 -04005618 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005619
Paul Jensenc8b9a742014-09-30 15:37:41 -04005620 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005621 }
5622
Erik Klinec75d4fa2017-02-15 19:59:17 +09005623 // Notify only this one new request of the current state. Transfer all the
5624 // current state by calling NetworkCapabilities and LinkProperties callbacks
5625 // so that callers can be guaranteed to have as close to atomicity in state
5626 // transfer as can be supported by this current API.
5627 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005628 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005629 if (nri.mPendingIntent != null) {
5630 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5631 // Attempt no subsequent state pushes where intents are involved.
5632 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005633 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005634
5635 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005636 }
5637
Robert Greenwalt8d482522015-06-24 13:23:42 -07005638 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005639 // The NetworkInfo we actually send out has no bearing on the real
5640 // state of affairs. For example, if the default connection is mobile,
5641 // and a request for HIPRI has just gone away, we need to pretend that
5642 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5643 // the state to DISCONNECTED, even though the network is of type MOBILE
5644 // and is still connected.
5645 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5646 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005647 if (state != DetailedState.DISCONNECTED) {
5648 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005649 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005650 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005651 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005652 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5653 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5654 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5655 if (info.isFailover()) {
5656 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5657 nai.networkInfo.setFailover(false);
5658 }
5659 if (info.getReason() != null) {
5660 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5661 }
5662 if (info.getExtraInfo() != null) {
5663 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5664 }
5665 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005666 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005667 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005668 if (newDefaultAgent != null) {
5669 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5670 newDefaultAgent.networkInfo);
5671 } else {
5672 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5673 }
5674 }
5675 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5676 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005677 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005678 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005679 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005680 }
5681 }
5682 }
5683
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005684 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005685 if (VDBG) {
5686 String notification = ConnectivityManager.getCallbackName(notifyType);
5687 log("notifyType " + notification + " for " + networkAgent.name());
5688 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005689 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5690 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005691 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5692 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005693 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5694 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005695 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005696 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005697 } else {
5698 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5699 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005700 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005701 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005702
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005703 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5704 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5705 }
5706
Jeff Sharkey69736342014-12-08 14:50:12 -08005707 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005708 * Returns the list of all interfaces that could be used by network traffic that does not
5709 * explicitly specify a network. This includes the default network, but also all VPNs that are
5710 * currently connected.
5711 *
5712 * Must be called on the handler thread.
5713 */
5714 private Network[] getDefaultNetworks() {
5715 ArrayList<Network> defaultNetworks = new ArrayList<>();
5716 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5717 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5718 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5719 defaultNetworks.add(nai.network);
5720 }
5721 }
5722 return defaultNetworks.toArray(new Network[0]);
5723 }
5724
5725 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005726 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5727 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005728 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005729 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005730 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005731 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005732 } catch (Exception ignored) {
5733 }
5734 }
5735
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005736 @Override
5737 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005738 int user = UserHandle.getUserId(Binder.getCallingUid());
5739 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005740 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005741 return mVpns.get(user).addAddress(address, prefixLength);
5742 }
5743 }
5744
5745 @Override
5746 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005747 int user = UserHandle.getUserId(Binder.getCallingUid());
5748 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005749 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005750 return mVpns.get(user).removeAddress(address, prefixLength);
5751 }
5752 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005753
5754 @Override
5755 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005756 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005757 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005758 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005759 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005760 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005761 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005762 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005763 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005764 }
5765 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005766 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005767
5768 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005769 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005770 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005771 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005772 }
5773
5774 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005775 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5776 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5777 enforceKeepalivePermission();
5778 mKeepaliveTracker.startNattKeepalive(
5779 getNetworkAgentInfoForNetwork(network),
5780 intervalSeconds, messenger, binder,
5781 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5782 }
5783
5784 @Override
5785 public void stopKeepalive(Network network, int slot) {
5786 mHandler.sendMessage(mHandler.obtainMessage(
5787 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5788 }
5789
5790 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005791 public void factoryReset() {
5792 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005793
5794 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5795 return;
5796 }
5797
Robin Lee3b3dd942015-05-12 18:14:58 +01005798 final int userId = UserHandle.getCallingUserId();
5799
Stuart Scottf1fb3972015-04-02 18:00:02 -07005800 // Turn airplane mode off
5801 setAirplaneMode(false);
5802
Stuart Scotte3e314d2015-04-20 14:07:45 -07005803 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5804 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005805 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005806 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005807 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005808 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005809 }
5810
Stuart Scotte3e314d2015-04-20 14:07:45 -07005811 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005812 // Remove always-on package
5813 synchronized (mVpns) {
5814 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5815 if (alwaysOnPackage != null) {
5816 setAlwaysOnVpnPackage(userId, null, false);
5817 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5818 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005819
Hugo Benichi69744342017-11-27 10:57:16 +09005820 // Turn Always-on VPN off
5821 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5822 final long ident = Binder.clearCallingIdentity();
5823 try {
5824 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5825 mLockdownEnabled = false;
5826 setLockdownTracker(null);
5827 } finally {
5828 Binder.restoreCallingIdentity(ident);
5829 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005830 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005831
Hugo Benichi69744342017-11-27 10:57:16 +09005832 // Turn VPN off
5833 VpnConfig vpnConfig = getVpnConfig(userId);
5834 if (vpnConfig != null) {
5835 if (vpnConfig.legacy) {
5836 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5837 } else {
5838 // Prevent this app (packagename = vpnConfig.user) from initiating
5839 // VPN connections in the future without user intervention.
5840 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005841
Hugo Benichi69744342017-11-27 10:57:16 +09005842 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5843 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005844 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005845 }
5846 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005847
5848 Settings.Global.putString(mContext.getContentResolver(),
5849 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005850 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005851
Ricky Wai44dcbde2018-01-23 04:09:45 +00005852 @Override
5853 public byte[] getNetworkWatchlistConfigHash() {
5854 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5855 if (nwm == null) {
5856 loge("Unable to get NetworkWatchlistManager");
5857 return null;
5858 }
5859 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5860 return nwm.getWatchlistConfigHash();
5861 }
5862
Paul Jensencf4c2c62015-07-01 14:16:32 -04005863 @VisibleForTesting
5864 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5865 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5866 return new NetworkMonitor(context, handler, nai, defaultRequest);
5867 }
Erik Kline48f12f22016-04-14 17:30:59 +09005868
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005869 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005870 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5871 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005872 }
5873
5874 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005875 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5876 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5877 }
5878
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005879 @VisibleForTesting
5880 public boolean hasService(String name) {
5881 return ServiceManager.checkService(name) != null;
5882 }
5883
Hugo Benichi64901e52017-10-19 14:42:40 +09005884 @VisibleForTesting
5885 protected IpConnectivityMetrics.Logger metricsLogger() {
5886 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5887 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005888 }
5889
5890 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005891 int[] transports = nai.networkCapabilities.getTransportTypes();
5892 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005893 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005894
5895 private static boolean toBool(int encodedBoolean) {
5896 return encodedBoolean != 0; // Only 0 means false.
5897 }
5898
5899 private static int encodeBool(boolean b) {
5900 return b ? 1 : 0;
5901 }
mswest46386886f2018-03-12 10:34:34 -07005902
5903 @Override
5904 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5905 FileDescriptor err, String[] args, ShellCallback callback,
5906 ResultReceiver resultReceiver) {
5907 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5908 }
5909
5910 private class ShellCmd extends ShellCommand {
5911
5912 @Override
5913 public int onCommand(String cmd) {
5914 if (cmd == null) {
5915 return handleDefaultCommands(cmd);
5916 }
5917 final PrintWriter pw = getOutPrintWriter();
5918 try {
5919 switch (cmd) {
5920 case "airplane-mode":
5921 final String action = getNextArg();
5922 if ("enable".equals(action)) {
5923 setAirplaneMode(true);
5924 return 0;
5925 } else if ("disable".equals(action)) {
5926 setAirplaneMode(false);
5927 return 0;
5928 } else if (action == null) {
5929 final ContentResolver cr = mContext.getContentResolver();
5930 final int enabled = Settings.Global.getInt(cr,
5931 Settings.Global.AIRPLANE_MODE_ON);
5932 pw.println(enabled == 0 ? "disabled" : "enabled");
5933 return 0;
5934 } else {
5935 onHelp();
5936 return -1;
5937 }
5938 default:
5939 return handleDefaultCommands(cmd);
5940 }
5941 } catch (Exception e) {
5942 pw.println(e);
5943 }
5944 return -1;
5945 }
5946
5947 @Override
5948 public void onHelp() {
5949 PrintWriter pw = getOutPrintWriter();
5950 pw.println("Connectivity service commands:");
5951 pw.println(" help");
5952 pw.println(" Print this help text.");
5953 pw.println(" airplane-mode [enable|disable]");
5954 pw.println(" Turn airplane mode on or off.");
5955 pw.println(" airplane-mode");
5956 pw.println(" Get airplane mode.");
5957 }
5958 }
Erik Kline79c6d052018-03-21 07:18:33 -07005959}