blob: 9421b12171e6eb6f418a58108cc5204dad65daeb [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;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070032import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060033import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070034import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070036import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070038import static android.net.NetworkPolicyManager.uidRulesToString;
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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070051import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090052import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070053import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090055import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.net.IConnectivityManager;
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;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070063import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070064import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070065import android.net.NetworkCapabilities;
Etan Cohena7434272017-04-03 12:17:51 -070066import android.net.MatchAllNetworkSpecifier;
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 Sharkeyf0ceede2011-08-02 17:22:34 -070071import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070072import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070073import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070074import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070075import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040076import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070077import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040078import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040079import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090080import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090081import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090082import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090083import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080085import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070086import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040087import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070089import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070090import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070091import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.Looper;
93import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070094import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070095import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070096import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070097import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070098import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080099import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900100import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700101import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400102import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700104import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700105import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700106import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700107import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600108import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700109import android.util.LocalLog;
110import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600111import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700112import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800113import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700114import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500115import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700117import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Wink Savilleab9321d2013-06-29 21:10:57 -0700119import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400120import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400121import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700123import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700124import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700125import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800126import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700127import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700128import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700129import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900130import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900131import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700132import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700133import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400134import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900135import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700136import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900137import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900138import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700139import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600140import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400141import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900142import com.android.server.connectivity.NetworkNotificationManager;
143import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400144import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700145import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800146import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700147import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700148import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700149import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600150
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700151import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700152
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700153import org.xmlpull.v1.XmlPullParser;
154import org.xmlpull.v1.XmlPullParserException;
155
156import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700158import java.io.FileNotFoundException;
159import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700160import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700162import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700163import java.net.InetAddress;
164import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700165import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700166import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700167import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700168import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700169import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700170import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700171import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700172import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700173import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600174import java.util.SortedSet;
175import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
177/**
178 * @hide
179 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800180public class ConnectivityService extends IConnectivityManager.Stub
181 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900182 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900184 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700185 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Jake Hamby786e71a2014-02-06 14:43:50 -0800187 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900188 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700189
Jeff Sharkey899223b2012-08-04 15:24:58 -0700190 // TODO: create better separation between radio types and network types
191
Robert Greenwalt42acef32009-08-12 16:08:25 -0700192 // how long to wait before switching back to a radio's default network
193 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
194 // system property that can override the above value
195 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
196 "android.telephony.apn-restore";
197
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900198 // How long to wait before putting up a "This network doesn't have an Internet connection,
199 // connect anyway?" dialog after the user selects a network that doesn't validate.
200 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
201
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900202 // Default to 30s linger time-out. Modifiable only for testing.
203 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
204 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
205 @VisibleForTesting
206 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
207
Jeremy Joslin79294842014-12-03 17:15:28 -0800208 // How long to delay to removal of a pending intent based request.
209 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
210 private final int mReleasePendingIntentDelayMs;
211
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900212 private MockableSystemProperties mSystemProperties;
213
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800214 private Tethering mTethering;
215
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700216 private final PermissionMonitor mPermissionMonitor;
217
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700218 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700219
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700220 @GuardedBy("mVpns")
221 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700222
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700223 private boolean mLockdownEnabled;
224 private LockdownVpnTracker mLockdownTracker;
225
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700226 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
227 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700228 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600229 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700230 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700231 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600232 @GuardedBy("mRulesLock")
233 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
234 /** Flag indicating if background data is restricted. */
235 @GuardedBy("mRulesLock")
236 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700237
Erik Klineda4bfa82015-04-30 12:58:40 +0900238 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700240 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700241 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800243 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
245 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700246 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700248 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800249 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700250 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700251
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700252 private String mCurrentTcpBufferSizes;
253
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700254 private static final int ENABLED = 1;
255 private static final int DISABLED = 0;
256
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900257 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900258 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
259 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900260
Paul Jensenb10e37f2014-11-25 12:33:08 -0500261 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400262 // Tear down networks that have no chance (e.g. even if validated) of becoming
263 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500264 // all networks have been rematched against all NetworkRequests.
265 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400266 // Don't reap networks. This should be passed when some networks have not yet been
267 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500268 DONT_REAP
269 };
270
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900271 private enum UnneededFor {
272 LINGER, // Determine whether this network is unneeded and should be lingered.
273 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
274 }
275
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700276 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700277 * used internally to change our mobile data enabled flag
278 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700279 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700280
281 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700282 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700283 * from one net to another. Clear happens when we get a new
284 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
285 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700286 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700287 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700288
Robert Greenwalt434203a2010-10-11 16:00:27 -0700289 /**
290 * used internally to reload global proxy settings
291 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700292 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700293
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700294 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400295 * PAC manager has received new port.
296 */
297 private static final int EVENT_PROXY_HAS_CHANGED = 16;
298
Robert Greenwalte049c232014-04-11 15:53:27 -0700299 /**
300 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700301 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700302 */
303 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
304
Robert Greenwalt7b816022014-04-18 15:25:25 -0700305 /**
306 * used internally when registering NetworkAgents
307 * obj = Messenger
308 */
309 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
310
Robert Greenwalt9258c642014-03-26 16:47:06 -0700311 /**
312 * used to add a network request
313 * includes a NetworkRequestInfo
314 */
315 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
316
317 /**
318 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900319 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700320 * cancel it.
321 * includes a NetworkRequestInfo
322 */
323 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
324
325 /**
326 * used to add a network listener - no request
327 * includes a NetworkRequestInfo
328 */
329 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
330
331 /**
332 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400333 * arg1 = UID of caller
334 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700335 */
336 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
337
Robert Greenwalta67be032014-05-16 15:49:14 -0700338 /**
339 * used internally when registering NetworkFactories
340 * obj = Messenger
341 */
342 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
343
Robert Greenwalt27711812014-06-25 16:45:57 -0700344 /**
345 * used internally to expire a wakelock when transitioning
346 * from one net to another. Expire happens when we fail to find
347 * a new network (typically after 1 minute) -
348 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
349 * a replacement network.
350 */
351 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
352
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700353 /**
354 * Used internally to indicate the system is ready.
355 */
356 private static final int EVENT_SYSTEM_READY = 25;
357
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800358 /**
359 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400360 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800361 */
362 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
363
364 /**
365 * used to remove a pending intent and its associated network request.
366 * arg1 = UID of caller
367 * obj = PendingIntent
368 */
369 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
370
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900371 /**
372 * used to specify whether a network should be used even if unvalidated.
373 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
374 * arg2 = whether to remember this choice in the future (1 or 0)
375 * obj = network
376 */
377 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
378
379 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900380 * used to specify whether a network should not be penalized when it becomes unvalidated.
381 */
382 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
383
384 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900385 * used to ask the user to confirm a connection to an unvalidated network.
386 * obj = network
387 */
388 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700389
Erik Klineda4bfa82015-04-30 12:58:40 +0900390 /**
391 * used internally to (re)configure mobile data always-on settings.
392 */
393 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
394
Paul Jensen694f2b82015-06-17 14:15:39 -0400395 /**
396 * used to add a network listener with a pending intent
397 * obj = NetworkRequestInfo
398 */
399 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
400
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900401 private static String eventName(int what) {
402 return sMagicDecoderRing.get(what, Integer.toString(what));
403 }
404
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900405 /** Handler thread used for both of the handlers below. */
406 @VisibleForTesting
407 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700408 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700409 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700410 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700411 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700412
Mike Lockwood0f79b542009-08-14 14:18:49 -0400413 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800414 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400415
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700416 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700417 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800418 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700419
Robert Greenwalt434203a2010-10-11 16:00:27 -0700420 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400421 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700422 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700423 private boolean mDefaultProxyDisabled = false;
424
Robert Greenwalt434203a2010-10-11 16:00:27 -0700425 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400426 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700427
Jason Monk602b2322013-07-03 17:04:33 -0400428 private PacManager mPacManager = null;
429
Erik Klineda4bfa82015-04-30 12:58:40 +0900430 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700431
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400432 private UserManager mUserManager;
433
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700434 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700435 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700436
Robert Greenwalt50393202011-06-21 17:26:14 -0700437 // the set of network types that can only be enabled by system/sig apps
438 List mProtectedNetworks;
439
John Spurlockbf991a82013-06-24 14:20:23 -0400440 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700441
Wink Savilleab9321d2013-06-29 21:10:57 -0700442 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400443
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900444 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900445 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900446 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900447
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700448 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
449 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700450 private final static int MAX_NET_ID = 65535;
451 private int mNextNetId = MIN_NET_ID;
452
Robert Greenwalt34524f02014-05-18 16:22:10 -0700453 // sequence number of NetworkRequests
454 private int mNextNetworkRequestId = 1;
455
Erik Kline7523eb32015-07-09 18:24:03 +0900456 // NetworkRequest activity String log entries.
457 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
458 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
459
Hugo Benichic2ae2872016-07-11 11:05:12 +0900460 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900461 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900462 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
463
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900464 private static final int MAX_WAKELOCK_LOGS = 20;
465 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
466
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700467 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
468 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400469 private static class ValidationLog {
470 final Network mNetwork;
471 final String mNetworkExtraInfo;
472 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700473
Paul Jensen0808eb82016-06-03 13:51:21 -0400474 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
475 mNetwork = network;
476 mNetworkExtraInfo = networkExtraInfo;
477 mLog = log;
478 }
479 }
480 private final ArrayDeque<ValidationLog> mValidationLogs =
481 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
482
483 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700484 synchronized(mValidationLogs) {
485 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
486 mValidationLogs.removeLast();
487 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400488 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700489 }
490 }
491
Hugo Benichif9fdf872016-07-28 17:53:06 +0900492 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900493
Erik Kline065ab6e2016-10-02 18:02:14 +0900494 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900495 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900496
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700497 /**
498 * Implements support for the legacy "one network per network type" model.
499 *
500 * We used to have a static array of NetworkStateTrackers, one for each
501 * network type, but that doesn't work any more now that we can have,
502 * for example, more that one wifi network. This class stores all the
503 * NetworkAgentInfo objects that support a given type, but the legacy
504 * API will only see the first one.
505 *
506 * It serves two main purposes:
507 *
508 * 1. Provide information about "the network for a given type" (since this
509 * API only supports one).
510 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
511 * the first network for a given type changes, or if the default network
512 * changes.
513 */
514 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900516 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900517 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900518
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700519 /**
520 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
521 * Each list holds references to all NetworkAgentInfos that are used to
522 * satisfy requests for that network type.
523 *
524 * This array is built out at startup such that an unsupported network
525 * doesn't get an ArrayList instance, making this a tristate:
526 * unsupported, supported but not active and active.
527 *
528 * The actual lists are populated when we scan the network types that
529 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900530 *
531 * Threading model:
532 * - addSupportedType() is only called in the constructor
533 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
534 * They are therefore not thread-safe with respect to each other.
535 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
536 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
537 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700538 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900539 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700540
541 public LegacyTypeTracker() {
542 mTypeLists = (ArrayList<NetworkAgentInfo>[])
543 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
544 }
545
546 public void addSupportedType(int type) {
547 if (mTypeLists[type] != null) {
548 throw new IllegalStateException(
549 "legacy list for type " + type + "already initialized");
550 }
551 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
552 }
553
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700554 public boolean isTypeSupported(int type) {
555 return isNetworkTypeValid(type) && mTypeLists[type] != null;
556 }
557
558 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900559 synchronized (mTypeLists) {
560 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
561 return mTypeLists[type].get(0);
562 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900564 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700565 }
566
Robert Greenwalt8d482522015-06-24 13:23:42 -0700567 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900568 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900569 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700570 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900571 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900572 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900573 }
574 }
575
576 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700577 public void add(int type, NetworkAgentInfo nai) {
578 if (!isTypeSupported(type)) {
579 return; // Invalid network type.
580 }
581 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
582
583 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
584 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700585 return;
586 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900587 synchronized (mTypeLists) {
588 list.add(nai);
589 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900590
591 // 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 +0900592 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900593 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700594 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
595 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 }
598
Lorenzo Colittia793a672014-07-31 23:20:17 +0900599 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900600 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900601 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
602 if (list == null || list.isEmpty()) {
603 return;
604 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900605 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606
Hugo Benichi78caa2582016-06-21 09:48:07 +0900607 synchronized (mTypeLists) {
608 if (!list.remove(nai)) {
609 return;
610 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900611 }
612
Robert Greenwalt8d482522015-06-24 13:23:42 -0700613 final DetailedState state = DetailedState.DISCONNECTED;
614
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900615 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700616 maybeLogBroadcast(nai, state, type, wasDefault);
617 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618 }
619
620 if (!list.isEmpty() && wasFirstNetwork) {
621 if (DBG) log("Other network available for type " + type +
622 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900623 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700624 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
625 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900626 }
627 }
628
629 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
631 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700632 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900633 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700634 }
635 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700636
Robert Greenwalt8d482522015-06-24 13:23:42 -0700637 // send out another legacy broadcast - currently only used for suspend/unsuspend
638 // toggle
639 public void update(NetworkAgentInfo nai) {
640 final boolean isDefault = isDefaultNetwork(nai);
641 final DetailedState state = nai.networkInfo.getDetailedState();
642 for (int type = 0; type < mTypeLists.length; type++) {
643 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700644 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900645 final boolean isFirst = contains && (nai == list.get(0));
646 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700647 maybeLogBroadcast(nai, state, type, isDefault);
648 sendLegacyNetworkBroadcast(nai, state, type);
649 }
650 }
651 }
652
Lorenzo Colittia793a672014-07-31 23:20:17 +0900653 private String naiToString(NetworkAgentInfo nai) {
654 String name = (nai != null) ? nai.name() : "null";
655 String state = (nai.networkInfo != null) ?
656 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
657 "???/???";
658 return name + " " + state;
659 }
660
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700661 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900662 pw.println("mLegacyTypeTracker:");
663 pw.increaseIndent();
664 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700665 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900666 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700667 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900668 pw.println();
669 pw.println("Current state:");
670 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900671 synchronized (mTypeLists) {
672 for (int type = 0; type < mTypeLists.length; type++) {
673 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
674 for (NetworkAgentInfo nai : mTypeLists[type]) {
675 pw.println(type + " " + naiToString(nai));
676 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900677 }
678 }
679 pw.decreaseIndent();
680 pw.decreaseIndent();
681 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700682 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700683 }
684 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
685
Jeff Sharkey899223b2012-08-04 15:24:58 -0700686 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700687 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900688 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
689 }
690
691 @VisibleForTesting
692 protected ConnectivityService(Context context, INetworkManagementService netManager,
693 INetworkStatsService statsService, INetworkPolicyManager policyManager,
694 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800695 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800696
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900697 mSystemProperties = getSystemProperties();
698
Hugo Benichif9fdf872016-07-28 17:53:06 +0900699 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900700 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900701 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900702 mNetworkRequests.put(mDefaultRequest, defaultNRI);
703 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900704
705 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900706 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700707
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900708 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900709 mHandlerThread.start();
710 mHandler = new InternalHandler(mHandlerThread.getLooper());
711 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700712
Jeremy Joslin79294842014-12-03 17:15:28 -0800713 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
714 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
715
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900716 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900717
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700718 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700719 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800720 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700721 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700722 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700723 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700724
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700725 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600726 mPolicyManager.setConnectivityListener(mPolicyListener);
727 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700728 } catch (RemoteException e) {
729 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700730 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700731 }
732
733 final PowerManager powerManager = (PowerManager) context.getSystemService(
734 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700735 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
736 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
737 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800738 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700739
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700740 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700741
Wink Saville51f456f2013-04-23 14:26:51 -0700742 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900743 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700744 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700745 String[] naStrings = context.getResources().getStringArray(
746 com.android.internal.R.array.networkAttributes);
747 for (String naString : naStrings) {
748 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700749 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700750 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700751 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800752 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700753 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700754 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700755 }
Wink Saville51f456f2013-04-23 14:26:51 -0700756 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
757 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
758 n.type);
759 continue;
760 }
Wink Saville975c8482011-04-07 14:23:45 -0700761 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800762 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700763 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700764 continue;
765 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700766 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700767
Wink Saville975c8482011-04-07 14:23:45 -0700768 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700769 mNetworksDefined++;
770 } catch(Exception e) {
771 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700772 }
773 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700774
775 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
776 if (mNetConfigs[TYPE_VPN] == null) {
777 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
778 // don't need to add TYPE_VPN to mNetConfigs.
779 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
780 mNetworksDefined++; // used only in the log() statement below.
781 }
782
Wink Saville5e56bc52013-07-29 15:00:57 -0700783 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700784
Robert Greenwalt50393202011-06-21 17:26:14 -0700785 mProtectedNetworks = new ArrayList<Integer>();
786 int[] protectedNetworks = context.getResources().getIntArray(
787 com.android.internal.R.array.config_protectedNetworks);
788 for (int p : protectedNetworks) {
789 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
790 mProtectedNetworks.add(p);
791 } else {
792 if (DBG) loge("Ignoring protectedNetwork " + p);
793 }
794 }
795
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900796 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
797 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700798
Christopher Wiley497c1472016-10-11 13:26:03 -0700799 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
800 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800801
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700802 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
803
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700804 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700805 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100806 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700807 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700808 intentFilter.addAction(Intent.ACTION_USER_ADDED);
809 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000810 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700811 mContext.registerReceiverAsUser(
812 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000813 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
814 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900815
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700816 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700817 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700818 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700819 } catch (RemoteException e) {
820 loge("Error registering observer :" + e);
821 }
822
Erik Klineda4bfa82015-04-30 12:58:40 +0900823 mSettingsObserver = new SettingsObserver(mContext, mHandler);
824 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800825
John Spurlockbf991a82013-06-24 14:20:23 -0400826 mDataConnectionStats = new DataConnectionStats(mContext);
827 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400828
Jason Monkdecd2952013-10-10 14:02:51 -0400829 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700830
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400831 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900832
833 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900834 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
835 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900836
837 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
838 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
839 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
840 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
841 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
842 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
843 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900844
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900845 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900846 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900847 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700849
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900850 private NetworkRequest createInternetRequestForTransport(
851 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900852 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900853 netCap.addCapability(NET_CAPABILITY_INTERNET);
854 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900855 if (transportType > -1) {
856 netCap.addTransportType(transportType);
857 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900858 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900859 }
860
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900861 // Used only for testing.
862 // TODO: Delete this and either:
863 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
864 // changing ContentResolver to make registerContentObserver non-final).
865 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
866 // by subclassing SettingsObserver.
867 @VisibleForTesting
868 void updateMobileDataAlwaysOn() {
869 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
870 }
871
Erik Klineda4bfa82015-04-30 12:58:40 +0900872 private void handleMobileDataAlwaysOn() {
873 final boolean enable = (Settings.Global.getInt(
Lorenzo Colitti5d6bf6d2017-01-17 11:07:10 +0900874 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) == 1);
Erik Klineda4bfa82015-04-30 12:58:40 +0900875 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
876 if (enable == isEnabled) {
877 return; // Nothing to do.
878 }
879
880 if (enable) {
881 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900882 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900883 } else {
884 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
885 }
886 }
887
888 private void registerSettingsCallbacks() {
889 // Watch for global HTTP proxy changes.
890 mSettingsObserver.observe(
891 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
892 EVENT_APPLY_GLOBAL_HTTP_PROXY);
893
894 // Watch for whether or not to keep mobile data always on.
895 mSettingsObserver.observe(
896 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
897 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
898 }
899
Robert Greenwalt34524f02014-05-18 16:22:10 -0700900 private synchronized int nextNetworkRequestId() {
901 return mNextNetworkRequestId++;
902 }
903
Paul Jensen67b0b072015-06-10 11:22:17 -0400904 @VisibleForTesting
905 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400906 synchronized (mNetworkForNetId) {
907 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
908 int netId = mNextNetId;
909 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
910 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500911 if (!mNetIdInUse.get(netId)) {
912 mNetIdInUse.put(netId, true);
913 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400914 }
915 }
916 }
917 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700918 }
919
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600920 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800921 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600922 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
923 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800924 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600925 state = nai.getNetworkState();
926 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800927 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600928 final NetworkInfo info = new NetworkInfo(networkType, 0,
929 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800930 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
931 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600932 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
933 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600935 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600936 return state;
937 } else {
938 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400940 }
941
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800942 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
943 if (network == null) {
944 return null;
945 }
946 synchronized (mNetworkForNetId) {
947 return mNetworkForNetId.get(network.netId);
948 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600949 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800950
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900951 private Network[] getVpnUnderlyingNetworks(int uid) {
952 if (!mLockdownEnabled) {
953 int user = UserHandle.getUserId(uid);
954 synchronized (mVpns) {
955 Vpn vpn = mVpns.get(user);
956 if (vpn != null && vpn.appliesToUid(uid)) {
957 return vpn.getUnderlyingNetworks();
958 }
959 }
960 }
961 return null;
962 }
963
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800964 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400965 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800966
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900967 final Network[] networks = getVpnUnderlyingNetworks(uid);
968 if (networks != null) {
969 // getUnderlyingNetworks() returns:
970 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
971 // empty array => the VPN explicitly said "no default network".
972 // non-empty array => the VPN specified one or more default networks; we use the
973 // first one.
974 if (networks.length > 0) {
975 nai = getNetworkAgentInfoForNetwork(networks[0]);
976 } else {
977 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800978 }
979 }
980
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800981 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600982 return nai.getNetworkState();
983 } else {
984 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800985 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400986 }
987
988 /**
989 * Check if UID should be blocked from using the network with the given LinkProperties.
990 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600991 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
992 boolean ignoreBlocked) {
993 // Networks aren't blocked when ignoring blocked status
994 if (ignoreBlocked) return false;
995 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -0700996 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600997
998 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700999 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001000
Robin Lee17e61832016-05-09 13:46:28 +01001001 synchronized (mVpns) {
1002 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1003 if (vpn != null && vpn.isBlockingUid(uid)) {
1004 return true;
1005 }
1006 }
1007
Robert Greenwalt12e67352014-05-13 21:41:06 -07001008 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001009 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001010 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001011 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001012 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001013
Felipe Lemed31a97f2016-05-06 14:53:50 -07001014 boolean allowed = true;
1015 // Check Data Saver Mode first...
1016 if (networkMetered) {
1017 if ((uidRules & RULE_REJECT_METERED) != 0) {
1018 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1019 // Explicitly blacklisted.
1020 allowed = false;
1021 } else {
1022 allowed = !mRestrictBackground
1023 || (uidRules & RULE_ALLOW_METERED) != 0
1024 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1025 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1026 + " mRestrictBackground=" + mRestrictBackground
1027 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1028 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1029 + ": " + allowed);
1030 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001031 }
Felipe Leme781ba142016-05-09 16:24:48 -07001032 // ...then power restrictions.
1033 if (allowed) {
1034 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001035 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001036 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001037 }
1038 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001039 }
1040
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001041 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001042 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1043 return;
1044 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001045 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001046 synchronized (mBlockedAppUids) {
1047 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001048 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001049 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001050 blocked = false;
1051 } else {
1052 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001053 }
1054 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001055 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1056 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1057 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001058 }
1059
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001060 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001061 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1062 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1063 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1064 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001065 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001066 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001067 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1068
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001069 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001070 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001071 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001072 if (mLockdownTracker != null) {
1073 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001074 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001075
1076 // TODO: apply metered state closer to NetworkAgentInfo
1077 final long token = Binder.clearCallingIdentity();
1078 try {
1079 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1080 } catch (RemoteException e) {
1081 } finally {
1082 Binder.restoreCallingIdentity(token);
1083 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001084 }
1085
1086 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 * Return NetworkInfo for the active (i.e., connected) network interface.
1088 * It is assumed that at most one network is active at a time. If more
1089 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001090 * @return the info for the active network, or {@code null} if none is
1091 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001093 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001095 enforceAccessPermission();
1096 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001097 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001098 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001099 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1100 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 }
1102
Paul Jensen31a94f42015-02-13 14:18:39 -05001103 @Override
1104 public Network getActiveNetwork() {
1105 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001106 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001107 }
1108
1109 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001110 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001111 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001112 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001113 }
1114
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001115 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001116 final int user = UserHandle.getUserId(uid);
1117 int vpnNetId = NETID_UNSET;
1118 synchronized (mVpns) {
1119 final Vpn vpn = mVpns.get(user);
1120 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1121 }
1122 NetworkAgentInfo nai;
1123 if (vpnNetId != NETID_UNSET) {
1124 synchronized (mNetworkForNetId) {
1125 nai = mNetworkForNetId.get(vpnNetId);
1126 }
1127 if (nai != null) return nai.network;
1128 }
1129 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001130 if (nai != null
1131 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1132 nai = null;
1133 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001134 return nai != null ? nai.network : null;
1135 }
1136
Lorenzo Colitti18660282016-07-04 12:55:44 +09001137 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001138 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1139 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001140 final int uid = Binder.getCallingUid();
1141 NetworkState state = getUnfilteredActiveNetworkState(uid);
1142 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001143 }
1144
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001145 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001146 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001147 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001148 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001149 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001150 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001151 }
1152
1153 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 public NetworkInfo getNetworkInfo(int networkType) {
1155 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001156 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001157 if (getVpnUnderlyingNetworks(uid) != null) {
1158 // A VPN is active, so we may need to return one of its underlying networks. This
1159 // information is not available in LegacyTypeTracker, so we have to get it from
1160 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001161 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001162 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001163 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001164 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001165 }
1166 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001167 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
1170
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001171 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001172 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001173 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001174 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001176 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001177 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001178 return state.networkInfo;
1179 } else {
1180 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001181 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001182 }
1183
1184 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 public NetworkInfo[] getAllNetworkInfo() {
1186 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001187 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001188 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1189 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001190 NetworkInfo info = getNetworkInfo(networkType);
1191 if (info != null) {
1192 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001195 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 }
1197
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001198 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001199 public Network getNetworkForType(int networkType) {
1200 enforceAccessPermission();
1201 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001202 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1203 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001204 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001205 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001206 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001207 }
1208
1209 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001210 public Network[] getAllNetworks() {
1211 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001212 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001213 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001214 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001215 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001216 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001217 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001218 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001219 }
1220
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001221 @Override
1222 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1223 // The basic principle is: if an app's traffic could possibly go over a
1224 // network, without the app doing anything multinetwork-specific,
1225 // (hence, by "default"), then include that network's capabilities in
1226 // the array.
1227 //
1228 // In the normal case, app traffic only goes over the system's default
1229 // network connection, so that's the only network returned.
1230 //
1231 // With a VPN in force, some app traffic may go into the VPN, and thus
1232 // over whatever underlying networks the VPN specifies, while other app
1233 // traffic may go over the system default network (e.g.: a split-tunnel
1234 // VPN, or an app disallowed by the VPN), so the set of networks
1235 // returned includes the VPN's underlying networks and the system
1236 // default.
1237 enforceAccessPermission();
1238
1239 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1240
1241 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001242 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001243 if (nc != null) {
1244 result.put(nai.network, nc);
1245 }
1246
1247 if (!mLockdownEnabled) {
1248 synchronized (mVpns) {
1249 Vpn vpn = mVpns.get(userId);
1250 if (vpn != null) {
1251 Network[] networks = vpn.getUnderlyingNetworks();
1252 if (networks != null) {
1253 for (Network network : networks) {
1254 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001255 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001256 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001257 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001258 }
1259 }
1260 }
1261 }
1262 }
1263 }
1264
1265 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1266 out = result.values().toArray(out);
1267 return out;
1268 }
1269
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001270 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001271 public boolean isNetworkSupported(int networkType) {
1272 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001273 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001274 }
1275
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001276 /**
1277 * Return LinkProperties for the active (i.e., connected) default
1278 * network interface. It is assumed that at most one default network
1279 * is active at a time. If more than one is active, it is indeterminate
1280 * which will be returned.
1281 * @return the ip properties for the active network, or {@code null} if
1282 * none is active
1283 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001284 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001285 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001286 enforceAccessPermission();
1287 final int uid = Binder.getCallingUid();
1288 NetworkState state = getUnfilteredActiveNetworkState(uid);
1289 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001290 }
1291
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001292 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001293 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001294 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001295 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1296 if (nai != null) {
1297 synchronized (nai) {
1298 return new LinkProperties(nai.linkProperties);
1299 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001300 }
1301 return null;
1302 }
1303
Robert Greenwalt12e67352014-05-13 21:41:06 -07001304 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001305 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001306 public LinkProperties getLinkProperties(Network network) {
1307 enforceAccessPermission();
Hugo Benichi29551722017-04-06 16:01:44 +09001308 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1309 }
1310
1311 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1312 if (nai == null) {
1313 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001314 }
Hugo Benichi29551722017-04-06 16:01:44 +09001315 synchronized (nai) {
1316 return new LinkProperties(nai.linkProperties);
1317 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001318 }
1319
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001320 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001321 if (nai != null) {
1322 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001323 if (nai.networkCapabilities != null) {
1324 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001325 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001326 }
1327 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001328 return null;
1329 }
1330
1331 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001332 public NetworkCapabilities getNetworkCapabilities(Network network) {
1333 enforceAccessPermission();
1334 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1335 }
1336
1337 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001338 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001339 // Require internal since we're handing out IMSI details
1340 enforceConnectivityInternalPermission();
1341
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001342 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001343 for (Network network : getAllNetworks()) {
1344 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1345 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001346 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001347 }
1348 }
1349 return result.toArray(new NetworkState[result.size()]);
1350 }
1351
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001352 @Override
1353 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1354 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001355 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001356 final long token = Binder.clearCallingIdentity();
1357 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001358 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1359 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001360 try {
1361 return mPolicyManager.getNetworkQuotaInfo(state);
1362 } catch (RemoteException e) {
1363 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001364 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001365 return null;
1366 } finally {
1367 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001368 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001369 }
1370
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001371 @Override
1372 public boolean isActiveNetworkMetered() {
1373 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001374
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001375 final NetworkInfo info = getActiveNetworkInfo();
1376 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001377 }
1378
Jeff Sharkey216c1812012-08-05 14:29:23 -07001379 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1380 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001381 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001382 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001383 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001384 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001385 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001386
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001387 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 * Ensure that a network route exists to deliver traffic to the specified
1389 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001390 * @param networkType the type of the network over which traffic to the
1391 * specified host is to be routed
1392 * @param hostAddress the IP address of the host to which the route is
1393 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 * @return {@code true} on success, {@code false} on failure
1395 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001396 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001397 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001399 if (mProtectedNetworks.contains(networkType)) {
1400 enforceConnectivityInternalPermission();
1401 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001402
Chad Brubakerc0234532014-02-14 13:24:29 -08001403 InetAddress addr;
1404 try {
1405 addr = InetAddress.getByAddress(hostAddress);
1406 } catch (UnknownHostException e) {
1407 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1408 return false;
1409 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001412 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 return false;
1414 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001415
1416 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1417 if (nai == null) {
1418 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1419 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1420 } else {
1421 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1422 }
1423 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001424 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001425
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001426 DetailedState netState;
1427 synchronized (nai) {
1428 netState = nai.networkInfo.getDetailedState();
1429 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001430
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001431 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001432 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001433 log("requestRouteToHostAddress on down network "
1434 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001435 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001436 }
1437 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001439
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001440 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001441 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001442 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001443 LinkProperties lp;
1444 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001445 synchronized (nai) {
1446 lp = nai.linkProperties;
1447 netId = nai.network.netId;
1448 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001449 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001450 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1451 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001452 } finally {
1453 Binder.restoreCallingIdentity(token);
1454 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001455 }
1456
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001457 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001458 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001459 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001460 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001461 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001462 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001463 if (bestRoute.getGateway().equals(addr)) {
1464 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001465 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001466 } else {
1467 // if we will connect to this through another route, add a direct route
1468 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001469 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001470 }
1471 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001472 if (DBG) log("Adding legacy route " + bestRoute +
1473 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001474 try {
1475 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1476 } catch (Exception e) {
1477 // never crash - catch them all
1478 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001479 return false;
1480 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001481 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
1483
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001484 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1485 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001486 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001487 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001488 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001489 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001490 }
1491
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001492 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001493 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001494 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001495 if (oldRules == uidRules) return;
1496
Felipe Leme781ba142016-05-09 16:24:48 -07001497 if (uidRules == RULE_NONE) {
1498 mUidRules.delete(uid);
1499 } else {
1500 mUidRules.put(uid, uidRules);
1501 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001502 }
1503
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001504 // TODO: notify UID when it has requested targeted updates
1505 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001506
1507 @Override
1508 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001509 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001510 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001511 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001512 }
1513
1514 synchronized (mRulesLock) {
1515 mMeteredIfaces.clear();
1516 for (String iface : meteredIfaces) {
1517 mMeteredIfaces.add(iface);
1518 }
1519 }
1520 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001521
1522 @Override
1523 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1524 // caller is NPMS, since we only register with them
1525 if (LOGD_RULES) {
1526 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1527 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001528
1529 synchronized (mRulesLock) {
1530 mRestrictBackground = restrictBackground;
1531 }
1532
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001533 if (restrictBackground) {
1534 log("onRestrictBackgroundChanged(true): disabling tethering");
1535 mTethering.untetherAll();
1536 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001537 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001538
1539 @Override
1540 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1541 if (LOGD_RULES) {
1542 // caller is NPMS, since we only register with them
1543 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1544 + whitelisted + ")");
1545 }
1546 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001547 @Override
1548 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1549 if (LOGD_RULES) {
1550 // caller is NPMS, since we only register with them
1551 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1552 + blacklisted + ")");
1553 }
1554 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001555 };
1556
Robin Lee3b3dd942015-05-12 18:14:58 +01001557 /**
1558 * Require that the caller is either in the same user or has appropriate permission to interact
1559 * across users.
1560 *
1561 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1562 */
1563 private void enforceCrossUserPermission(int userId) {
1564 if (userId == UserHandle.getCallingUserId()) {
1565 // Not a cross-user call.
1566 return;
1567 }
1568 mContext.enforceCallingOrSelfPermission(
1569 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1570 "ConnectivityService");
1571 }
1572
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001573 private void enforceInternetPermission() {
1574 mContext.enforceCallingOrSelfPermission(
1575 android.Manifest.permission.INTERNET,
1576 "ConnectivityService");
1577 }
1578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001580 mContext.enforceCallingOrSelfPermission(
1581 android.Manifest.permission.ACCESS_NETWORK_STATE,
1582 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 }
1584
1585 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001586 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 }
1588
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001589 private void enforceTetherAccessPermission() {
1590 mContext.enforceCallingOrSelfPermission(
1591 android.Manifest.permission.ACCESS_NETWORK_STATE,
1592 "ConnectivityService");
1593 }
1594
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001595 private void enforceConnectivityInternalPermission() {
1596 mContext.enforceCallingOrSelfPermission(
1597 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1598 "ConnectivityService");
1599 }
1600
Hugo Benichi514da602016-07-19 15:59:27 +09001601 private void enforceConnectivityRestrictedNetworksPermission() {
1602 try {
1603 mContext.enforceCallingOrSelfPermission(
1604 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1605 "ConnectivityService");
1606 return;
1607 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1608 enforceConnectivityInternalPermission();
1609 }
1610
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001611 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001612 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001613 }
1614
Lorenzo Colitti18660282016-07-04 12:55:44 +09001615 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001616 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001617 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001618 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001619 }
1620
1621 private void sendInetConditionBroadcast(NetworkInfo info) {
1622 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1623 }
1624
Wink Saville628b0852011-08-04 15:01:58 -07001625 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001626 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001627 info = new NetworkInfo(info);
1628 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001629 }
1630
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001631 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001632 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001633 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 if (info.isFailover()) {
1635 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1636 info.setFailover(false);
1637 }
1638 if (info.getReason() != null) {
1639 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1640 }
1641 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001642 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1643 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001645 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001646 return intent;
1647 }
1648
1649 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1650 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1651 }
1652
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001653 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001654 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1655 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1656 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001657 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001658 final long ident = Binder.clearCallingIdentity();
1659 try {
1660 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1661 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1662 } finally {
1663 Binder.restoreCallingIdentity(ident);
1664 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001665 }
1666
Mike Lockwood0f79b542009-08-14 14:18:49 -04001667 private void sendStickyBroadcast(Intent intent) {
1668 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001669 if (!mSystemReady) {
1670 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001671 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001672 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001673 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001674 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001675 }
1676
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001677 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001678 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001679 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001680 final NetworkInfo ni = intent.getParcelableExtra(
1681 ConnectivityManager.EXTRA_NETWORK_INFO);
1682 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1683 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1684 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001685 } else {
1686 BroadcastOptions opts = BroadcastOptions.makeBasic();
1687 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1688 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001689 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001690 final IBatteryStats bs = BatteryStatsService.getService();
1691 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001692 bs.noteConnectivityChanged(intent.getIntExtra(
1693 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1694 ni != null ? ni.getState().toString() : "?");
1695 } catch (RemoteException e) {
1696 }
1697 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001698 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001699 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001700 } finally {
1701 Binder.restoreCallingIdentity(ident);
1702 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001703 }
1704 }
1705
1706 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001707 loadGlobalProxy();
1708
Mike Lockwood0f79b542009-08-14 14:18:49 -04001709 synchronized(this) {
1710 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001711 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001712 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001713 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001714 }
1715 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001716 // load the global proxy at startup
1717 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001718
Robin Lee244ce8e2016-01-05 18:03:46 +00001719 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1720 // for user to unlock device too.
1721 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001722
Erik Klineda4bfa82015-04-30 12:58:40 +09001723 // Configure whether mobile data is always on.
1724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1725
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001726 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001727
1728 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 }
1730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001732 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001733 *
1734 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001735 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001736 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001737 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1738 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001739
1740 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001741 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001742
Robert Greenwalt7b816022014-04-18 15:25:25 -07001743 if (networkAgent.networkCapabilities.hasTransport(
1744 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001745 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1746 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001747 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001748 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001749 } else if (networkAgent.networkCapabilities.hasTransport(
1750 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001751 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1752 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001753 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001754 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001755 } else {
1756 // do not track any other networks
1757 timeout = 0;
1758 }
1759
Robert Greenwalt7b816022014-04-18 15:25:25 -07001760 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001761 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001762 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001763 } catch (Exception e) {
1764 // You shall not crash!
1765 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001766 }
1767 }
1768 }
1769
1770 /**
1771 * Remove data activity tracking when network disconnects.
1772 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001773 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1774 final String iface = networkAgent.linkProperties.getInterfaceName();
1775 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001776
Robert Greenwalt7b816022014-04-18 15:25:25 -07001777 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1778 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001779 try {
1780 // the call fails silently if no idletimer setup for this interface
1781 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001782 } catch (Exception e) {
1783 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001784 }
1785 }
1786 }
1787
1788 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001789 * Reads the network specific MTU size from reources.
1790 * and set it on it's iface.
1791 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001792 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1793 final String iface = newLp.getInterfaceName();
1794 final int mtu = newLp.getMtu();
Pierre Imaiaccd5fc2016-02-08 16:01:40 +09001795 if (oldLp == null && mtu == 0) {
1796 // Silently ignore unset MTU value.
1797 return;
1798 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001799 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1800 if (VDBG) log("identical MTU - not setting");
1801 return;
1802 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001803 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001804 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001805 return;
1806 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001807
w1997615afd812014-08-05 15:18:11 -07001808 // Cannot set MTU without interface name
1809 if (TextUtils.isEmpty(iface)) {
1810 loge("Setting MTU size with null iface.");
1811 return;
1812 }
1813
Robert Greenwalt7b816022014-04-18 15:25:25 -07001814 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001815 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001816 mNetd.setMtu(iface, mtu);
1817 } catch (Exception e) {
1818 Slog.e(TAG, "exception in setMtu()" + e);
1819 }
1820 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001821
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001822 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001823 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1824
1825 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001826 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001827 protected MockableSystemProperties getSystemProperties() {
1828 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001829 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001830
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001831 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1832 if (isDefaultNetwork(nai) == false) {
1833 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001834 }
1835
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001836 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1837 String[] values = null;
1838 if (tcpBufferSizes != null) {
1839 values = tcpBufferSizes.split(",");
1840 }
1841
1842 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001843 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001844 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1845 values = tcpBufferSizes.split(",");
1846 }
1847
1848 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1849
1850 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001851 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001852
1853 final String prefix = "/sys/kernel/ipv4/tcp_";
1854 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1855 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1856 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1857 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1858 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1859 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1860 mCurrentTcpBufferSizes = tcpBufferSizes;
1861 } catch (IOException e) {
1862 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001863 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001864
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001865 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001866 Settings.Global.TCP_DEFAULT_INIT_RWND,
1867 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001868 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1869 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001870 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001871 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001872 }
1873
Mattias Falk8b47b362011-08-23 14:15:13 +02001874 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001875 /*
1876 * Tell the VMs to toss their DNS caches
1877 */
1878 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1879 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001880 /*
1881 * Connectivity events can happen before boot has completed ...
1882 */
1883 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001884 final long ident = Binder.clearCallingIdentity();
1885 try {
1886 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1887 } finally {
1888 Binder.restoreCallingIdentity(ident);
1889 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001890 }
1891
Robert Greenwalt562cc542014-05-15 18:07:26 -07001892 @Override
1893 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001894 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001895 NETWORK_RESTORE_DELAY_PROP_NAME);
1896 if(restoreDefaultNetworkDelayStr != null &&
1897 restoreDefaultNetworkDelayStr.length() != 0) {
1898 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001899 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001900 } catch (NumberFormatException e) {
1901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001903 // if the system property isn't set, use the value for the apn type
1904 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1905
1906 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1907 (mNetConfigs[networkType] != null)) {
1908 ret = mNetConfigs[networkType].restoreTime;
1909 }
1910 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 }
1912
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001913 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001914 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001915 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001916 }
1917 return false;
1918 }
1919
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001920 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1921 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1922 final long DIAG_TIME_MS = 5000;
1923 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1924 // Start gathering diagnostic information.
1925 netDiags.add(new NetworkDiagnostics(
1926 nai.network,
1927 new LinkProperties(nai.linkProperties), // Must be a copy.
1928 DIAG_TIME_MS));
1929 }
1930
1931 for (NetworkDiagnostics netDiag : netDiags) {
1932 pw.println();
1933 netDiag.waitForMeasurements();
1934 netDiag.dump(pw);
1935 }
1936 }
1937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001939 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1940 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001941 if (mContext.checkCallingOrSelfPermission(
1942 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001944 pw.println("Permission Denial: can't dump ConnectivityService " +
1945 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1946 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 return;
1948 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001949
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001950 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001951 dumpNetworkDiagnostics(pw);
1952 return;
1953 }
Erik Kline379747a2015-06-05 17:47:34 +09001954
Lorenzo Colittie3805462015-06-03 11:18:24 +09001955 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001956 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001957 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001958 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001959 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001960 pw.println();
1961
Paul Jensen85cf78e2015-06-25 13:25:07 -04001962 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001963 pw.print("Active default network: ");
1964 if (defaultNai == null) {
1965 pw.println("none");
1966 } else {
1967 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001969 pw.println();
1970
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001971 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001972 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001973 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1974 pw.println(nai.toString());
1975 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001976 pw.println(String.format(
1977 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1978 nai.numForegroundNetworkRequests(),
1979 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1980 nai.numBackgroundNetworkRequests(),
1981 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001982 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001983 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1984 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001985 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001986 pw.decreaseIndent();
1987 pw.println("Lingered:");
1988 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001989 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001990 pw.decreaseIndent();
1991 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001992 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001993 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001994 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001995
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001996 pw.println("Metered Interfaces:");
1997 pw.increaseIndent();
1998 for (String value : mMeteredIfaces) {
1999 pw.println(value);
2000 }
2001 pw.decreaseIndent();
2002 pw.println();
2003
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002004 pw.print("Restrict background: ");
2005 pw.println(mRestrictBackground);
2006 pw.println();
2007
Felipe Leme46c4fc32016-05-04 09:21:43 -07002008 pw.println("Status for known UIDs:");
2009 pw.increaseIndent();
2010 final int size = mUidRules.size();
2011 for (int i = 0; i < size; i++) {
2012 final int uid = mUidRules.keyAt(i);
2013 pw.print("UID=");
2014 pw.print(uid);
2015 final int uidRules = mUidRules.get(uid, RULE_NONE);
2016 pw.print(" rules=");
2017 pw.print(uidRulesToString(uidRules));
2018 pw.println();
2019 }
2020 pw.println();
2021 pw.decreaseIndent();
2022
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002023 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002024 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002025 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2026 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002027 }
2028 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002029 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002030
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002031 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002032
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002033 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002034 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002035
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002036 pw.println();
2037 mKeepaliveTracker.dump(pw);
2038
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002039 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002040 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002041
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002042 if (argsContain(args, "--short") == false) {
2043 pw.println();
2044 synchronized (mValidationLogs) {
2045 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002046 for (ValidationLog p : mValidationLogs) {
2047 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002048 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002049 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002050 pw.decreaseIndent();
2051 }
2052 }
Erik Kline7523eb32015-07-09 18:24:03 +09002053
2054 pw.println();
2055 pw.println("mNetworkRequestInfoLogs (most recent first):");
2056 pw.increaseIndent();
2057 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2058 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002059
2060 pw.println();
2061 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2062 pw.increaseIndent();
2063 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2064 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002065
2066 pw.println();
2067 pw.println("NetTransition WakeLock activity (most recent first):");
2068 pw.increaseIndent();
2069 mWakelockLogs.reverseDump(fd, pw, args);
2070 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002074 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002075 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002076 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002077 if (officialNai != null && officialNai.equals(nai)) return true;
2078 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002079 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002080 " - " + nai);
2081 }
2082 return false;
2083 }
2084
Robert Greenwalt42acef32009-08-12 16:08:25 -07002085 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002086 private class NetworkStateTrackerHandler extends Handler {
2087 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002088 super(looper);
2089 }
2090
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002091 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002093 default:
2094 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002095 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002096 handleAsyncChannelHalfConnect(msg);
2097 break;
2098 }
2099 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2100 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2101 if (nai != null) nai.asyncChannel.disconnect();
2102 break;
2103 }
2104 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2105 handleAsyncChannelDisconnected(msg);
2106 break;
2107 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002108 }
2109 return true;
2110 }
2111
2112 private void maybeHandleNetworkAgentMessage(Message msg) {
2113 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2114 if (nai == null) {
2115 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002116 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002117 }
2118 return;
2119 }
2120
2121 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002122 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002123 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2124 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002125 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2126 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002127 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002128 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002129 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002130 break;
2131 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002133 if (VDBG) {
2134 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002135 "; created=" + nai.created +
2136 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002137 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002138 LinkProperties oldLp = nai.linkProperties;
2139 synchronized (nai) {
2140 nai.linkProperties = (LinkProperties)msg.obj;
2141 }
Robin Lee585e2482016-05-01 23:00:00 +01002142 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 break;
2144 }
2145 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002146 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002147 updateNetworkInfo(nai, info);
2148 break;
2149 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002150 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002151 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002152 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002153 break;
2154 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002155 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002156 try {
2157 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002158 } catch (Exception e) {
2159 // Never crash!
2160 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002161 }
2162 break;
2163 }
2164 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002165 try {
2166 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002167 } catch (Exception e) {
2168 // Never crash!
2169 loge("Exception in removeVpnUidRanges: " + e);
2170 }
2171 break;
2172 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002173 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002174 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2175 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002176 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002177 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002178 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002179 break;
2180 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002181 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002182 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2183 break;
2184 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002185 }
2186 }
2187
2188 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2189 switch (msg.what) {
2190 default:
2191 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002192 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002193 final NetworkAgentInfo nai;
2194 synchronized (mNetworkForNetId) {
2195 nai = mNetworkForNetId.get(msg.arg2);
2196 }
2197 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002198 final boolean valid =
2199 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002200 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002201 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2202 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002203 if (valid != nai.lastValidated) {
2204 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002205 nai.lastValidated = valid;
2206 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002207 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002208 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2209 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002210 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002211 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002212 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002213 Bundle redirectUrlBundle = new Bundle();
2214 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002215 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002216 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002217 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002218 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002219 if (wasValidated && !nai.lastValidated) {
2220 handleNetworkUnvalidated(nai);
2221 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002222 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002223 break;
2224 }
Paul Jensen869868be2014-05-15 10:33:05 -04002225 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002226 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002227 final boolean visible = (msg.arg1 != 0);
2228 final NetworkAgentInfo nai;
2229 synchronized (mNetworkForNetId) {
2230 nai = mNetworkForNetId.get(netId);
2231 }
Calvin On1f64f3f2016-10-11 15:10:46 -07002232 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002233 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002234 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002235 nai.lastCaptivePortalDetected = visible;
2236 nai.everCaptivePortalDetected |= visible;
Calvin On1f64f3f2016-10-11 15:10:46 -07002237 if (nai.lastCaptivePortalDetected &&
2238 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2239 if (DBG) log("Avoiding captive portal network: " + nai.name());
2240 nai.asyncChannel.sendMessage(
2241 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2242 teardownUnneededNetwork(nai);
2243 break;
2244 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002245 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002246 }
2247 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002248 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002249 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002250 if (nai == null) {
2251 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2252 break;
2253 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002254 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002255 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002256 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002257 }
Paul Jensen869868be2014-05-15 10:33:05 -04002258 }
Paul Jensen869868be2014-05-15 10:33:05 -04002259 break;
2260 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002261 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002262 return true;
2263 }
2264
Calvin On1f64f3f2016-10-11 15:10:46 -07002265 private int getCaptivePortalMode() {
2266 return Settings.Global.getInt(mContext.getContentResolver(),
2267 Settings.Global.CAPTIVE_PORTAL_MODE,
2268 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2269 }
2270
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002271 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2272 switch (msg.what) {
2273 default:
2274 return false;
2275 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2276 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2277 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2278 handleLingerComplete(nai);
2279 }
2280 break;
2281 }
2282 }
2283 return true;
2284 }
2285
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002286 @Override
2287 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002288 if (!maybeHandleAsyncChannelMessage(msg) &&
2289 !maybeHandleNetworkMonitorMessage(msg) &&
2290 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002291 maybeHandleNetworkAgentMessage(msg);
2292 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002293 }
2294 }
2295
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002296 private void updateLingerState(NetworkAgentInfo nai, long now) {
2297 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2298 // 2. If the network was lingering and there are now requests, unlinger it.
2299 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2300 // one lingered request, start lingering.
2301 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002302 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002303 if (DBG) log("Unlingering " + nai.name());
2304 nai.unlinger();
2305 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002306 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002307 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002308 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002309 nai.linger();
2310 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2311 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2312 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002313 }
2314
Robert Greenwalt7b816022014-04-18 15:25:25 -07002315 private void handleAsyncChannelHalfConnect(Message msg) {
2316 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002317 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002318 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2319 if (VDBG) log("NetworkFactory connected");
2320 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002321 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002322 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002323 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002324 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002325 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002326 }
2327 } else {
2328 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002329 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002330 }
2331 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2332 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2333 if (VDBG) log("NetworkAgent connected");
2334 // A network agent has requested a connection. Establish the connection.
2335 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2336 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2337 } else {
2338 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002339 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002340 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002341 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002342 synchronized (mNetworkForNetId) {
2343 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002344 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002345 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002346 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002347 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002348 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349 }
2350 }
2351 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002352
Robert Greenwalt7b816022014-04-18 15:25:25 -07002353 private void handleAsyncChannelDisconnected(Message msg) {
2354 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2355 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002356 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002357 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002358 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002359 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002360 // TODO - if we move the logic to the network agent (have them disconnect
2361 // because they lost all their requests or because their score isn't good)
2362 // then they would disconnect organically, report their new state and then
2363 // disconnect the channel.
2364 if (nai.networkInfo.isConnected()) {
2365 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2366 null, null);
2367 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002368 final boolean wasDefault = isDefaultNetwork(nai);
2369 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002370 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002371 // Log default network disconnection before required book-keeping.
2372 // Let rematchAllNetworksAndRequests() below record a new default network event
2373 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2374 // whose timestamps tell how long it takes to recover a default network.
2375 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002376 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002377 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002378 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2379 // by other networks that are already connected. Perhaps that can be done by
2380 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2381 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002382 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002383 mKeepaliveTracker.handleStopAllKeepalives(nai,
2384 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002385 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002386 mNetworkAgentInfos.remove(msg.replyTo);
2387 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002388 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002389 // Remove the NetworkAgent, but don't mark the netId as
2390 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002391 mNetworkForNetId.remove(nai.network.netId);
2392 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002393 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002394 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2395 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002396 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2397 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2398 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002399 sendUpdatedScoreToFactories(request, 0);
2400 }
2401 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002402 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002403 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002404 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002405 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002406 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002407 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002408 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002409 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002410 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002411 if (nai.created) {
2412 // Tell netd to clean up the configuration for this network
2413 // (routing rules, DNS, etc).
2414 // This may be slow as it requires a lot of netd shelling out to ip and
2415 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2416 // after we've rematched networks with requests which should make a potential
2417 // fallback network the default or requested a new network from the
2418 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2419 // long time.
2420 try {
2421 mNetd.removeNetwork(nai.network.netId);
2422 } catch (Exception e) {
2423 loge("Exception removing network: " + e);
2424 }
2425 }
2426 synchronized (mNetworkForNetId) {
2427 mNetIdInUse.delete(nai.network.netId);
2428 }
2429 } else {
2430 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2431 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002432 }
2433 }
2434
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002435 // If this method proves to be too slow then we can maintain a separate
2436 // pendingIntent => NetworkRequestInfo map.
2437 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2438 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2439 Intent intent = pendingIntent.getIntent();
2440 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2441 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2442 if (existingPendingIntent != null &&
2443 existingPendingIntent.getIntent().filterEquals(intent)) {
2444 return entry.getValue();
2445 }
2446 }
2447 return null;
2448 }
2449
2450 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2451 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2452
2453 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2454 if (existingRequest != null) { // remove the existing request.
2455 if (DBG) log("Replacing " + existingRequest.request + " with "
2456 + nri.request + " because their intents matched.");
2457 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2458 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002459 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002460 }
2461
Erik Klineda4bfa82015-04-30 12:58:40 +09002462 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002463 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002464 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002465 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002466 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002467 if (nri.request.networkCapabilities.hasSignalStrength() &&
2468 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2469 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002470 }
2471 }
2472 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002473 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002474 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002475 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002476 }
2477 }
2478
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002479 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2480 int callingUid) {
2481 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2482 if (nri != null) {
2483 handleReleaseNetworkRequest(nri.request, callingUid);
2484 }
2485 }
2486
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002487 // Determines whether the network is the best (or could become the best, if it validated), for
2488 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2489 // on the value of reason:
2490 //
2491 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2492 // then it should be torn down.
2493 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2494 // then it should be lingered.
2495 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2496 final int numRequests;
2497 switch (reason) {
2498 case TEARDOWN:
2499 numRequests = nai.numRequestNetworkRequests();
2500 break;
2501 case LINGER:
2502 numRequests = nai.numForegroundNetworkRequests();
2503 break;
2504 default:
2505 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2506 return true;
2507 }
2508
2509 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002510 return false;
2511 }
Paul Jensene0988542015-06-25 15:30:08 -04002512 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002513 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2514 // Background requests don't affect lingering.
2515 continue;
2516 }
2517
Paul Jensene0988542015-06-25 15:30:08 -04002518 // If this Network is already the highest scoring Network for a request, or if
2519 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002520 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002521 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002522 // Note that this catches two important cases:
2523 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2524 // is currently satisfying the request. This is desirable when
2525 // cellular ends up validating but WiFi does not.
2526 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002527 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002528 // WiFi ends up validating and out scoring cellular.
2529 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2530 nai.getCurrentScoreAsValidated())) {
2531 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002532 }
2533 }
Paul Jensene0988542015-06-25 15:30:08 -04002534 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002535 }
2536
Erik Klineacdd6392016-07-07 16:50:58 +09002537 private NetworkRequestInfo getNriForAppRequest(
2538 NetworkRequest request, int callingUid, String requestedOperation) {
2539 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2540
Robert Greenwalt9258c642014-03-26 16:47:06 -07002541 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002542 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002543 log(String.format("UID %d attempted to %s for unowned request %s",
2544 callingUid, requestedOperation, nri));
2545 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002546 }
Erik Klineacdd6392016-07-07 16:50:58 +09002547 }
2548
2549 return nri;
2550 }
2551
Erik Kline3841a482015-11-25 12:49:38 +09002552 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2553 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2554 nri.request.requestId) == null) {
2555 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2556 }
2557 }
2558
Erik Klineacdd6392016-07-07 16:50:58 +09002559 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2560 final NetworkRequestInfo nri = getNriForAppRequest(
2561 request, callingUid, "release NetworkRequest");
Erik Kline3841a482015-11-25 12:49:38 +09002562 if (nri != null) {
2563 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2564 }
2565 }
Erik Klineacdd6392016-07-07 16:50:58 +09002566
Erik Kline3841a482015-11-25 12:49:38 +09002567 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2568 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2569 if (VDBG || (DBG && nri.request.isRequest())) {
2570 log("releasing " + nri.request + " (" + logCallbackType + ")");
2571 }
Erik Klineacdd6392016-07-07 16:50:58 +09002572 nri.unlinkDeathRecipient();
Erik Kline3841a482015-11-25 12:49:38 +09002573 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002574 synchronized (mUidToNetworkRequestCount) {
2575 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2576 if (requests < 1) {
2577 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2578 nri.mUid);
2579 } else if (requests == 1) {
2580 mUidToNetworkRequestCount.removeAt(
2581 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2582 } else {
2583 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2584 }
2585 }
2586 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2587 if (nri.request.isRequest()) {
2588 boolean wasKept = false;
2589 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2590 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002591 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002592 nai.removeRequest(nri.request.requestId);
2593 if (VDBG) {
2594 log(" Removing from current network " + nai.name() +
2595 ", leaving " + nai.numNetworkRequests() + " requests.");
2596 }
2597 // If there are still lingered requests on this network, don't tear it down,
2598 // but resume lingering instead.
2599 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002600 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002601 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2602 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002603 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002604 wasKept = true;
2605 }
2606 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002607 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2608 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002609 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002610 }
Erik Klineacdd6392016-07-07 16:50:58 +09002611 }
2612
2613 // TODO: remove this code once we know that the Slog.wtf is never hit.
2614 //
2615 // Find all networks that are satisfying this request and remove the request
2616 // from their request lists.
2617 // TODO - it's my understanding that for a request there is only a single
2618 // network satisfying it, so this loop is wasteful
2619 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2620 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2621 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2622 otherNai.name() + ", but mNetworkAgentInfos says " +
2623 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002624 }
2625 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002626
Erik Klineacdd6392016-07-07 16:50:58 +09002627 // Maintain the illusion. When this request arrived, we might have pretended
2628 // that a network connected to serve it, even though the network was already
2629 // connected. Now that this request has gone away, we might have to pretend
2630 // that the network disconnected. LegacyTypeTracker will generate that
2631 // phantom disconnect for this type.
2632 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2633 boolean doRemove = true;
2634 if (wasKept) {
2635 // check if any of the remaining requests for this network are for the
2636 // same legacy type - if so, don't remove the nai
2637 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2638 NetworkRequest otherRequest = nai.requestAt(i);
2639 if (otherRequest.legacyType == nri.request.legacyType &&
2640 otherRequest.isRequest()) {
2641 if (DBG) log(" still have other legacy request - leaving");
2642 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002643 }
2644 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002645 }
2646
Erik Klineacdd6392016-07-07 16:50:58 +09002647 if (doRemove) {
2648 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002649 }
2650 }
Erik Klineacdd6392016-07-07 16:50:58 +09002651
2652 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2653 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2654 nri.request);
2655 }
2656 } else {
2657 // listens don't have a singular affectedNetwork. Check all networks to see
2658 // if this listen request applies and remove it.
2659 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2660 nai.removeRequest(nri.request.requestId);
2661 if (nri.request.networkCapabilities.hasSignalStrength() &&
2662 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2663 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2664 }
2665 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002666 }
Erik Kline3841a482015-11-25 12:49:38 +09002667 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002668 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002669
Lorenzo Colitti18660282016-07-04 12:55:44 +09002670 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002671 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2672 enforceConnectivityInternalPermission();
2673 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2674 accept ? 1 : 0, always ? 1: 0, network));
2675 }
2676
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002677 @Override
2678 public void setAvoidUnvalidated(Network network) {
2679 enforceConnectivityInternalPermission();
2680 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2681 }
2682
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002683 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2684 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2685 " accept=" + accept + " always=" + always);
2686
2687 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2688 if (nai == null) {
2689 // Nothing to do.
2690 return;
2691 }
2692
2693 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002694 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002695 return;
2696 }
2697
2698 if (!nai.networkMisc.explicitlySelected) {
2699 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2700 }
2701
2702 if (accept != nai.networkMisc.acceptUnvalidated) {
2703 int oldScore = nai.getCurrentScore();
2704 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002705 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002706 sendUpdatedScoreToFactories(nai);
2707 }
2708
2709 if (always) {
2710 nai.asyncChannel.sendMessage(
2711 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2712 }
2713
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002714 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002715 // Tell the NetworkAgent to not automatically reconnect to the network.
2716 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2717 // Teardown the nework.
2718 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002719 }
2720
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002721 }
2722
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002723 private void handleSetAvoidUnvalidated(Network network) {
2724 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2725 if (nai == null || nai.lastValidated) {
2726 // Nothing to do. The network either disconnected or revalidated.
2727 return;
2728 }
2729 if (!nai.avoidUnvalidated) {
2730 int oldScore = nai.getCurrentScore();
2731 nai.avoidUnvalidated = true;
2732 rematchAllNetworksAndRequests(nai, oldScore);
2733 sendUpdatedScoreToFactories(nai);
2734 }
2735 }
2736
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002737 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002738 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002739 mHandler.sendMessageDelayed(
2740 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2741 PROMPT_UNVALIDATED_DELAY_MS);
2742 }
2743
Hugo Benichic8e9e122016-09-14 23:23:08 +00002744 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002745 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002746 }
2747
Erik Kline065ab6e2016-10-02 18:02:14 +09002748 private void rematchForAvoidBadWifiUpdate() {
2749 rematchAllNetworksAndRequests(null, 0);
2750 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2751 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2752 sendUpdatedScoreToFactories(nai);
2753 }
2754 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002755 }
2756
Erik Kline065ab6e2016-10-02 18:02:14 +09002757 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002758 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002759 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002760 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002761 if (!configRestrict) {
2762 pw.println("Bad Wi-Fi avoidance: unrestricted");
2763 return;
2764 }
2765
2766 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2767 pw.increaseIndent();
2768 pw.println("Config restrict: " + configRestrict);
2769
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002770 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002771 String description;
2772 // Can't use a switch statement because strings are legal case labels, but null is not.
2773 if ("0".equals(value)) {
2774 description = "get stuck";
2775 } else if (value == null) {
2776 description = "prompt";
2777 } else if ("1".equals(value)) {
2778 description = "avoid";
2779 } else {
2780 description = value + " (?)";
2781 }
2782 pw.println("User setting: " + description);
2783 pw.println("Network overrides:");
2784 pw.increaseIndent();
2785 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2786 if (nai.avoidUnvalidated) {
2787 pw.println(nai.name());
2788 }
2789 }
2790 pw.decreaseIndent();
2791 pw.decreaseIndent();
2792 }
2793
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002794 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2795 final String action;
2796 switch (type) {
2797 case NO_INTERNET:
2798 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2799 break;
2800 case LOST_INTERNET:
2801 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2802 break;
2803 default:
2804 Slog.wtf(TAG, "Unknown notification type " + type);
2805 return;
2806 }
2807
2808 Intent intent = new Intent(action);
2809 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2810 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2811 intent.setClassName("com.android.settings",
2812 "com.android.settings.wifi.WifiNoInternetDialog");
2813
2814 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2815 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2816 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2817 }
2818
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002819 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002820 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002821 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2822
2823 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2824 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002825 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002826 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002827 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2828 return;
2829 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002830 showValidationNotification(nai, NotificationType.NO_INTERNET);
2831 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002832
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002833 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2834 NetworkCapabilities nc = nai.networkCapabilities;
2835 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002836
Erik Kline065ab6e2016-10-02 18:02:14 +09002837 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002838 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002839 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2840 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002841 }
2842
Lorenzo Colitti46aa9c02017-01-24 18:08:41 +09002843 @Override
2844 public int getMultipathPreference(Network network) {
2845 enforceAccessPermission();
2846
2847 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2848 if (nai != null && !nai.networkInfo.isMetered()) {
2849 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2850 }
2851
2852 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2853 }
2854
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002855 private class InternalHandler extends Handler {
2856 public InternalHandler(Looper looper) {
2857 super(looper);
2858 }
2859
2860 @Override
2861 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002862 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002863 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002864 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002865 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002866 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002867 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002868 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002869 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002870 break;
2871 }
Jason Monkdecd2952013-10-10 14:02:51 -04002872 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002873 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002874 break;
2875 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002876 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002877 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2878 break;
2879 }
2880 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2881 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002882 break;
2883 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002884 case EVENT_REGISTER_NETWORK_AGENT: {
2885 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2886 break;
2887 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002888 case EVENT_REGISTER_NETWORK_REQUEST:
2889 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002890 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002891 break;
2892 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002893 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2894 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002895 handleRegisterNetworkRequestWithIntent(msg);
2896 break;
2897 }
Erik Kline3841a482015-11-25 12:49:38 +09002898 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2899 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2900 handleTimedOutNetworkRequest(nri);
2901 break;
2902 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002903 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2904 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2905 break;
2906 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002907 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002908 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002909 break;
2910 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002911 case EVENT_SET_ACCEPT_UNVALIDATED: {
2912 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2913 break;
2914 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002915 case EVENT_SET_AVOID_UNVALIDATED: {
2916 handleSetAvoidUnvalidated((Network) msg.obj);
2917 break;
2918 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002919 case EVENT_PROMPT_UNVALIDATED: {
2920 handlePromptUnvalidated((Network) msg.obj);
2921 break;
2922 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002923 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2924 handleMobileDataAlwaysOn();
2925 break;
2926 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002927 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2928 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2929 mKeepaliveTracker.handleStartKeepalive(msg);
2930 break;
2931 }
2932 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2933 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2934 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2935 int slot = msg.arg1;
2936 int reason = msg.arg2;
2937 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2938 break;
2939 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002940 case EVENT_SYSTEM_READY: {
2941 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2942 nai.networkMonitor.systemReady = true;
2943 }
2944 break;
2945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 }
2947 }
2948 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002949
2950 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002951 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002952 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002953 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002954 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002955 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002956 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002957 } else {
2958 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2959 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002960 }
2961
2962 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002963 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002964 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002965 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002966
2967 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002968 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002969 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002970 } else {
2971 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2972 }
2973 }
2974
2975 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002976 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002977 public int getLastTetherError(String iface) {
2978 enforceTetherAccessPermission();
2979
2980 if (isTetheringSupported()) {
2981 return mTethering.getLastTetherError(iface);
2982 } else {
2983 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2984 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002985 }
2986
2987 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002988 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002989 public String[] getTetherableUsbRegexs() {
2990 enforceTetherAccessPermission();
2991 if (isTetheringSupported()) {
2992 return mTethering.getTetherableUsbRegexs();
2993 } else {
2994 return new String[0];
2995 }
2996 }
2997
Lorenzo Colitti18660282016-07-04 12:55:44 +09002998 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002999 public String[] getTetherableWifiRegexs() {
3000 enforceTetherAccessPermission();
3001 if (isTetheringSupported()) {
3002 return mTethering.getTetherableWifiRegexs();
3003 } else {
3004 return new String[0];
3005 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003006 }
3007
Lorenzo Colitti18660282016-07-04 12:55:44 +09003008 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003009 public String[] getTetherableBluetoothRegexs() {
3010 enforceTetherAccessPermission();
3011 if (isTetheringSupported()) {
3012 return mTethering.getTetherableBluetoothRegexs();
3013 } else {
3014 return new String[0];
3015 }
3016 }
3017
Lorenzo Colitti18660282016-07-04 12:55:44 +09003018 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003019 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003020 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003021 if (isTetheringSupported()) {
3022 return mTethering.setUsbTethering(enable);
3023 } else {
3024 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3025 }
3026 }
3027
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003028 // TODO - move iface listing, queries, etc to new module
3029 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003030 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003031 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003032 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003033 return mTethering.getTetherableIfaces();
3034 }
3035
Lorenzo Colitti18660282016-07-04 12:55:44 +09003036 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003037 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003038 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003039 return mTethering.getTetheredIfaces();
3040 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003041
Lorenzo Colitti18660282016-07-04 12:55:44 +09003042 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003043 public String[] getTetheringErroredIfaces() {
3044 enforceTetherAccessPermission();
3045 return mTethering.getErroredIfaces();
3046 }
3047
Lorenzo Colitti18660282016-07-04 12:55:44 +09003048 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003049 public String[] getTetheredDhcpRanges() {
3050 enforceConnectivityInternalPermission();
3051 return mTethering.getTetheredDhcpRanges();
3052 }
3053
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003054 // if ro.tether.denied = true we default to no tethering
3055 // gservices could set the secure setting to 1 though to enable it on a build where it
3056 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003057 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003058 public boolean isTetheringSupported() {
3059 enforceTetherAccessPermission();
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09003060 int defaultVal = (mSystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003061 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003062 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3063 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003064
3065 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3066 boolean adminUser = false;
3067 final long token = Binder.clearCallingIdentity();
3068 try {
3069 adminUser = mUserManager.isAdminUser();
3070 } finally {
3071 Binder.restoreCallingIdentity(token);
3072 }
3073
3074 return tetherEnabledInSettings && adminUser &&
Erik Klined781fba2017-01-23 13:01:58 +09003075 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003076 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003077
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003078 @Override
Hugo Benichib55fb222017-03-10 14:20:57 +09003079 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003080 ConnectivityManager.enforceTetherChangePermission(mContext);
3081 if (!isTetheringSupported()) {
3082 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3083 return;
3084 }
3085 mTethering.startTethering(type, receiver, showProvisioningUi);
3086 }
3087
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003088 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003089 public void stopTethering(int type) {
3090 ConnectivityManager.enforceTetherChangePermission(mContext);
3091 mTethering.stopTethering(type);
3092 }
3093
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003094 // Called when we lose the default network and have no replacement yet.
3095 // This will automatically be cleared after X seconds or a new default network
3096 // becomes CONNECTED, whichever happens first. The timer is started by the
3097 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003098 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003099 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003100 if (mNetTransitionWakeLock.isHeld()) {
3101 return;
3102 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003103 mNetTransitionWakeLock.acquire();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003104 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003105 mWakelockLogs.log("ACQUIRE for " + forWhom);
3106 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3107 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003108 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003109
Hugo Benichi4c31b342017-03-30 23:18:10 +09003110 // Called when we gain a new default network to release the network transition wakelock in a
3111 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3112 // message is cancelled.
3113 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003114 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003115 if (!mNetTransitionWakeLock.isHeld()) {
3116 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003117 }
3118 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003119 // Cancel self timeout on wakelock hold.
3120 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3121 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3122 mHandler.sendMessageDelayed(msg, 1000);
3123 }
3124
3125 // Called when either message of ensureNetworkTransitionWakelock or
3126 // scheduleReleaseNetworkTransitionWakelock is processed.
3127 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3128 String event = eventName(eventId);
3129 synchronized (this) {
3130 if (!mNetTransitionWakeLock.isHeld()) {
3131 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3132 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3133 return;
3134 }
3135 mNetTransitionWakeLock.release();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003136 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003137 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003138 }
3139
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003140 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003141 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003142 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003143 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003144 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003145 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003146 }
3147
Lorenzo Colitti18660282016-07-04 12:55:44 +09003148 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003149 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003150 enforceAccessPermission();
3151 enforceInternetPermission();
3152
Hugo Benichi29551722017-04-06 16:01:44 +09003153 // TODO: execute this logic on ConnectivityService handler.
3154 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003155 if (network == null) {
3156 nai = getDefaultNetwork();
3157 } else {
3158 nai = getNetworkAgentInfoForNetwork(network);
3159 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003160 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3161 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3162 return;
3163 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003164 // Revalidate if the app report does not match our current validated state.
Hugo Benichi29551722017-04-06 16:01:44 +09003165 if (hasConnectivity == nai.lastValidated) {
3166 return;
3167 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003168 final int uid = Binder.getCallingUid();
3169 if (DBG) {
3170 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3171 ") by " + uid);
3172 }
Hugo Benichi29551722017-04-06 16:01:44 +09003173 // Validating a network that has not yet connected could result in a call to
3174 // rematchNetworkAndRequests() which is not meant to work on such networks.
3175 if (!nai.everConnected) {
3176 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003177 }
Hugo Benichi29551722017-04-06 16:01:44 +09003178 LinkProperties lp = getLinkProperties(nai);
3179 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3180 return;
3181 }
3182 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003183 }
3184
Paul Jensencee9b512015-05-06 07:32:40 -04003185 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003186 // this information is already available as a world read/writable jvm property
3187 // so this API change wouldn't have a benifit. It also breaks the passing
3188 // of proxy info to all the JVMs.
3189 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003190 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003191 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003192 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3193 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003194 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003195 }
3196
Lorenzo Colitti18660282016-07-04 12:55:44 +09003197 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003198 public ProxyInfo getProxyForNetwork(Network network) {
3199 if (network == null) return getDefaultProxy();
3200 final ProxyInfo globalProxy = getGlobalProxy();
3201 if (globalProxy != null) return globalProxy;
3202 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3203 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3204 // caller may not have.
3205 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3206 if (nai == null) return null;
3207 synchronized (nai) {
3208 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3209 if (proxyInfo == null) return null;
3210 return new ProxyInfo(proxyInfo);
3211 }
3212 }
3213
Paul Jensene0bef712014-12-10 15:12:18 -05003214 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3215 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3216 // proxy is null then there is no proxy in place).
3217 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3218 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3219 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3220 proxy = null;
3221 }
3222 return proxy;
3223 }
3224
3225 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3226 // better for determining if a new proxy broadcast is necessary:
3227 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3228 // avoid unnecessary broadcasts.
3229 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3230 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3231 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3232 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3233 // all set.
3234 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3235 a = canonicalizeProxyInfo(a);
3236 b = canonicalizeProxyInfo(b);
3237 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3238 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3239 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3240 }
3241
Jason Monk207900c2014-04-25 15:00:09 -04003242 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003243 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003244
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003245 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003246 if (proxyProperties == mGlobalProxy) return;
3247 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3248 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3249
3250 String host = "";
3251 int port = 0;
3252 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003253 String pacFileUrl = "";
3254 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003255 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003256 if (!proxyProperties.isValid()) {
3257 if (DBG)
3258 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3259 return;
3260 }
Jason Monk207900c2014-04-25 15:00:09 -04003261 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003262 host = mGlobalProxy.getHost();
3263 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003264 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003265 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003266 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003267 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003268 } else {
3269 mGlobalProxy = null;
3270 }
3271 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003272 final long token = Binder.clearCallingIdentity();
3273 try {
3274 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3275 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3276 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3277 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003278 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003279 } finally {
3280 Binder.restoreCallingIdentity(token);
3281 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003282
Jason Monkcf0f97a2014-10-02 15:39:38 -04003283 if (mGlobalProxy == null) {
3284 proxyProperties = mDefaultProxy;
3285 }
3286 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003287 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003288 }
3289
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003290 private void loadGlobalProxy() {
3291 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003292 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3293 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3294 String exclList = Settings.Global.getString(res,
3295 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003296 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3297 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003298 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003299 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003300 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003301 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003302 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003303 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003304 if (!proxyProperties.isValid()) {
3305 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3306 return;
3307 }
3308
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003309 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003310 mGlobalProxy = proxyProperties;
3311 }
3312 }
3313 }
3314
Jason Monk207900c2014-04-25 15:00:09 -04003315 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003316 // this information is already available as a world read/writable jvm property
3317 // so this API change wouldn't have a benifit. It also breaks the passing
3318 // of proxy info to all the JVMs.
3319 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003320 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003321 return mGlobalProxy;
3322 }
3323 }
3324
Jason Monk207900c2014-04-25 15:00:09 -04003325 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003326 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003327 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003328 proxy = null;
3329 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003330 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003331 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003332 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003333 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003334 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3335 return;
3336 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003337
3338 // This call could be coming from the PacManager, containing the port of the local
3339 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3340 // global (to get the correct local port), and send a broadcast.
3341 // TODO: Switch PacManager to have its own message to send back rather than
3342 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003343 if ((mGlobalProxy != null) && (proxy != null)
3344 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003345 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3346 mGlobalProxy = proxy;
3347 sendProxyBroadcast(mGlobalProxy);
3348 return;
3349 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003350 mDefaultProxy = proxy;
3351
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003352 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003353 if (!mDefaultProxyDisabled) {
3354 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003355 }
3356 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003357 }
3358
Paul Jensene0bef712014-12-10 15:12:18 -05003359 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3360 // This method gets called when any network changes proxy, but the broadcast only ever contains
3361 // the default proxy (even if it hasn't changed).
3362 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3363 // world where an app might be bound to a non-default network.
3364 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3365 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3366 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3367
3368 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3369 sendProxyBroadcast(getDefaultProxy());
3370 }
3371 }
3372
Robert Greenwalt434203a2010-10-11 16:00:27 -07003373 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003374 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3375 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003376 if (!TextUtils.isEmpty(proxy)) {
3377 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003378 if (data.length == 0) {
3379 return;
3380 }
3381
Robert Greenwalt434203a2010-10-11 16:00:27 -07003382 String proxyHost = data[0];
3383 int proxyPort = 8080;
3384 if (data.length > 1) {
3385 try {
3386 proxyPort = Integer.parseInt(data[1]);
3387 } catch (NumberFormatException e) {
3388 return;
3389 }
3390 }
Jason Monk207900c2014-04-25 15:00:09 -04003391 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003392 setGlobalProxy(p);
3393 }
3394 }
3395
Jason Monk207900c2014-04-25 15:00:09 -04003396 private void sendProxyBroadcast(ProxyInfo proxy) {
3397 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003398 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003399 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003400 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003401 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3402 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003403 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003404 final long ident = Binder.clearCallingIdentity();
3405 try {
3406 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3407 } finally {
3408 Binder.restoreCallingIdentity(ident);
3409 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003410 }
3411
3412 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003413 final private HashMap<Uri, Integer> mUriEventMap;
3414 final private Context mContext;
3415 final private Handler mHandler;
3416
3417 SettingsObserver(Context context, Handler handler) {
3418 super(null);
3419 mUriEventMap = new HashMap<Uri, Integer>();
3420 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003421 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003422 }
3423
Erik Klineda4bfa82015-04-30 12:58:40 +09003424 void observe(Uri uri, int what) {
3425 mUriEventMap.put(uri, what);
3426 final ContentResolver resolver = mContext.getContentResolver();
3427 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003428 }
3429
3430 @Override
3431 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003432 Slog.wtf(TAG, "Should never be reached.");
3433 }
3434
3435 @Override
3436 public void onChange(boolean selfChange, Uri uri) {
3437 final Integer what = mUriEventMap.get(uri);
3438 if (what != null) {
3439 mHandler.obtainMessage(what.intValue()).sendToTarget();
3440 } else {
3441 loge("No matching event to send for URI=" + uri);
3442 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003443 }
3444 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003445
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003446 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003447 Slog.d(TAG, s);
3448 }
3449
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003450 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003451 Slog.e(TAG, s);
3452 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003453
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003454 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003455 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003456 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3457 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3458 *
3459 * @param oldPackage Package name of the application which currently controls VPN, which will
3460 * be replaced. If there is no such application, this should should either be
3461 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3462 * @param newPackage Package name of the application which should gain control of VPN, or
3463 * {@code null} to disable.
3464 * @param userId User for whom to prepare the new VPN.
3465 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003466 * @hide
3467 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003468 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003469 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3470 int userId) {
3471 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003472 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003473
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003474 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003475 Vpn vpn = mVpns.get(userId);
3476 if (vpn != null) {
3477 return vpn.prepare(oldPackage, newPackage);
3478 } else {
3479 return false;
3480 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003481 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003482 }
3483
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003484 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003485 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3486 * This method is used by system-privileged apps.
3487 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3488 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3489 *
3490 * @param packageName The package for which authorization state should change.
3491 * @param userId User for whom {@code packageName} is installed.
3492 * @param authorized {@code true} if this app should be able to start a VPN connection without
3493 * explicit user approval, {@code false} if not.
3494 *
Jeff Davidson05542602014-08-11 14:07:27 -07003495 * @hide
3496 */
3497 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003498 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3499 enforceCrossUserPermission(userId);
3500
Jeff Davidson05542602014-08-11 14:07:27 -07003501 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003502 Vpn vpn = mVpns.get(userId);
3503 if (vpn != null) {
3504 vpn.setPackageAuthorization(packageName, authorized);
3505 }
Jeff Davidson05542602014-08-11 14:07:27 -07003506 }
3507 }
3508
3509 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003510 * Configure a TUN interface and return its file descriptor. Parameters
3511 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003512 * and not available in ConnectivityManager. Permissions are checked in
3513 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003514 * @hide
3515 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003516 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003517 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003518 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003519 int user = UserHandle.getUserId(Binder.getCallingUid());
3520 synchronized(mVpns) {
3521 return mVpns.get(user).establish(config);
3522 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003523 }
3524
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003525 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003526 * Start legacy VPN, controlling native daemons as needed. Creates a
3527 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003528 */
3529 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003530 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003531 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003532 final LinkProperties egress = getActiveLinkProperties();
3533 if (egress == null) {
3534 throw new IllegalStateException("Missing active network connection");
3535 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003536 int user = UserHandle.getUserId(Binder.getCallingUid());
3537 synchronized(mVpns) {
3538 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3539 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003540 }
3541
3542 /**
3543 * Return the information of the ongoing legacy VPN. This method is used
3544 * by VpnSettings and not available in ConnectivityManager. Permissions
3545 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003546 */
3547 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003548 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3549 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003550
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003551 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003552 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003553 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003554 }
3555
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003556 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003557 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3558 * and not available in ConnectivityManager.
3559 */
3560 @Override
3561 public VpnInfo[] getAllVpnInfo() {
3562 enforceConnectivityInternalPermission();
3563 if (mLockdownEnabled) {
3564 return new VpnInfo[0];
3565 }
3566
3567 synchronized(mVpns) {
3568 List<VpnInfo> infoList = new ArrayList<>();
3569 for (int i = 0; i < mVpns.size(); i++) {
3570 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3571 if (info != null) {
3572 infoList.add(info);
3573 }
3574 }
3575 return infoList.toArray(new VpnInfo[infoList.size()]);
3576 }
3577 }
3578
3579 /**
3580 * @return VPN information for accounting, or null if we can't retrieve all required
3581 * information, e.g primary underlying iface.
3582 */
3583 @Nullable
3584 private VpnInfo createVpnInfo(Vpn vpn) {
3585 VpnInfo info = vpn.getVpnInfo();
3586 if (info == null) {
3587 return null;
3588 }
3589 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3590 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3591 // the underlyingNetworks list.
3592 if (underlyingNetworks == null) {
3593 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3594 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3595 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3596 }
3597 } else if (underlyingNetworks.length > 0) {
3598 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3599 if (linkProperties != null) {
3600 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3601 }
3602 }
3603 return info.primaryUnderlyingIface == null ? null : info;
3604 }
3605
3606 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003607 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3608 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003609 * Permissions are checked in Vpn class.
3610 * @hide
3611 */
3612 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003613 public VpnConfig getVpnConfig(int userId) {
3614 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003615 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003616 Vpn vpn = mVpns.get(userId);
3617 if (vpn != null) {
3618 return vpn.getVpnConfig();
3619 } else {
3620 return null;
3621 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003622 }
3623 }
3624
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003625 @Override
3626 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003627 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3628 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3629 return false;
3630 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003631
3632 // Tear down existing lockdown if profile was removed
3633 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3634 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003635 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3636 if (profileTag == null) {
3637 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3638 return false;
3639 }
3640 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003641 final VpnProfile profile = VpnProfile.decode(
3642 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003643 if (profile == null) {
3644 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3645 setLockdownTracker(null);
3646 return true;
3647 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003648 int user = UserHandle.getUserId(Binder.getCallingUid());
3649 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003650 Vpn vpn = mVpns.get(user);
3651 if (vpn == null) {
3652 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3653 return false;
3654 }
3655 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003656 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003657 } else {
3658 setLockdownTracker(null);
3659 }
3660
3661 return true;
3662 }
3663
3664 /**
3665 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3666 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3667 */
3668 private void setLockdownTracker(LockdownVpnTracker tracker) {
3669 // Shutdown any existing tracker
3670 final LockdownVpnTracker existing = mLockdownTracker;
3671 mLockdownTracker = null;
3672 if (existing != null) {
3673 existing.shutdown();
3674 }
3675
3676 try {
3677 if (tracker != null) {
3678 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003679 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003680 mLockdownTracker = tracker;
3681 mLockdownTracker.init();
3682 } else {
3683 mNetd.setFirewallEnabled(false);
3684 }
3685 } catch (RemoteException e) {
3686 // ignored; NMS lives inside system_server
3687 }
3688 }
3689
3690 private void throwIfLockdownEnabled() {
3691 if (mLockdownEnabled) {
3692 throw new IllegalStateException("Unavailable in lockdown mode");
3693 }
3694 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003695
Robin Lee244ce8e2016-01-05 18:03:46 +00003696 /**
Robin Lee17e61832016-05-09 13:46:28 +01003697 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3698 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003699 *
Robin Lee17e61832016-05-09 13:46:28 +01003700 * @return {@code true} if the service was started, the service was already connected, or there
3701 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003702 */
Robin Lee17e61832016-05-09 13:46:28 +01003703 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003704 synchronized (mVpns) {
3705 Vpn vpn = mVpns.get(userId);
3706 if (vpn == null) {
3707 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3708 // exists already.
3709 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3710 return false;
3711 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003712
Robin Lee812800c2016-05-13 15:38:08 +01003713 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003714 }
3715 }
3716
3717 @Override
Robin Leedc679712016-05-03 13:23:03 +01003718 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003719 enforceConnectivityInternalPermission();
3720 enforceCrossUserPermission(userId);
3721
3722 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3723 if (LockdownVpnTracker.isEnabled()) {
3724 return false;
3725 }
3726
Robin Lee244ce8e2016-01-05 18:03:46 +00003727 synchronized (mVpns) {
3728 Vpn vpn = mVpns.get(userId);
3729 if (vpn == null) {
3730 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3731 return false;
3732 }
Robin Lee17e61832016-05-09 13:46:28 +01003733 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003734 return false;
3735 }
Robin Lee17e61832016-05-09 13:46:28 +01003736 if (!startAlwaysOnVpn(userId)) {
3737 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003738 return false;
3739 }
3740 }
3741 return true;
3742 }
3743
3744 @Override
3745 public String getAlwaysOnVpnPackage(int userId) {
3746 enforceConnectivityInternalPermission();
3747 enforceCrossUserPermission(userId);
3748
3749 synchronized (mVpns) {
3750 Vpn vpn = mVpns.get(userId);
3751 if (vpn == null) {
3752 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3753 return null;
3754 }
3755 return vpn.getAlwaysOnPackage();
3756 }
3757 }
3758
Wink Savilleab9321d2013-06-29 21:10:57 -07003759 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003760 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003761 // TODO: Remove? Any reason to trigger a provisioning check?
3762 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003763 }
3764
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003765 /** Location to an updatable file listing carrier provisioning urls.
3766 * An example:
3767 *
3768 * <?xml version="1.0" encoding="utf-8"?>
3769 * <provisioningUrls>
3770 * <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 -07003771 * </provisioningUrls>
3772 */
3773 private static final String PROVISIONING_URL_PATH =
3774 "/data/misc/radio/provisioning_urls.xml";
3775 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003776
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003777 /** XML tag for root element. */
3778 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3779 /** XML tag for individual url */
3780 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003781 /** XML attribute for mcc */
3782 private static final String ATTR_MCC = "mcc";
3783 /** XML attribute for mnc */
3784 private static final String ATTR_MNC = "mnc";
3785
Paul Jensen434dde82015-06-11 09:43:30 -04003786 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003787 FileReader fileReader = null;
3788 XmlPullParser parser = null;
3789 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003790
3791 try {
3792 fileReader = new FileReader(mProvisioningUrlFile);
3793 parser = Xml.newPullParser();
3794 parser.setInput(fileReader);
3795 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3796
3797 while (true) {
3798 XmlUtils.nextElement(parser);
3799
3800 String element = parser.getName();
3801 if (element == null) break;
3802
Paul Jensen434dde82015-06-11 09:43:30 -04003803 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003804 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3805 try {
3806 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3807 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3808 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3809 parser.next();
3810 if (parser.getEventType() == XmlPullParser.TEXT) {
3811 return parser.getText();
3812 }
3813 }
3814 }
3815 } catch (NumberFormatException e) {
3816 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3817 }
3818 }
3819 }
3820 return null;
3821 } catch (FileNotFoundException e) {
3822 loge("Carrier Provisioning Urls file not found");
3823 } catch (XmlPullParserException e) {
3824 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3825 } catch (IOException e) {
3826 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3827 } finally {
3828 if (fileReader != null) {
3829 try {
3830 fileReader.close();
3831 } catch (IOException e) {}
3832 }
3833 }
3834 return null;
3835 }
3836
Wink Saville42d4f082013-07-20 20:31:59 -07003837 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003838 public String getMobileProvisioningUrl() {
3839 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003840 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003841 if (TextUtils.isEmpty(url)) {
3842 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003843 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003844 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003845 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003846 }
Wink Saville8cf35602013-07-10 23:00:07 -07003847 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003848 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003849 String phoneNumber = mTelephonyManager.getLine1Number();
3850 if (TextUtils.isEmpty(phoneNumber)) {
3851 phoneNumber = "0000000000";
3852 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003853 url = String.format(url,
3854 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3855 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003856 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003857 }
3858
Wink Savilleab9321d2013-06-29 21:10:57 -07003859 return url;
3860 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003861
Wink Saville948282b2013-08-29 08:55:16 -07003862 @Override
3863 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003864 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003865 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003866 final long ident = Binder.clearCallingIdentity();
3867 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003868 // Concatenate the range of types onto the range of NetIDs.
3869 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3870 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003871 } finally {
3872 Binder.restoreCallingIdentity(ident);
3873 }
Wink Saville948282b2013-08-29 08:55:16 -07003874 }
Wink Saville7788c612013-08-29 14:57:08 -07003875
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003876 @Override
3877 public void setAirplaneMode(boolean enable) {
3878 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003879 final long ident = Binder.clearCallingIdentity();
3880 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003881 final ContentResolver cr = mContext.getContentResolver();
3882 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3883 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3884 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003885 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003886 } finally {
3887 Binder.restoreCallingIdentity(ident);
3888 }
3889 }
3890
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003891 private void onUserStart(int userId) {
3892 synchronized(mVpns) {
3893 Vpn userVpn = mVpns.get(userId);
3894 if (userVpn != null) {
3895 loge("Starting user already has a VPN");
3896 return;
3897 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003898 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003899 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003900 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003901 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3902 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003903 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003904 }
3905
3906 private void onUserStop(int userId) {
3907 synchronized(mVpns) {
3908 Vpn userVpn = mVpns.get(userId);
3909 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003910 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003911 return;
3912 }
Robin Lee17e61832016-05-09 13:46:28 +01003913 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003914 mVpns.delete(userId);
3915 }
3916 }
3917
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003918 private void onUserAdded(int userId) {
3919 synchronized(mVpns) {
3920 final int vpnsSize = mVpns.size();
3921 for (int i = 0; i < vpnsSize; i++) {
3922 Vpn vpn = mVpns.valueAt(i);
3923 vpn.onUserAdded(userId);
3924 }
3925 }
3926 }
3927
3928 private void onUserRemoved(int userId) {
3929 synchronized(mVpns) {
3930 final int vpnsSize = mVpns.size();
3931 for (int i = 0; i < vpnsSize; i++) {
3932 Vpn vpn = mVpns.valueAt(i);
3933 vpn.onUserRemoved(userId);
3934 }
3935 }
3936 }
3937
Robin Lee89e7a692016-02-29 14:38:17 +00003938 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003939 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3940 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3941 updateLockdownVpn();
3942 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003943 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003944 }
3945 }
3946
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003947 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3948 @Override
3949 public void onReceive(Context context, Intent intent) {
3950 final String action = intent.getAction();
3951 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3952 if (userId == UserHandle.USER_NULL) return;
3953
Robin Lee323f29d2016-05-04 16:38:06 +01003954 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003955 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003956 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003957 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003958 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3959 onUserAdded(userId);
3960 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3961 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003962 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3963 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003964 }
3965 }
3966 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003967
Robin Lee95204e02017-01-27 11:59:22 +00003968 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3969 @Override
3970 public void onReceive(Context context, Intent intent) {
3971 // Try creating lockdown tracker, since user present usually means
3972 // unlocked keystore.
3973 updateLockdownVpn();
3974 mContext.unregisterReceiver(this);
3975 }
3976 };
3977
Robert Greenwalta67be032014-05-16 15:49:14 -07003978 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3979 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003980 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3981 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003982
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003983 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3984 // Map from UID to number of NetworkRequests that UID has filed.
3985 @GuardedBy("mUidToNetworkRequestCount")
3986 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3987
Robert Greenwalta67be032014-05-16 15:49:14 -07003988 private static class NetworkFactoryInfo {
3989 public final String name;
3990 public final Messenger messenger;
3991 public final AsyncChannel asyncChannel;
3992
3993 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3994 this.name = name;
3995 this.messenger = messenger;
3996 this.asyncChannel = asyncChannel;
3997 }
3998 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003999
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004000 private void ensureNetworkRequestHasType(NetworkRequest request) {
4001 if (request.type == NetworkRequest.Type.NONE) {
4002 throw new IllegalArgumentException(
4003 "All NetworkRequests in ConnectivityService must have a type");
4004 }
4005 }
4006
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004007 /**
4008 * Tracks info about the requester.
4009 * Also used to notice when the calling process dies so we can self-expire
4010 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004011 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004012 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004013 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004014 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004015 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004016 final int mPid;
4017 final int mUid;
4018 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004019
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004020 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004021 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004022 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004023 mPendingIntent = pi;
4024 messenger = null;
4025 mBinder = null;
4026 mPid = getCallingPid();
4027 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004028 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004029 }
4030
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004031 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004032 super();
4033 messenger = m;
4034 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004035 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004036 mBinder = binder;
4037 mPid = getCallingPid();
4038 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004039 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004040 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004041
4042 try {
4043 mBinder.linkToDeath(this, 0);
4044 } catch (RemoteException e) {
4045 binderDied();
4046 }
4047 }
4048
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004049 private void enforceRequestCountLimit() {
4050 synchronized (mUidToNetworkRequestCount) {
4051 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4052 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4053 throw new IllegalArgumentException("Too many NetworkRequests filed");
4054 }
4055 mUidToNetworkRequestCount.put(mUid, networkRequests);
4056 }
4057 }
4058
Robert Greenwalt9258c642014-03-26 16:47:06 -07004059 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004060 if (mBinder != null) {
4061 mBinder.unlinkToDeath(this, 0);
4062 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004063 }
4064
4065 public void binderDied() {
4066 log("ConnectivityService NetworkRequestInfo binderDied(" +
4067 request + ", " + mBinder + ")");
4068 releaseNetworkRequest(request);
4069 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004070
4071 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004072 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004073 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004074 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004075 }
4076
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004077 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4078 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4079 if (badCapability != null) {
4080 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004081 }
4082 }
4083
Erik Kline9d598e12015-07-13 16:37:51 +09004084 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004085 final SortedSet<Integer> thresholds = new TreeSet();
4086 synchronized (nai) {
4087 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4088 if (nri.request.networkCapabilities.hasSignalStrength() &&
4089 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4090 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4091 }
4092 }
4093 }
Erik Kline9d598e12015-07-13 16:37:51 +09004094 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004095 }
4096
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004097 private void updateSignalStrengthThresholds(
4098 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4099 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004100 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004101 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4102
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004103 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004104 String detail;
4105 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4106 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4107 } else {
4108 detail = reason;
4109 }
4110 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4111 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4112 }
4113
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004114 nai.asyncChannel.sendMessage(
4115 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004116 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004117 }
4118
Robert Greenwalt9258c642014-03-26 16:47:06 -07004119 @Override
4120 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004121 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004122 final NetworkRequest.Type type = (networkCapabilities == null)
4123 ? NetworkRequest.Type.TRACK_DEFAULT
4124 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004125 // If the requested networkCapabilities is null, take them instead from
4126 // the default network request. This allows callers to keep track of
4127 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004128 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004129 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4130 enforceAccessPermission();
4131 } else {
4132 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4133 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004134 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4135 // of the app when the request is filed, but we never change the request if the app
4136 // changes network state. http://b/29964605
4137 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004138 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004139 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004140
Etan Cohenba07c8c2017-02-05 10:42:27 -08004141 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004142 throw new IllegalArgumentException("Bad timeout specified");
4143 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004144
Etan Cohena7434272017-04-03 12:17:51 -07004145 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4146 networkCapabilities.getNetworkSpecifier());
Etan Cohenddb9ef02015-11-18 10:56:15 -08004147
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004148 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004149 nextNetworkRequestId(), type);
4150 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004151 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004152
4153 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004154 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004155 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004156 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004157 }
4158 return networkRequest;
4159 }
4160
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004161 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004162 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004163 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004164 } else {
4165 enforceChangePermission();
4166 }
4167 }
4168
fenglub15e72b2015-03-20 11:29:56 -07004169 @Override
fengludb571472015-04-21 17:12:05 -07004170 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004171 enforceAccessPermission();
4172 NetworkAgentInfo nai = null;
4173 if (network == null) {
4174 return false;
4175 }
4176 synchronized (mNetworkForNetId) {
4177 nai = mNetworkForNetId.get(network.netId);
4178 }
4179 if (nai != null) {
4180 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4181 return true;
4182 }
4183 return false;
4184 }
4185
Felipe Lemeee27cab2016-06-20 16:36:29 -07004186 private boolean isSystem(int uid) {
4187 return uid < Process.FIRST_APPLICATION_UID;
4188 }
fenglub15e72b2015-03-20 11:29:56 -07004189
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004190 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004191 final int uid = Binder.getCallingUid();
4192 if (isSystem(uid)) {
4193 return;
4194 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004195 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004196 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004197 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004198 synchronized(mRulesLock) {
4199 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4200 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004201 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4202 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004203 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004204 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004205 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004206 }
4207 }
4208 }
4209
Robert Greenwalt9258c642014-03-26 16:47:06 -07004210 @Override
4211 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4212 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004213 checkNotNull(operation, "PendingIntent cannot be null.");
4214 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4215 enforceNetworkRequestPermissions(networkCapabilities);
4216 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004217 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004218
Etan Cohena7434272017-04-03 12:17:51 -07004219 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4220 networkCapabilities.getNetworkSpecifier());
4221
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004222 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004223 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4224 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004225 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004226 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4227 nri));
4228 return networkRequest;
4229 }
4230
Jeremy Joslin79294842014-12-03 17:15:28 -08004231 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4232 mHandler.sendMessageDelayed(
4233 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4234 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4235 }
4236
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004237 @Override
4238 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004239 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004240 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4241 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004242 }
4243
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004244 // In order to implement the compatibility measure for pre-M apps that call
4245 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4246 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4247 // This ensures it has permission to do so.
4248 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4249 if (nc == null) {
4250 return false;
4251 }
4252 int[] transportTypes = nc.getTransportTypes();
4253 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4254 return false;
4255 }
4256 try {
4257 mContext.enforceCallingOrSelfPermission(
4258 android.Manifest.permission.ACCESS_WIFI_STATE,
4259 "ConnectivityService");
4260 } catch (SecurityException e) {
4261 return false;
4262 }
4263 return true;
4264 }
4265
Robert Greenwalt9258c642014-03-26 16:47:06 -07004266 @Override
4267 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4268 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004269 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4270 enforceAccessPermission();
4271 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004272
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004273 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4274 if (!ConnectivityManager.checkChangePermission(mContext)) {
4275 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4276 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4277 // onLost and onAvailable callbacks when networks move in and out of the background.
4278 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4279 // can't request networks.
4280 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4281 }
4282
Etan Cohena7434272017-04-03 12:17:51 -07004283 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4284 networkCapabilities.getNetworkSpecifier());
4285
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004286 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004287 NetworkRequest.Type.LISTEN);
4288 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004289 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004290
4291 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4292 return networkRequest;
4293 }
4294
4295 @Override
4296 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4297 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004298 checkNotNull(operation, "PendingIntent cannot be null.");
4299 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4300 enforceAccessPermission();
4301 }
4302
Etan Cohena7434272017-04-03 12:17:51 -07004303 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4304 networkCapabilities.getNetworkSpecifier());
4305
Erik Kline7523eb32015-07-09 18:24:03 +09004306 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004307 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4308 NetworkRequest.Type.LISTEN);
4309 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004310 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004311
4312 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004313 }
4314
Erik Klineacdd6392016-07-07 16:50:58 +09004315 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004316 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004317 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004318 mHandler.sendMessage(mHandler.obtainMessage(
4319 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004320 }
4321
4322 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004323 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004324 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004325 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4326 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004327 }
4328
Robert Greenwalta67be032014-05-16 15:49:14 -07004329 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004330 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004331 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4332 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4333 }
4334
4335 @Override
4336 public void unregisterNetworkFactory(Messenger messenger) {
4337 enforceConnectivityInternalPermission();
4338 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4339 }
4340
4341 private void handleUnregisterNetworkFactory(Messenger messenger) {
4342 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4343 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004344 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004345 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004346 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004347 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004348 }
4349
Robert Greenwalt7b816022014-04-18 15:25:25 -07004350 /**
4351 * NetworkAgentInfo supporting a request by requestId.
4352 * These have already been vetted (their Capabilities satisfy the request)
4353 * and the are the highest scored network available.
4354 * the are keyed off the Requests requestId.
4355 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004356 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004357 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4358 new SparseArray<NetworkAgentInfo>();
4359
Paul Jensen31a94f42015-02-13 14:18:39 -05004360 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4361 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004362 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4363 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004364 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4365 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4366 // there may not be a strict 1:1 correlation between the two.
4367 @GuardedBy("mNetworkForNetId")
4368 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004369
Robert Greenwalt7b816022014-04-18 15:25:25 -07004370 // NetworkAgentInfo keyed off its connecting messenger
4371 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004372 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004373 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4374 new HashMap<Messenger, NetworkAgentInfo>();
4375
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004376 @GuardedBy("mBlockedAppUids")
4377 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4378
Paul Jensen2c311d62014-11-17 12:34:51 -05004379 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004380 private final NetworkRequest mDefaultRequest;
4381
Erik Klineda4bfa82015-04-30 12:58:40 +09004382 // Request used to optionally keep mobile data active even when higher
4383 // priority networks like Wi-Fi are active.
4384 private final NetworkRequest mDefaultMobileDataRequest;
4385
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004386 private NetworkAgentInfo getDefaultNetwork() {
4387 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4388 }
4389
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004390 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004391 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004392 }
4393
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004394 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4395 return nri.request.requestId == mDefaultRequest.requestId;
4396 }
4397
Paul Jensen31a94f42015-02-13 14:18:39 -05004398 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004399 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004400 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004401 enforceConnectivityInternalPermission();
4402
Paul Jensen2c311d62014-11-17 12:34:51 -05004403 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4404 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004405 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004406 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4407 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004408 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004409 synchronized (this) {
4410 nai.networkMonitor.systemReady = mSystemReady;
4411 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004412 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4413 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004414 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004415 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004416 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004417 }
4418
4419 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4420 if (VDBG) log("Got NetworkAgent Messenger");
4421 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004422 synchronized (mNetworkForNetId) {
4423 mNetworkForNetId.put(na.network.netId, na);
4424 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004425 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4426 NetworkInfo networkInfo = na.networkInfo;
4427 na.networkInfo = null;
4428 updateNetworkInfo(na, networkInfo);
4429 }
4430
4431 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4432 LinkProperties newLp = networkAgent.linkProperties;
4433 int netId = networkAgent.network.netId;
4434
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004435 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4436 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004437 if (networkAgent.clatd != null) {
4438 networkAgent.clatd.fixupLinkProperties(oldLp);
4439 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004440
Paul Jensen992f2522014-04-28 10:33:11 -04004441 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004442 updateMtu(newLp, oldLp);
4443 // TODO - figure out what to do for clat
4444// for (LinkProperties lp : newLp.getStackedLinks()) {
4445// updateMtu(lp, null);
4446// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004447 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004448
Erik Kline94887872016-04-05 13:30:49 +09004449 updateRoutes(newLp, oldLp, netId);
4450 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004451
Paul Jensen3b759822014-05-13 11:44:01 -04004452 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004453 if (isDefaultNetwork(networkAgent)) {
4454 handleApplyDefaultProxy(newLp.getHttpProxy());
4455 } else {
4456 updateProxy(newLp, oldLp, networkAgent);
4457 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004458 // TODO - move this check to cover the whole function
4459 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004460 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004461 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4462 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004463
4464 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004465 }
4466
Lorenzo Colitti95439462014-10-09 13:44:48 +09004467 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4468 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4469 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004470
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004471 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004472 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4473 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004474 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004475 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004476 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004477 }
Paul Jensen992f2522014-04-28 10:33:11 -04004478
4479 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4480 CompareResult<String> interfaceDiff = new CompareResult<String>();
4481 if (oldLp != null) {
4482 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4483 } else if (newLp != null) {
4484 interfaceDiff.added = newLp.getAllInterfaceNames();
4485 }
4486 for (String iface : interfaceDiff.added) {
4487 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004488 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004489 mNetd.addInterfaceToNetwork(iface, netId);
4490 } catch (Exception e) {
4491 loge("Exception adding interface: " + e);
4492 }
4493 }
4494 for (String iface : interfaceDiff.removed) {
4495 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004496 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004497 mNetd.removeInterfaceFromNetwork(iface, netId);
4498 } catch (Exception e) {
4499 loge("Exception removing interface: " + e);
4500 }
4501 }
4502 }
4503
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004504 /**
4505 * Have netd update routes from oldLp to newLp.
4506 * @return true if routes changed between oldLp and newLp
4507 */
4508 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004509 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4510 if (oldLp != null) {
4511 routeDiff = oldLp.compareAllRoutes(newLp);
4512 } else if (newLp != null) {
4513 routeDiff.added = newLp.getAllRoutes();
4514 }
4515
4516 // add routes before removing old in case it helps with continuous connectivity
4517
4518 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4519 for (RouteInfo route : routeDiff.added) {
4520 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004521 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004522 try {
4523 mNetd.addRoute(netId, route);
4524 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004525 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4526 loge("Exception in addRoute for non-gateway: " + e);
4527 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004528 }
4529 }
4530 for (RouteInfo route : routeDiff.added) {
4531 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004532 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004533 try {
4534 mNetd.addRoute(netId, route);
4535 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004536 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4537 loge("Exception in addRoute for gateway: " + e);
4538 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004539 }
4540 }
4541
4542 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004543 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004544 try {
4545 mNetd.removeRoute(netId, route);
4546 } catch (Exception e) {
4547 loge("Exception in removeRoute: " + e);
4548 }
4549 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004550 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004551 }
Erik Kline41368502015-06-17 13:19:54 +09004552
Erik Kline94887872016-04-05 13:30:49 +09004553 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4554 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4555 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004556 }
Erik Kline94887872016-04-05 13:30:49 +09004557
4558 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004559 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004560 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004561 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004562 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4563 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004564 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004565 }
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004566 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4567 if (defaultNai != null && defaultNai.network.netId == netId) {
4568 setDefaultDnsSystemProperties(dnses);
4569 }
Erik Kline94887872016-04-05 13:30:49 +09004570 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004571 }
4572
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004573 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4574 int last = 0;
4575 for (InetAddress dns : dnses) {
4576 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004577 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004578 }
4579 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004580 setNetDnsProperty(i, "");
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004581 }
4582 mNumDnsEntries = last;
4583 }
4584
Erik Kline4edba012017-04-07 15:29:29 +09004585 private void setNetDnsProperty(int which, String value) {
4586 final String key = "net.dns" + which;
4587 // Log and forget errors setting unsupported properties.
4588 try {
4589 mSystemProperties.set(key, value);
4590 } catch (Exception e) {
4591 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4592 }
4593 }
4594
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004595 private String getNetworkPermission(NetworkCapabilities nc) {
4596 // TODO: make these permission strings AIDL constants instead.
4597 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4598 return NetworkManagementService.PERMISSION_SYSTEM;
4599 }
4600 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4601 return NetworkManagementService.PERMISSION_NETWORK;
4602 }
4603 return null;
4604 }
4605
Paul Jensen3d194ea2015-06-16 14:27:36 -04004606 /**
4607 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4608 * augmented with any stateful capabilities implied from {@code networkAgent}
4609 * (e.g., validated status and captive portal status).
4610 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004611 * @param oldScore score of the network before any of the changes that prompted us
4612 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004613 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004614 * @param networkCapabilities the new network capabilities.
4615 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004616 private void updateCapabilities(
4617 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004618 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4619 networkCapabilities)) {
4620 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4621 + nai.networkCapabilities + " -> " + networkCapabilities);
4622 }
4623
Paul Jensen3d194ea2015-06-16 14:27:36 -04004624 // Don't modify caller's NetworkCapabilities.
4625 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004626 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004627 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4628 } else {
4629 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4630 }
Paul Jensene0988542015-06-25 15:30:08 -04004631 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004632 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4633 } else {
4634 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4635 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004636 if (nai.isBackgroundNetwork()) {
4637 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4638 } else {
4639 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4640 }
4641
4642 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4643
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004644 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4645 final String newPermission = getNetworkPermission(networkCapabilities);
4646 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004647 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004648 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004649 } catch (RemoteException e) {
4650 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004651 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004652 }
4653
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004654 final NetworkCapabilities prevNc = nai.networkCapabilities;
4655 synchronized (nai) {
4656 nai.networkCapabilities = networkCapabilities;
4657 }
4658 if (nai.getCurrentScore() == oldScore &&
4659 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4660 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4661 // the change we're processing can't affect any requests, it can only affect the listens
4662 // on this network. We might have been called by rematchNetworkAndRequests when a
4663 // network changed foreground state.
4664 processListenRequests(nai, true);
4665 } else {
4666 // If the requestable capabilities have changed or the score changed, we can't have been
4667 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004668 rematchAllNetworksAndRequests(nai, oldScore);
4669 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004670 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004671 }
4672
Paul Jensenc8b9a742014-09-30 15:37:41 -04004673 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004674 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4675 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004676 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004677 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004678 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4679 }
4680 }
4681
Robert Greenwalt7b816022014-04-18 15:25:25 -07004682 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4683 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004684 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004685 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4686 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004687 }
4688 }
4689
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004690 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4691 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004692 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004693 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004694 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4695 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004696 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004697 sendIntent(nri.mPendingIntent, intent);
4698 }
4699 // else not handled
4700 }
4701
4702 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4703 mPendingIntentWakeLock.acquire();
4704 try {
4705 if (DBG) log("Sending " + pendingIntent);
4706 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4707 } catch (PendingIntent.CanceledException e) {
4708 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4709 mPendingIntentWakeLock.release();
4710 releasePendingNetworkRequest(pendingIntent);
4711 }
4712 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4713 }
4714
4715 @Override
4716 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4717 String resultData, Bundle resultExtras) {
4718 if (DBG) log("Finished sending " + pendingIntent);
4719 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004720 // Release with a delay so the receiving client has an opportunity to put in its
4721 // own request.
4722 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004723 }
4724
Robert Greenwalt9258c642014-03-26 16:47:06 -07004725 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004726 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004727 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004728 Bundle bundle = new Bundle();
4729 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4730 new NetworkRequest(nri.request));
4731 Message msg = Message.obtain();
4732 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4733 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4734 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4735 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004736 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004737 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004738 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004739 break;
4740 }
4741 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4742 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4743 new NetworkCapabilities(networkAgent.networkCapabilities));
4744 break;
4745 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004746 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004747 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4748 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004749 break;
4750 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004751 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004752 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004753 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004754 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004755 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004756 String notification = ConnectivityManager.getCallbackName(notificationType);
4757 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004758 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004759 nri.messenger.send(msg);
4760 } catch (RemoteException e) {
4761 // may occur naturally in the race of binder death.
4762 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4763 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004764 }
4765
Paul Jensenc8b9a742014-09-30 15:37:41 -04004766 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004767 if (nai.numRequestNetworkRequests() != 0) {
4768 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4769 NetworkRequest nr = nai.requestAt(i);
4770 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004771 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004772 loge("Dead network still had at least " + nr);
4773 break;
4774 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004775 }
4776 nai.asyncChannel.disconnect();
4777 }
4778
Robert Greenwalt7b816022014-04-18 15:25:25 -07004779 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4780 if (oldNetwork == null) {
4781 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4782 return;
4783 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004784 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004785
4786 // If we get here it means that the last linger timeout for this network expired. So there
4787 // must be no other active linger timers, and we must stop lingering.
4788 oldNetwork.clearLingerState();
4789
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004790 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004791 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004792 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004793 } else {
4794 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004795 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4796 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004797 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004798 }
4799
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004800 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004801 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004802 setupDataActivityTracking(newNetwork);
4803 try {
4804 mNetd.setDefaultNetId(newNetwork.network.netId);
4805 } catch (Exception e) {
4806 loge("Exception setting default network :" + e);
4807 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004808 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004809 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004810 updateTcpBufferSizes(newNetwork);
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004811 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004812 }
4813
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004814 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004815 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4816 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4817 NetworkRequest nr = nri.request;
4818 if (!nr.isListen()) continue;
4819 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4820 nai.removeRequest(nri.request.requestId);
4821 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4822 }
4823 }
4824
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004825 if (capabilitiesChanged) {
4826 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4827 }
4828
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004829 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4830 NetworkRequest nr = nri.request;
4831 if (!nr.isListen()) continue;
4832 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4833 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004834 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004835 }
4836 }
4837 }
4838
Paul Jensen2161a8e2014-09-11 11:00:39 -04004839 // Handles a network appearing or improving its score.
4840 //
4841 // - Evaluates all current NetworkRequests that can be
4842 // satisfied by newNetwork, and reassigns to newNetwork
4843 // any such requests for which newNetwork is the best.
4844 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004845 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004846 // needed. A network is needed if it is the best network for
4847 // one or more NetworkRequests, or if it is a VPN.
4848 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004849 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004850 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004851 //
4852 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4853 // networks that have no chance (i.e. even if validated)
4854 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004855 //
4856 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4857 // it does not remove NetworkRequests that other Networks could better satisfy.
4858 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4859 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4860 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004861 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004862 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004863 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4864 // performed to tear down unvalidated networks that have no chance (i.e. even if
4865 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004866 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004867 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004868 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004869 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004870 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004871 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004872
4873 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4874 final int score = newNetwork.getCurrentScore();
4875
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004876 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004877
Paul Jensen2161a8e2014-09-11 11:00:39 -04004878 // Find and migrate to this Network any NetworkRequests for
4879 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004880 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004881 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004882 NetworkCapabilities nc = newNetwork.networkCapabilities;
4883 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004884 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004885 // Process requests in the first pass and listens in the second pass. This allows us to
4886 // change a network's capabilities depending on which requests it has. This is only
4887 // correct if the change in capabilities doesn't affect whether the network satisfies
4888 // requests or not, and doesn't affect the network's score.
4889 if (nri.request.isListen()) continue;
4890
Paul Jensencf4c2c62015-07-01 14:16:32 -04004891 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4892 final boolean satisfies = newNetwork.satisfies(nri.request);
4893 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004894 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004895 log("Network " + newNetwork.name() + " was already satisfying" +
4896 " request " + nri.request.requestId + ". No change.");
4897 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004898 keep = true;
4899 continue;
4900 }
4901
4902 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004903 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004904 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004905 // next check if it's better than any current network we're using for
4906 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004907 if (VDBG) {
4908 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004909 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004910 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004911 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004912 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004913 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004914 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004915 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004916 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004917 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004918 affectedNetworks.add(currentNetwork);
4919 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004920 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004921 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004922 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004923 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004924 if (!newNetwork.addRequest(nri.request)) {
4925 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4926 }
4927 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004928 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004929 // Tell NetworkFactories about the new score, so they can stop
4930 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004931 // TODO - this could get expensive if we have alot of requests for this
4932 // network. Think about if there is a way to reduce this. Push
4933 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004934 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004935 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004936 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004937 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004938 if (currentNetwork != null) {
4939 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4940 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004941 }
4942 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004943 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004944 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4945 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004946 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004947 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4948 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4949 // This means this code doesn't have to handle the case where "currentNetwork" no
4950 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4951 if (DBG) {
4952 log("Network " + newNetwork.name() + " stopped satisfying" +
4953 " request " + nri.request.requestId);
4954 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004955 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004956 if (currentNetwork == newNetwork) {
4957 mNetworkForRequestId.remove(nri.request.requestId);
4958 sendUpdatedScoreToFactories(nri.request, 0);
4959 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004960 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4961 newNetwork.name() +
4962 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004963 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004964 // TODO: Technically, sending CALLBACK_LOST here is
4965 // incorrect if there is a replacement network currently
4966 // connected that can satisfy nri, which is a request
4967 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004968 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4969 // so this code is only incorrect for a network that loses
4970 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004971 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004972 }
4973 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004974 if (isNewDefault) {
4975 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004976 makeDefault(newNetwork);
4977 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4978 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09004979 // Have a new default network, release the transition wakelock in
4980 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04004981 }
4982
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004983 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4984 Slog.wtf(TAG, String.format(
4985 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4986 nc, newNetwork.networkCapabilities));
4987 }
4988 if (newNetwork.getCurrentScore() != score) {
4989 Slog.wtf(TAG, String.format(
4990 "BUG: %s changed score during rematch: %d -> %d",
4991 score, newNetwork.getCurrentScore()));
4992 }
4993
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004994 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004995 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4996 // If the network went from background to foreground or vice versa, we need to update
4997 // its foreground state. It is safe to do this after rematching the requests because
4998 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4999 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005000 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005001 } else {
5002 processListenRequests(newNetwork, false);
5003 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005004
Paul Jensencf4c2c62015-07-01 14:16:32 -04005005 // do this after the default net is switched, but
5006 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005007 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005008
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005009 // Linger any networks that are no longer needed. This should be done after sending the
5010 // available callback for newNetwork.
5011 for (NetworkAgentInfo nai : affectedNetworks) {
5012 updateLingerState(nai, now);
5013 }
5014 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5015 // does not need to be done in any particular order.
5016 updateLingerState(newNetwork, now);
5017
Paul Jensencf4c2c62015-07-01 14:16:32 -04005018 if (isNewDefault) {
5019 // Maintain the illusion: since the legacy API only
5020 // understands one network at a time, we must pretend
5021 // that the current default network disconnected before
5022 // the new one connected.
5023 if (oldDefaultNetwork != null) {
5024 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5025 oldDefaultNetwork, true);
5026 }
5027 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5028 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5029 notifyLockdownVpn(newNetwork);
5030 }
5031
Robert Greenwalt7b816022014-04-18 15:25:25 -07005032 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005033 // Notify battery stats service about this network, both the normal
5034 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005035 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005036 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005037 final IBatteryStats bs = BatteryStatsService.getService();
5038 final int type = newNetwork.networkInfo.getType();
5039
5040 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5041 bs.noteNetworkInterfaceType(baseIface, type);
5042 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5043 final String stackedIface = stacked.getInterfaceName();
5044 bs.noteNetworkInterfaceType(stackedIface, type);
5045 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5046 }
5047 } catch (RemoteException ignored) {
5048 }
5049
Robert Greenwalt152ed372014-12-17 17:19:53 -08005050 // This has to happen after the notifyNetworkCallbacks as that tickles each
5051 // ConnectivityManager instance so that legacy requests correctly bind dns
5052 // requests to this network. The legacy users are listening for this bcast
5053 // and will generally do a dns request so they can ensureRouteToHost and if
5054 // they do that before the callbacks happen they'll use the default network.
5055 //
5056 // TODO: Is there still a race here? We send the broadcast
5057 // after sending the callback, but if the app can receive the
5058 // broadcast before the callback, it might still break.
5059 //
5060 // This *does* introduce a race where if the user uses the new api
5061 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5062 // they may get old info. Reverse this after the old startUsing api is removed.
5063 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005064 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5065 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005066 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005067 // legacy type tracker filters out repeat adds
5068 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5069 }
5070 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005071
5072 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5073 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5074 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5075 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5076 if (newNetwork.isVPN()) {
5077 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5078 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005079 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005080 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5081 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005082 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005083 if (nai.getLingerExpiry() > 0) {
5084 // This network has active linger timers and no requests, but is not
5085 // lingering. Linger it.
5086 //
5087 // One way (the only way?) this can happen if this network is unvalidated
5088 // and became unneeded due to another network improving its score to the
5089 // point where this network will no longer be able to satisfy any requests
5090 // even if it validates.
5091 updateLingerState(nai, now);
5092 } else {
5093 if (DBG) log("Reaping " + nai.name());
5094 teardownUnneededNetwork(nai);
5095 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005096 }
5097 }
5098 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005099 }
5100
Paul Jensen1c7ba022015-06-16 14:27:36 -04005101 /**
5102 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5103 * being disconnected.
5104 * @param changed If only one Network's score or capabilities have been modified since the last
5105 * time this function was called, pass this Network in this argument, otherwise pass
5106 * null.
5107 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5108 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5109 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5110 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5111 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005112 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005113 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005114 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5115 // to avoid the slowness. It is not simply enough to process just "changed", for
5116 // example in the case where "changed"'s score decreases and another network should begin
5117 // satifying a NetworkRequest that "changed" currently satisfies.
5118
5119 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5120 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5121 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005122 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005123 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005124 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005125 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005126 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5127 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5128 // Rematch higher scoring networks first to prevent requests first matching a lower
5129 // scoring network and then a higher scoring network, which could produce multiple
5130 // callbacks and inadvertently unlinger networks.
5131 Arrays.sort(nais);
5132 for (NetworkAgentInfo nai : nais) {
5133 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005134 // Only reap the last time through the loop. Reaping before all rematching
5135 // is complete could incorrectly teardown a network that hasn't yet been
5136 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005137 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005138 : ReapUnvalidatedNetworks.REAP,
5139 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005140 }
5141 }
5142 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005143
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005144 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005145 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005146 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005147 // For now only update icons for default connection.
5148 // TODO: Update WiFi and cellular icons separately. b/17237507
5149 if (!isDefaultNetwork(nai)) return;
5150
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005151 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005152 // Don't repeat publish.
5153 if (newInetCondition == mDefaultInetConditionPublished) return;
5154
5155 mDefaultInetConditionPublished = newInetCondition;
5156 sendInetConditionBroadcast(nai.networkInfo);
5157 }
5158
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005159 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5160 if (mLockdownTracker != null) {
5161 if (nai != null && nai.isVPN()) {
5162 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5163 } else {
5164 mLockdownTracker.onNetworkInfoChanged();
5165 }
5166 }
5167 }
5168
Robert Greenwalt7b816022014-04-18 15:25:25 -07005169 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005170 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005171 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005172 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005173 synchronized (networkAgent) {
5174 oldInfo = networkAgent.networkInfo;
5175 networkAgent.networkInfo = newInfo;
5176 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005177 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005178
5179 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005180 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5181 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5182 notifyIfacesChangedForNetworkStats();
5183 } else if (VDBG) log("ignoring duplicate network state non-change");
5184 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005185 return;
5186 }
5187 if (DBG) {
5188 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5189 (oldInfo == null ? "null" : oldInfo.getState()) +
5190 " to " + state);
5191 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005192
Robin Lee585e2482016-05-01 23:00:00 +01005193 if (!networkAgent.created
5194 && (state == NetworkInfo.State.CONNECTED
5195 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005196
5197 // A network that has just connected has zero requests and is thus a foreground network.
5198 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5199
Robert Greenwalt7b816022014-04-18 15:25:25 -07005200 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005201 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005202 if (networkAgent.isVPN()) {
5203 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005204 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5205 (networkAgent.networkMisc == null ||
5206 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005207 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005208 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005209 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005210 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005211 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005212 loge("Error creating network " + networkAgent.network.netId + ": "
5213 + e.getMessage());
5214 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005215 }
Paul Jenseneec75412014-08-04 12:21:19 -04005216 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005217 }
5218
5219 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5220 networkAgent.everConnected = true;
5221
Robert Greenwalt7b816022014-04-18 15:25:25 -07005222 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005223 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005224
Paul Jensenca8f16a2014-05-09 12:47:55 -04005225 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005226 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005227
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005228 if (networkAgent.isVPN()) {
5229 // Temporarily disable the default proxy (not global).
5230 synchronized (mProxyLock) {
5231 if (!mDefaultProxyDisabled) {
5232 mDefaultProxyDisabled = true;
5233 if (mGlobalProxy == null && mDefaultProxy != null) {
5234 sendProxyBroadcast(null);
5235 }
5236 }
5237 }
5238 // TODO: support proxy per network.
5239 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005240
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005241 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5242 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5243 // capabilities, so it only needs to be done once on initial connect, not every time the
5244 // network's capabilities change. Note that we do this before rematching the network,
5245 // so we could decide to tear it down immediately afterwards. That's fine though - on
5246 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5247 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005248 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005249
Paul Jensen2161a8e2014-09-11 11:00:39 -04005250 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005251 final long now = SystemClock.elapsedRealtime();
5252 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005253
5254 // This has to happen after matching the requests, because callbacks are just requests.
5255 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005256 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005257 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005258 if (networkAgent.isVPN()) {
5259 synchronized (mProxyLock) {
5260 if (mDefaultProxyDisabled) {
5261 mDefaultProxyDisabled = false;
5262 if (mGlobalProxy == null && mDefaultProxy != null) {
5263 sendProxyBroadcast(mDefaultProxy);
5264 }
5265 }
5266 }
5267 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005268 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5269 state == NetworkInfo.State.SUSPENDED) {
5270 // going into or coming out of SUSPEND: rescore and notify
5271 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005272 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005273 }
5274 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5275 ConnectivityManager.CALLBACK_SUSPENDED :
5276 ConnectivityManager.CALLBACK_RESUMED));
5277 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005278 }
5279 }
5280
Robert Greenwaltac96c522014-06-03 16:43:57 -07005281 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005282 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005283 if (score < 0) {
5284 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5285 "). Bumping score to min of 0");
5286 score = 0;
5287 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005288
Paul Jensen2161a8e2014-09-11 11:00:39 -04005289 final int oldScore = nai.getCurrentScore();
5290 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005291
Paul Jensen85cf78e2015-06-25 13:25:07 -04005292 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005293
Paul Jensenc8b9a742014-09-30 15:37:41 -04005294 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005295 }
5296
Erik Klinec75d4fa2017-02-15 19:59:17 +09005297 // Notify only this one new request of the current state. Transfer all the
5298 // current state by calling NetworkCapabilities and LinkProperties callbacks
5299 // so that callers can be guaranteed to have as close to atomicity in state
5300 // transfer as can be supported by this current API.
5301 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohenbf3b1ba2016-10-27 15:05:50 -07005302 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005303 if (nri.mPendingIntent != null) {
5304 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5305 // Attempt no subsequent state pushes where intents are involved.
5306 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005307 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005308
5309 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5310 // Whether a network is currently suspended is also an important
5311 // element of state to be transferred (it would not otherwise be
5312 // delivered by any currently available mechanism).
5313 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5314 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5315 }
5316 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5317 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005318 }
5319
Robert Greenwalt8d482522015-06-24 13:23:42 -07005320 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005321 // The NetworkInfo we actually send out has no bearing on the real
5322 // state of affairs. For example, if the default connection is mobile,
5323 // and a request for HIPRI has just gone away, we need to pretend that
5324 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5325 // the state to DISCONNECTED, even though the network is of type MOBILE
5326 // and is still connected.
5327 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5328 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005329 if (state != DetailedState.DISCONNECTED) {
5330 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005331 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005332 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005333 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005334 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5335 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5336 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5337 if (info.isFailover()) {
5338 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5339 nai.networkInfo.setFailover(false);
5340 }
5341 if (info.getReason() != null) {
5342 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5343 }
5344 if (info.getExtraInfo() != null) {
5345 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5346 }
5347 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005348 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005349 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005350 if (newDefaultAgent != null) {
5351 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5352 newDefaultAgent.networkInfo);
5353 } else {
5354 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5355 }
5356 }
5357 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5358 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005359 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005360 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005361 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005362 }
5363 }
5364 }
5365
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005366 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005367 if (VDBG) {
5368 String notification = ConnectivityManager.getCallbackName(notifyType);
5369 log("notifyType " + notification + " for " + networkAgent.name());
5370 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005371 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5372 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005373 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5374 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005375 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5376 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005377 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005378 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005379 } else {
5380 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5381 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005382 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005383 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005384
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005385 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5386 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5387 }
5388
Jeff Sharkey69736342014-12-08 14:50:12 -08005389 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005390 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5391 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005392 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005393 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005394 try {
5395 mStatsService.forceUpdateIfaces();
5396 } catch (Exception ignored) {
5397 }
5398 }
5399
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005400 @Override
5401 public boolean addVpnAddress(String address, int prefixLength) {
5402 throwIfLockdownEnabled();
5403 int user = UserHandle.getUserId(Binder.getCallingUid());
5404 synchronized (mVpns) {
5405 return mVpns.get(user).addAddress(address, prefixLength);
5406 }
5407 }
5408
5409 @Override
5410 public boolean removeVpnAddress(String address, int prefixLength) {
5411 throwIfLockdownEnabled();
5412 int user = UserHandle.getUserId(Binder.getCallingUid());
5413 synchronized (mVpns) {
5414 return mVpns.get(user).removeAddress(address, prefixLength);
5415 }
5416 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005417
5418 @Override
5419 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5420 throwIfLockdownEnabled();
5421 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005422 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005423 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005424 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005425 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005426 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005427 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005428 }
5429 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005430 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005431
5432 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005433 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005434 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005435 }
5436
5437 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005438 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5439 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5440 enforceKeepalivePermission();
5441 mKeepaliveTracker.startNattKeepalive(
5442 getNetworkAgentInfoForNetwork(network),
5443 intervalSeconds, messenger, binder,
5444 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5445 }
5446
5447 @Override
5448 public void stopKeepalive(Network network, int slot) {
5449 mHandler.sendMessage(mHandler.obtainMessage(
5450 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5451 }
5452
5453 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005454 public void factoryReset() {
5455 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005456
5457 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5458 return;
5459 }
5460
Robin Lee3b3dd942015-05-12 18:14:58 +01005461 final int userId = UserHandle.getCallingUserId();
5462
Stuart Scottf1fb3972015-04-02 18:00:02 -07005463 // Turn airplane mode off
5464 setAirplaneMode(false);
5465
Stuart Scotte3e314d2015-04-20 14:07:45 -07005466 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5467 // Untether
5468 for (String tether : getTetheredIfaces()) {
5469 untether(tether);
5470 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005471 }
5472
Stuart Scotte3e314d2015-04-20 14:07:45 -07005473 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005474 // Remove always-on package
5475 synchronized (mVpns) {
5476 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5477 if (alwaysOnPackage != null) {
5478 setAlwaysOnVpnPackage(userId, null, false);
5479 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5480 }
5481 }
5482
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005483 // Turn Always-on VPN off
5484 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5485 final long ident = Binder.clearCallingIdentity();
5486 try {
5487 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5488 mLockdownEnabled = false;
5489 setLockdownTracker(null);
5490 } finally {
5491 Binder.restoreCallingIdentity(ident);
5492 }
5493 }
5494
Stuart Scotte3e314d2015-04-20 14:07:45 -07005495 // Turn VPN off
5496 VpnConfig vpnConfig = getVpnConfig(userId);
5497 if (vpnConfig != null) {
5498 if (vpnConfig.legacy) {
5499 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5500 } else {
5501 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5502 // in the future without user intervention.
5503 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005504
Victor Changb04a5ea2016-05-30 20:36:30 +01005505 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005506 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005507 }
5508 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005509
5510 Settings.Global.putString(mContext.getContentResolver(),
5511 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005512 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005513
5514 @VisibleForTesting
5515 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5516 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5517 return new NetworkMonitor(context, handler, nai, defaultRequest);
5518 }
Erik Kline48f12f22016-04-14 17:30:59 +09005519
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005520 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005521 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5522 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005523 }
5524
5525 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005526 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5527 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5528 }
5529
Hugo Benichicfddd682016-05-31 16:28:06 +09005530 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005531 int newNetid = NETID_UNSET;
5532 int prevNetid = NETID_UNSET;
5533 int[] transports = new int[0];
5534 boolean hadIPv4 = false;
5535 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005536
Hugo Benichi5f16f762016-04-20 12:09:33 +09005537 if (newNai != null) {
5538 newNetid = newNai.network.netId;
5539 transports = newNai.networkCapabilities.getTransportTypes();
5540 }
5541 if (prevNai != null) {
5542 prevNetid = prevNai.network.netId;
5543 final LinkProperties lp = prevNai.linkProperties;
5544 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5545 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5546 }
5547
Hugo Benichicfddd682016-05-31 16:28:06 +09005548 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5549 }
5550
5551 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5552 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554}