blob: 408b7ed0558e283683b1c4be647478839a11311a [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;
Hugo Benichidba33db2017-03-23 22:40:44 +090096import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070097import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070098import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070099import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800100import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900101import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700102import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400103import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700105import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700106import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700107import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700108import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600109import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700110import android.util.LocalLog;
111import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600112import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700113import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800114import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700115import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500116import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700117import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700118import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Wink Savilleab9321d2013-06-29 21:10:57 -0700120import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400121import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400122import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700123import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700124import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700125import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700126import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800127import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700128import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700129import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700130import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900131import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900132import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700133import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700134import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400135import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900136import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700137import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900138import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900139import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700140import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600141import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400142import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900143import com.android.server.connectivity.NetworkNotificationManager;
144import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400145import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700146import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800147import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700148import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700149import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700150import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600151
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700152import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700153
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700154import org.xmlpull.v1.XmlPullParser;
155import org.xmlpull.v1.XmlPullParserException;
156
157import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700159import java.io.FileNotFoundException;
160import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700161import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700163import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700164import java.net.InetAddress;
165import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700166import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700167import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700168import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700169import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700170import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700171import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700172import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700173import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700174import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600175import java.util.SortedSet;
176import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
178/**
179 * @hide
180 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800181public class ConnectivityService extends IConnectivityManager.Stub
182 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900183 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900185 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700186 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Jake Hamby786e71a2014-02-06 14:43:50 -0800188 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900189 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700190
Jeff Sharkey899223b2012-08-04 15:24:58 -0700191 // TODO: create better separation between radio types and network types
192
Robert Greenwalt42acef32009-08-12 16:08:25 -0700193 // how long to wait before switching back to a radio's default network
194 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
195 // system property that can override the above value
196 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
197 "android.telephony.apn-restore";
198
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900199 // How long to wait before putting up a "This network doesn't have an Internet connection,
200 // connect anyway?" dialog after the user selects a network that doesn't validate.
201 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
202
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900203 // Default to 30s linger time-out. Modifiable only for testing.
204 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
205 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
206 @VisibleForTesting
207 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
208
Jeremy Joslin79294842014-12-03 17:15:28 -0800209 // How long to delay to removal of a pending intent based request.
210 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
211 private final int mReleasePendingIntentDelayMs;
212
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900213 private MockableSystemProperties mSystemProperties;
214
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800215 private Tethering mTethering;
216
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700217 private final PermissionMonitor mPermissionMonitor;
218
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700219 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700220
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700221 @GuardedBy("mVpns")
222 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700223
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700224 private boolean mLockdownEnabled;
225 private LockdownVpnTracker mLockdownTracker;
226
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700227 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
228 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700229 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600230 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700231 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700232 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600233 @GuardedBy("mRulesLock")
234 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
235 /** Flag indicating if background data is restricted. */
236 @GuardedBy("mRulesLock")
237 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700238
Erik Klineda4bfa82015-04-30 12:58:40 +0900239 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700241 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700242 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800244 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245
246 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700247 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700249 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800250 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700251 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700252
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700253 private String mCurrentTcpBufferSizes;
254
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700255 private static final int ENABLED = 1;
256 private static final int DISABLED = 0;
257
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900258 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900259 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
260 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900261
Paul Jensenb10e37f2014-11-25 12:33:08 -0500262 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400263 // Tear down networks that have no chance (e.g. even if validated) of becoming
264 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500265 // all networks have been rematched against all NetworkRequests.
266 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400267 // Don't reap networks. This should be passed when some networks have not yet been
268 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500269 DONT_REAP
270 };
271
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900272 private enum UnneededFor {
273 LINGER, // Determine whether this network is unneeded and should be lingered.
274 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
275 }
276
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700277 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700278 * used internally to change our mobile data enabled flag
279 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700280 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700281
282 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700283 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700284 * from one net to another. Clear happens when we get a new
285 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
286 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700287 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700288 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700289
Robert Greenwalt434203a2010-10-11 16:00:27 -0700290 /**
291 * used internally to reload global proxy settings
292 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700293 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700294
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700295 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400296 * PAC manager has received new port.
297 */
298 private static final int EVENT_PROXY_HAS_CHANGED = 16;
299
Robert Greenwalte049c232014-04-11 15:53:27 -0700300 /**
301 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700302 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700303 */
304 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
305
Robert Greenwalt7b816022014-04-18 15:25:25 -0700306 /**
307 * used internally when registering NetworkAgents
308 * obj = Messenger
309 */
310 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
311
Robert Greenwalt9258c642014-03-26 16:47:06 -0700312 /**
313 * used to add a network request
314 * includes a NetworkRequestInfo
315 */
316 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
317
318 /**
319 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900320 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700321 * cancel it.
322 * includes a NetworkRequestInfo
323 */
324 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
325
326 /**
327 * used to add a network listener - no request
328 * includes a NetworkRequestInfo
329 */
330 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
331
332 /**
333 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400334 * arg1 = UID of caller
335 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700336 */
337 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
338
Robert Greenwalta67be032014-05-16 15:49:14 -0700339 /**
340 * used internally when registering NetworkFactories
341 * obj = Messenger
342 */
343 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
344
Robert Greenwalt27711812014-06-25 16:45:57 -0700345 /**
346 * used internally to expire a wakelock when transitioning
347 * from one net to another. Expire happens when we fail to find
348 * a new network (typically after 1 minute) -
349 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
350 * a replacement network.
351 */
352 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
353
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700354 /**
355 * Used internally to indicate the system is ready.
356 */
357 private static final int EVENT_SYSTEM_READY = 25;
358
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800359 /**
360 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400361 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800362 */
363 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
364
365 /**
366 * used to remove a pending intent and its associated network request.
367 * arg1 = UID of caller
368 * obj = PendingIntent
369 */
370 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
371
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900372 /**
373 * used to specify whether a network should be used even if unvalidated.
374 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
375 * arg2 = whether to remember this choice in the future (1 or 0)
376 * obj = network
377 */
378 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
379
380 /**
381 * used to ask the user to confirm a connection to an unvalidated network.
382 * obj = network
383 */
384 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700385
Erik Klineda4bfa82015-04-30 12:58:40 +0900386 /**
387 * used internally to (re)configure mobile data always-on settings.
388 */
389 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
390
Paul Jensen694f2b82015-06-17 14:15:39 -0400391 /**
392 * used to add a network listener with a pending intent
393 * obj = NetworkRequestInfo
394 */
395 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
396
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900397 /**
398 * used to specify whether a network should not be penalized when it becomes unvalidated.
399 */
400 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
401
402 /**
403 * used to trigger revalidation of a network.
404 */
405 private static final int EVENT_REVALIDATE_NETWORK = 36;
406
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900407 private static String eventName(int what) {
408 return sMagicDecoderRing.get(what, Integer.toString(what));
409 }
410
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900411 /** Handler thread used for both of the handlers below. */
412 @VisibleForTesting
413 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700414 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700415 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700416 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700417 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700418
Mike Lockwood0f79b542009-08-14 14:18:49 -0400419 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800420 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400421
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700422 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700423 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800424 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700425
Robert Greenwalt434203a2010-10-11 16:00:27 -0700426 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400427 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700428 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700429 private boolean mDefaultProxyDisabled = false;
430
Robert Greenwalt434203a2010-10-11 16:00:27 -0700431 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400432 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700433
Jason Monk602b2322013-07-03 17:04:33 -0400434 private PacManager mPacManager = null;
435
Erik Klineda4bfa82015-04-30 12:58:40 +0900436 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700437
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400438 private UserManager mUserManager;
439
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700440 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700441 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700442
Robert Greenwalt50393202011-06-21 17:26:14 -0700443 // the set of network types that can only be enabled by system/sig apps
444 List mProtectedNetworks;
445
John Spurlockbf991a82013-06-24 14:20:23 -0400446 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700447
Wink Savilleab9321d2013-06-29 21:10:57 -0700448 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400449
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900450 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900451 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900452 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900453
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700454 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
455 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700456 private final static int MAX_NET_ID = 65535;
457 private int mNextNetId = MIN_NET_ID;
458
Robert Greenwalt34524f02014-05-18 16:22:10 -0700459 // sequence number of NetworkRequests
460 private int mNextNetworkRequestId = 1;
461
Erik Kline7523eb32015-07-09 18:24:03 +0900462 // NetworkRequest activity String log entries.
463 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
464 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
465
Hugo Benichic2ae2872016-07-11 11:05:12 +0900466 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900467 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900468 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
469
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900470 private static final int MAX_WAKELOCK_LOGS = 20;
471 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
472
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700473 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
474 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400475 private static class ValidationLog {
476 final Network mNetwork;
477 final String mNetworkExtraInfo;
478 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700479
Paul Jensen0808eb82016-06-03 13:51:21 -0400480 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
481 mNetwork = network;
482 mNetworkExtraInfo = networkExtraInfo;
483 mLog = log;
484 }
485 }
486 private final ArrayDeque<ValidationLog> mValidationLogs =
487 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
488
489 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700490 synchronized(mValidationLogs) {
491 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
492 mValidationLogs.removeLast();
493 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400494 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700495 }
496 }
497
Hugo Benichif9fdf872016-07-28 17:53:06 +0900498 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900499
Erik Kline065ab6e2016-10-02 18:02:14 +0900500 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900501 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900502
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700503 /**
504 * Implements support for the legacy "one network per network type" model.
505 *
506 * We used to have a static array of NetworkStateTrackers, one for each
507 * network type, but that doesn't work any more now that we can have,
508 * for example, more that one wifi network. This class stores all the
509 * NetworkAgentInfo objects that support a given type, but the legacy
510 * API will only see the first one.
511 *
512 * It serves two main purposes:
513 *
514 * 1. Provide information about "the network for a given type" (since this
515 * API only supports one).
516 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
517 * the first network for a given type changes, or if the default network
518 * changes.
519 */
520 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900521
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900522 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900523 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900524
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700525 /**
526 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
527 * Each list holds references to all NetworkAgentInfos that are used to
528 * satisfy requests for that network type.
529 *
530 * This array is built out at startup such that an unsupported network
531 * doesn't get an ArrayList instance, making this a tristate:
532 * unsupported, supported but not active and active.
533 *
534 * The actual lists are populated when we scan the network types that
535 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900536 *
537 * Threading model:
538 * - addSupportedType() is only called in the constructor
539 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
540 * They are therefore not thread-safe with respect to each other.
541 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
542 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
543 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700544 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900545 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700546
547 public LegacyTypeTracker() {
548 mTypeLists = (ArrayList<NetworkAgentInfo>[])
549 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
550 }
551
552 public void addSupportedType(int type) {
553 if (mTypeLists[type] != null) {
554 throw new IllegalStateException(
555 "legacy list for type " + type + "already initialized");
556 }
557 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
558 }
559
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 public boolean isTypeSupported(int type) {
561 return isNetworkTypeValid(type) && mTypeLists[type] != null;
562 }
563
564 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900565 synchronized (mTypeLists) {
566 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
567 return mTypeLists[type].get(0);
568 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700569 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900570 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700571 }
572
Robert Greenwalt8d482522015-06-24 13:23:42 -0700573 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900574 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900575 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700576 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900577 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900578 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900579 }
580 }
581
582 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700583 public void add(int type, NetworkAgentInfo nai) {
584 if (!isTypeSupported(type)) {
585 return; // Invalid network type.
586 }
587 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
588
589 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
590 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700591 return;
592 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900593 synchronized (mTypeLists) {
594 list.add(nai);
595 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900596
597 // 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 +0900598 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900599 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700600 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
601 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700602 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700603 }
604
Lorenzo Colittia793a672014-07-31 23:20:17 +0900605 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900606 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900607 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
608 if (list == null || list.isEmpty()) {
609 return;
610 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900611 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900612
Hugo Benichi78caa2582016-06-21 09:48:07 +0900613 synchronized (mTypeLists) {
614 if (!list.remove(nai)) {
615 return;
616 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900617 }
618
Robert Greenwalt8d482522015-06-24 13:23:42 -0700619 final DetailedState state = DetailedState.DISCONNECTED;
620
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700622 maybeLogBroadcast(nai, state, type, wasDefault);
623 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900624 }
625
626 if (!list.isEmpty() && wasFirstNetwork) {
627 if (DBG) log("Other network available for type " + type +
628 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900629 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700630 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
631 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900632 }
633 }
634
635 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900636 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
637 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700638 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900639 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700640 }
641 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700642
Robert Greenwalt8d482522015-06-24 13:23:42 -0700643 // send out another legacy broadcast - currently only used for suspend/unsuspend
644 // toggle
645 public void update(NetworkAgentInfo nai) {
646 final boolean isDefault = isDefaultNetwork(nai);
647 final DetailedState state = nai.networkInfo.getDetailedState();
648 for (int type = 0; type < mTypeLists.length; type++) {
649 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700650 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900651 final boolean isFirst = contains && (nai == list.get(0));
652 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700653 maybeLogBroadcast(nai, state, type, isDefault);
654 sendLegacyNetworkBroadcast(nai, state, type);
655 }
656 }
657 }
658
Lorenzo Colittia793a672014-07-31 23:20:17 +0900659 private String naiToString(NetworkAgentInfo nai) {
660 String name = (nai != null) ? nai.name() : "null";
661 String state = (nai.networkInfo != null) ?
662 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
663 "???/???";
664 return name + " " + state;
665 }
666
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700667 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900668 pw.println("mLegacyTypeTracker:");
669 pw.increaseIndent();
670 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700671 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900672 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700673 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900674 pw.println();
675 pw.println("Current state:");
676 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900677 synchronized (mTypeLists) {
678 for (int type = 0; type < mTypeLists.length; type++) {
679 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
680 for (NetworkAgentInfo nai : mTypeLists[type]) {
681 pw.println(type + " " + naiToString(nai));
682 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900683 }
684 }
685 pw.decreaseIndent();
686 pw.decreaseIndent();
687 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700688 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700689 }
690 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
691
Jeff Sharkey899223b2012-08-04 15:24:58 -0700692 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700693 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900694 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
695 }
696
697 @VisibleForTesting
698 protected ConnectivityService(Context context, INetworkManagementService netManager,
699 INetworkStatsService statsService, INetworkPolicyManager policyManager,
700 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800701 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800702
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900703 mSystemProperties = getSystemProperties();
704
Hugo Benichif9fdf872016-07-28 17:53:06 +0900705 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900706 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900707 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900708 mNetworkRequests.put(mDefaultRequest, defaultNRI);
709 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900710
711 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900712 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700713
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900714 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900715 mHandlerThread.start();
716 mHandler = new InternalHandler(mHandlerThread.getLooper());
717 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700718
Jeremy Joslin79294842014-12-03 17:15:28 -0800719 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
720 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
721
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900722 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900723
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700724 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700725 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800726 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700727 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700728 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700729 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700730
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700731 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600732 mPolicyManager.setConnectivityListener(mPolicyListener);
733 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700734 } catch (RemoteException e) {
735 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700736 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700737 }
738
739 final PowerManager powerManager = (PowerManager) context.getSystemService(
740 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700741 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
742 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
743 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800744 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700745
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700746 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700747
Wink Saville51f456f2013-04-23 14:26:51 -0700748 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900749 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700750 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700751 String[] naStrings = context.getResources().getStringArray(
752 com.android.internal.R.array.networkAttributes);
753 for (String naString : naStrings) {
754 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700755 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700756 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700757 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800758 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700759 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700760 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700761 }
Wink Saville51f456f2013-04-23 14:26:51 -0700762 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
763 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
764 n.type);
765 continue;
766 }
Wink Saville975c8482011-04-07 14:23:45 -0700767 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800768 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700769 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700770 continue;
771 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700772 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700773
Wink Saville975c8482011-04-07 14:23:45 -0700774 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700775 mNetworksDefined++;
776 } catch(Exception e) {
777 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700778 }
779 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700780
781 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
782 if (mNetConfigs[TYPE_VPN] == null) {
783 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
784 // don't need to add TYPE_VPN to mNetConfigs.
785 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
786 mNetworksDefined++; // used only in the log() statement below.
787 }
788
Wink Saville5e56bc52013-07-29 15:00:57 -0700789 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700790
Robert Greenwalt50393202011-06-21 17:26:14 -0700791 mProtectedNetworks = new ArrayList<Integer>();
792 int[] protectedNetworks = context.getResources().getIntArray(
793 com.android.internal.R.array.config_protectedNetworks);
794 for (int p : protectedNetworks) {
795 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
796 mProtectedNetworks.add(p);
797 } else {
798 if (DBG) loge("Ignoring protectedNetwork " + p);
799 }
800 }
801
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900802 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
803 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700804
Christopher Wiley497c1472016-10-11 13:26:03 -0700805 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
806 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800807
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700808 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
809
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700810 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700811 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100812 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700813 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700814 intentFilter.addAction(Intent.ACTION_USER_ADDED);
815 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000816 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700817 mContext.registerReceiverAsUser(
818 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000819 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
820 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900821
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700822 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700823 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700824 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700825 } catch (RemoteException e) {
826 loge("Error registering observer :" + e);
827 }
828
Erik Klineda4bfa82015-04-30 12:58:40 +0900829 mSettingsObserver = new SettingsObserver(mContext, mHandler);
830 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800831
John Spurlockbf991a82013-06-24 14:20:23 -0400832 mDataConnectionStats = new DataConnectionStats(mContext);
833 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400834
Jason Monkdecd2952013-10-10 14:02:51 -0400835 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700836
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400837 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900838
839 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900840 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
841 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900842
843 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
844 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
845 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
846 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
847 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
848 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
849 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900850
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900851 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900852 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900853 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700855
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900856 private NetworkRequest createInternetRequestForTransport(
857 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900858 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900859 netCap.addCapability(NET_CAPABILITY_INTERNET);
860 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900861 if (transportType > -1) {
862 netCap.addTransportType(transportType);
863 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900864 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900865 }
866
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900867 // Used only for testing.
868 // TODO: Delete this and either:
869 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
870 // changing ContentResolver to make registerContentObserver non-final).
871 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
872 // by subclassing SettingsObserver.
873 @VisibleForTesting
874 void updateMobileDataAlwaysOn() {
875 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
876 }
877
Erik Klineda4bfa82015-04-30 12:58:40 +0900878 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900879 final boolean enable = toBool(Settings.Global.getInt(
880 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900881 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
882 if (enable == isEnabled) {
883 return; // Nothing to do.
884 }
885
886 if (enable) {
887 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900888 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900889 } else {
890 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
891 }
892 }
893
894 private void registerSettingsCallbacks() {
895 // Watch for global HTTP proxy changes.
896 mSettingsObserver.observe(
897 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
898 EVENT_APPLY_GLOBAL_HTTP_PROXY);
899
900 // Watch for whether or not to keep mobile data always on.
901 mSettingsObserver.observe(
902 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
903 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
904 }
905
Robert Greenwalt34524f02014-05-18 16:22:10 -0700906 private synchronized int nextNetworkRequestId() {
907 return mNextNetworkRequestId++;
908 }
909
Paul Jensen67b0b072015-06-10 11:22:17 -0400910 @VisibleForTesting
911 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400912 synchronized (mNetworkForNetId) {
913 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
914 int netId = mNextNetId;
915 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
916 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500917 if (!mNetIdInUse.get(netId)) {
918 mNetIdInUse.put(netId, true);
919 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400920 }
921 }
922 }
923 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700924 }
925
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600926 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800927 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600928 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
929 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800930 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600931 state = nai.getNetworkState();
932 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800933 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600934 final NetworkInfo info = new NetworkInfo(networkType, 0,
935 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800936 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
937 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600938 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
939 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800940 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600941 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600942 return state;
943 } else {
944 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800945 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400946 }
947
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800948 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
949 if (network == null) {
950 return null;
951 }
952 synchronized (mNetworkForNetId) {
953 return mNetworkForNetId.get(network.netId);
954 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600955 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800956
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900957 private Network[] getVpnUnderlyingNetworks(int uid) {
958 if (!mLockdownEnabled) {
959 int user = UserHandle.getUserId(uid);
960 synchronized (mVpns) {
961 Vpn vpn = mVpns.get(user);
962 if (vpn != null && vpn.appliesToUid(uid)) {
963 return vpn.getUnderlyingNetworks();
964 }
965 }
966 }
967 return null;
968 }
969
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800970 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400971 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800972
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900973 final Network[] networks = getVpnUnderlyingNetworks(uid);
974 if (networks != null) {
975 // getUnderlyingNetworks() returns:
976 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
977 // empty array => the VPN explicitly said "no default network".
978 // non-empty array => the VPN specified one or more default networks; we use the
979 // first one.
980 if (networks.length > 0) {
981 nai = getNetworkAgentInfoForNetwork(networks[0]);
982 } else {
983 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800984 }
985 }
986
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800987 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600988 return nai.getNetworkState();
989 } else {
990 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800991 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400992 }
993
994 /**
995 * Check if UID should be blocked from using the network with the given LinkProperties.
996 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600997 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
998 boolean ignoreBlocked) {
999 // Networks aren't blocked when ignoring blocked status
1000 if (ignoreBlocked) return false;
1001 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001002 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001003
1004 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001005 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001006
Robin Lee17e61832016-05-09 13:46:28 +01001007 synchronized (mVpns) {
1008 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1009 if (vpn != null && vpn.isBlockingUid(uid)) {
1010 return true;
1011 }
1012 }
1013
Robert Greenwalt12e67352014-05-13 21:41:06 -07001014 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001015 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001016 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001017 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001018 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001019
Felipe Lemed31a97f2016-05-06 14:53:50 -07001020 boolean allowed = true;
1021 // Check Data Saver Mode first...
1022 if (networkMetered) {
1023 if ((uidRules & RULE_REJECT_METERED) != 0) {
1024 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1025 // Explicitly blacklisted.
1026 allowed = false;
1027 } else {
1028 allowed = !mRestrictBackground
1029 || (uidRules & RULE_ALLOW_METERED) != 0
1030 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1031 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1032 + " mRestrictBackground=" + mRestrictBackground
1033 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1034 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1035 + ": " + allowed);
1036 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001037 }
Felipe Leme781ba142016-05-09 16:24:48 -07001038 // ...then power restrictions.
1039 if (allowed) {
1040 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001041 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001042 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001043 }
1044 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001045 }
1046
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001047 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001048 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1049 return;
1050 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001051 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001052 synchronized (mBlockedAppUids) {
1053 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001054 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001055 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001056 blocked = false;
1057 } else {
1058 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001059 }
1060 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001061 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1062 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1063 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001064 }
1065
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001066 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001067 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1068 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1069 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1070 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001071 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001072 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001073 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1074
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001075 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001076 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001077 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001078 if (mLockdownTracker != null) {
1079 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001080 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001081
1082 // TODO: apply metered state closer to NetworkAgentInfo
1083 final long token = Binder.clearCallingIdentity();
1084 try {
1085 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1086 } catch (RemoteException e) {
1087 } finally {
1088 Binder.restoreCallingIdentity(token);
1089 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001090 }
1091
1092 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 * Return NetworkInfo for the active (i.e., connected) network interface.
1094 * It is assumed that at most one network is active at a time. If more
1095 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001096 * @return the info for the active network, or {@code null} if none is
1097 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001099 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001101 enforceAccessPermission();
1102 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001103 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001104 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001105 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1106 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 }
1108
Paul Jensen31a94f42015-02-13 14:18:39 -05001109 @Override
1110 public Network getActiveNetwork() {
1111 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001112 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001113 }
1114
1115 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001116 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001117 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001118 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001119 }
1120
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001121 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001122 final int user = UserHandle.getUserId(uid);
1123 int vpnNetId = NETID_UNSET;
1124 synchronized (mVpns) {
1125 final Vpn vpn = mVpns.get(user);
1126 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1127 }
1128 NetworkAgentInfo nai;
1129 if (vpnNetId != NETID_UNSET) {
1130 synchronized (mNetworkForNetId) {
1131 nai = mNetworkForNetId.get(vpnNetId);
1132 }
1133 if (nai != null) return nai.network;
1134 }
1135 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001136 if (nai != null
1137 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1138 nai = null;
1139 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001140 return nai != null ? nai.network : null;
1141 }
1142
Lorenzo Colitti18660282016-07-04 12:55:44 +09001143 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001144 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1145 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001146 final int uid = Binder.getCallingUid();
1147 NetworkState state = getUnfilteredActiveNetworkState(uid);
1148 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001149 }
1150
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001151 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001152 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001153 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001154 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001155 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001156 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 }
1158
1159 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 public NetworkInfo getNetworkInfo(int networkType) {
1161 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001162 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001163 if (getVpnUnderlyingNetworks(uid) != null) {
1164 // A VPN is active, so we may need to return one of its underlying networks. This
1165 // information is not available in LegacyTypeTracker, so we have to get it from
1166 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001167 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001168 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001169 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001170 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001171 }
1172 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001173 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001174 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 }
1176
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001177 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001178 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001180 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001181 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001182 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001183 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001184 return state.networkInfo;
1185 } else {
1186 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001187 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001188 }
1189
1190 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 public NetworkInfo[] getAllNetworkInfo() {
1192 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001193 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001194 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1195 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001196 NetworkInfo info = getNetworkInfo(networkType);
1197 if (info != null) {
1198 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001201 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 }
1203
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001204 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001205 public Network getNetworkForType(int networkType) {
1206 enforceAccessPermission();
1207 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001208 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1209 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001210 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001211 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001212 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001213 }
1214
1215 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001216 public Network[] getAllNetworks() {
1217 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001218 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001219 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001220 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001221 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001222 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001223 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001224 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001225 }
1226
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001227 @Override
1228 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1229 // The basic principle is: if an app's traffic could possibly go over a
1230 // network, without the app doing anything multinetwork-specific,
1231 // (hence, by "default"), then include that network's capabilities in
1232 // the array.
1233 //
1234 // In the normal case, app traffic only goes over the system's default
1235 // network connection, so that's the only network returned.
1236 //
1237 // With a VPN in force, some app traffic may go into the VPN, and thus
1238 // over whatever underlying networks the VPN specifies, while other app
1239 // traffic may go over the system default network (e.g.: a split-tunnel
1240 // VPN, or an app disallowed by the VPN), so the set of networks
1241 // returned includes the VPN's underlying networks and the system
1242 // default.
1243 enforceAccessPermission();
1244
1245 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1246
1247 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001248 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001249 if (nc != null) {
1250 result.put(nai.network, nc);
1251 }
1252
1253 if (!mLockdownEnabled) {
1254 synchronized (mVpns) {
1255 Vpn vpn = mVpns.get(userId);
1256 if (vpn != null) {
1257 Network[] networks = vpn.getUnderlyingNetworks();
1258 if (networks != null) {
1259 for (Network network : networks) {
1260 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001261 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001262 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001263 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001264 }
1265 }
1266 }
1267 }
1268 }
1269 }
1270
1271 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1272 out = result.values().toArray(out);
1273 return out;
1274 }
1275
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001276 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001277 public boolean isNetworkSupported(int networkType) {
1278 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001279 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001280 }
1281
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001282 /**
1283 * Return LinkProperties for the active (i.e., connected) default
1284 * network interface. It is assumed that at most one default network
1285 * is active at a time. If more than one is active, it is indeterminate
1286 * which will be returned.
1287 * @return the ip properties for the active network, or {@code null} if
1288 * none is active
1289 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001290 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001291 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001292 enforceAccessPermission();
1293 final int uid = Binder.getCallingUid();
1294 NetworkState state = getUnfilteredActiveNetworkState(uid);
1295 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001296 }
1297
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001298 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001299 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001300 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001301 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1302 if (nai != null) {
1303 synchronized (nai) {
1304 return new LinkProperties(nai.linkProperties);
1305 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001306 }
1307 return null;
1308 }
1309
Robert Greenwalt12e67352014-05-13 21:41:06 -07001310 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001311 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001312 public LinkProperties getLinkProperties(Network network) {
1313 enforceAccessPermission();
Hugo Benichi29551722017-04-06 16:01:44 +09001314 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1315 }
1316
1317 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1318 if (nai == null) {
1319 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001320 }
Hugo Benichi29551722017-04-06 16:01:44 +09001321 synchronized (nai) {
1322 return new LinkProperties(nai.linkProperties);
1323 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001324 }
1325
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001326 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001327 if (nai != null) {
1328 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001329 if (nai.networkCapabilities != null) {
1330 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001331 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001332 }
1333 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001334 return null;
1335 }
1336
1337 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001338 public NetworkCapabilities getNetworkCapabilities(Network network) {
1339 enforceAccessPermission();
1340 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1341 }
1342
1343 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001344 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001345 // Require internal since we're handing out IMSI details
1346 enforceConnectivityInternalPermission();
1347
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001348 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001349 for (Network network : getAllNetworks()) {
1350 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1351 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001352 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001353 }
1354 }
1355 return result.toArray(new NetworkState[result.size()]);
1356 }
1357
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001358 @Override
1359 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1360 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001361 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001362 final long token = Binder.clearCallingIdentity();
1363 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001364 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1365 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001366 try {
1367 return mPolicyManager.getNetworkQuotaInfo(state);
1368 } catch (RemoteException e) {
1369 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001370 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001371 return null;
1372 } finally {
1373 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001374 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001375 }
1376
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001377 @Override
1378 public boolean isActiveNetworkMetered() {
1379 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001380
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001381 final NetworkInfo info = getActiveNetworkInfo();
1382 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001383 }
1384
Jeff Sharkey216c1812012-08-05 14:29:23 -07001385 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1386 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001387 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001388 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001389 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001390 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001391 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001392
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001393 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 * Ensure that a network route exists to deliver traffic to the specified
1395 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001396 * @param networkType the type of the network over which traffic to the
1397 * specified host is to be routed
1398 * @param hostAddress the IP address of the host to which the route is
1399 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 * @return {@code true} on success, {@code false} on failure
1401 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001402 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001403 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001405 if (mProtectedNetworks.contains(networkType)) {
1406 enforceConnectivityInternalPermission();
1407 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001408
Chad Brubakerc0234532014-02-14 13:24:29 -08001409 InetAddress addr;
1410 try {
1411 addr = InetAddress.getByAddress(hostAddress);
1412 } catch (UnknownHostException e) {
1413 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1414 return false;
1415 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001418 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 return false;
1420 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001421
1422 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1423 if (nai == null) {
1424 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1425 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1426 } else {
1427 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1428 }
1429 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001430 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001431
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001432 DetailedState netState;
1433 synchronized (nai) {
1434 netState = nai.networkInfo.getDetailedState();
1435 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001436
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001437 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001438 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001439 log("requestRouteToHostAddress on down network "
1440 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001441 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001442 }
1443 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001445
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001446 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001447 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001448 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001449 LinkProperties lp;
1450 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001451 synchronized (nai) {
1452 lp = nai.linkProperties;
1453 netId = nai.network.netId;
1454 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001455 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001456 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1457 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001458 } finally {
1459 Binder.restoreCallingIdentity(token);
1460 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001461 }
1462
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001463 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001464 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001465 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001466 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001467 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001468 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001469 if (bestRoute.getGateway().equals(addr)) {
1470 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001471 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001472 } else {
1473 // if we will connect to this through another route, add a direct route
1474 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001475 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001476 }
1477 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001478 if (DBG) log("Adding legacy route " + bestRoute +
1479 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001480 try {
1481 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1482 } catch (Exception e) {
1483 // never crash - catch them all
1484 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001485 return false;
1486 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001487 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
1489
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001490 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1491 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001492 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001493 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001494 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001495 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001496 }
1497
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001498 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001499 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001500 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001501 if (oldRules == uidRules) return;
1502
Felipe Leme781ba142016-05-09 16:24:48 -07001503 if (uidRules == RULE_NONE) {
1504 mUidRules.delete(uid);
1505 } else {
1506 mUidRules.put(uid, uidRules);
1507 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001508 }
1509
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001510 // TODO: notify UID when it has requested targeted updates
1511 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001512
1513 @Override
1514 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001515 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001516 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001517 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001518 }
1519
1520 synchronized (mRulesLock) {
1521 mMeteredIfaces.clear();
1522 for (String iface : meteredIfaces) {
1523 mMeteredIfaces.add(iface);
1524 }
1525 }
1526 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001527
1528 @Override
1529 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1530 // caller is NPMS, since we only register with them
1531 if (LOGD_RULES) {
1532 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1533 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001534
1535 synchronized (mRulesLock) {
1536 mRestrictBackground = restrictBackground;
1537 }
1538
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001539 if (restrictBackground) {
1540 log("onRestrictBackgroundChanged(true): disabling tethering");
1541 mTethering.untetherAll();
1542 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001543 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001544
1545 @Override
1546 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1547 if (LOGD_RULES) {
1548 // caller is NPMS, since we only register with them
1549 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1550 + whitelisted + ")");
1551 }
1552 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001553 @Override
1554 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1555 if (LOGD_RULES) {
1556 // caller is NPMS, since we only register with them
1557 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1558 + blacklisted + ")");
1559 }
1560 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001561 };
1562
Robin Lee3b3dd942015-05-12 18:14:58 +01001563 /**
1564 * Require that the caller is either in the same user or has appropriate permission to interact
1565 * across users.
1566 *
1567 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1568 */
1569 private void enforceCrossUserPermission(int userId) {
1570 if (userId == UserHandle.getCallingUserId()) {
1571 // Not a cross-user call.
1572 return;
1573 }
1574 mContext.enforceCallingOrSelfPermission(
1575 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1576 "ConnectivityService");
1577 }
1578
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001579 private void enforceInternetPermission() {
1580 mContext.enforceCallingOrSelfPermission(
1581 android.Manifest.permission.INTERNET,
1582 "ConnectivityService");
1583 }
1584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001586 mContext.enforceCallingOrSelfPermission(
1587 android.Manifest.permission.ACCESS_NETWORK_STATE,
1588 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590
1591 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001592 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 }
1594
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001595 private void enforceTetherAccessPermission() {
1596 mContext.enforceCallingOrSelfPermission(
1597 android.Manifest.permission.ACCESS_NETWORK_STATE,
1598 "ConnectivityService");
1599 }
1600
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001601 private void enforceConnectivityInternalPermission() {
1602 mContext.enforceCallingOrSelfPermission(
1603 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1604 "ConnectivityService");
1605 }
1606
Hugo Benichi514da602016-07-19 15:59:27 +09001607 private void enforceConnectivityRestrictedNetworksPermission() {
1608 try {
1609 mContext.enforceCallingOrSelfPermission(
1610 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1611 "ConnectivityService");
1612 return;
1613 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1614 enforceConnectivityInternalPermission();
1615 }
1616
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001617 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001618 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001619 }
1620
Lorenzo Colitti18660282016-07-04 12:55:44 +09001621 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001622 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001623 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001624 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001625 }
1626
1627 private void sendInetConditionBroadcast(NetworkInfo info) {
1628 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1629 }
1630
Wink Saville628b0852011-08-04 15:01:58 -07001631 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001632 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001633 info = new NetworkInfo(info);
1634 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001635 }
1636
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001637 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001638 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001639 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 if (info.isFailover()) {
1641 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1642 info.setFailover(false);
1643 }
1644 if (info.getReason() != null) {
1645 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1646 }
1647 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001648 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1649 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001651 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001652 return intent;
1653 }
1654
1655 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1656 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1657 }
1658
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001659 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001660 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1661 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1662 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001663 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001664 final long ident = Binder.clearCallingIdentity();
1665 try {
1666 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1667 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1668 } finally {
1669 Binder.restoreCallingIdentity(ident);
1670 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001671 }
1672
Mike Lockwood0f79b542009-08-14 14:18:49 -04001673 private void sendStickyBroadcast(Intent intent) {
1674 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001675 if (!mSystemReady) {
1676 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001677 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001678 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001679 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001680 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001681 }
1682
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001683 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001684 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001685 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001686 final NetworkInfo ni = intent.getParcelableExtra(
1687 ConnectivityManager.EXTRA_NETWORK_INFO);
1688 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1689 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1690 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001691 } else {
1692 BroadcastOptions opts = BroadcastOptions.makeBasic();
1693 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1694 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001695 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001696 final IBatteryStats bs = BatteryStatsService.getService();
1697 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001698 bs.noteConnectivityChanged(intent.getIntExtra(
1699 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1700 ni != null ? ni.getState().toString() : "?");
1701 } catch (RemoteException e) {
1702 }
1703 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001704 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001705 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001706 } finally {
1707 Binder.restoreCallingIdentity(ident);
1708 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001709 }
1710 }
1711
1712 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001713 loadGlobalProxy();
1714
Mike Lockwood0f79b542009-08-14 14:18:49 -04001715 synchronized(this) {
1716 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001717 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001718 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001719 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001720 }
1721 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001722 // load the global proxy at startup
1723 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001724
Robin Lee244ce8e2016-01-05 18:03:46 +00001725 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1726 // for user to unlock device too.
1727 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001728
Erik Klineda4bfa82015-04-30 12:58:40 +09001729 // Configure whether mobile data is always on.
1730 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1731
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001732 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001733
1734 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 }
1736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001738 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001739 *
1740 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001741 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001742 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001743 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1744 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001745
1746 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001747 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001748
Robert Greenwalt7b816022014-04-18 15:25:25 -07001749 if (networkAgent.networkCapabilities.hasTransport(
1750 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001751 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1752 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001753 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001754 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001755 } else if (networkAgent.networkCapabilities.hasTransport(
1756 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001757 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1758 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001759 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001760 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001761 } else {
1762 // do not track any other networks
1763 timeout = 0;
1764 }
1765
Robert Greenwalt7b816022014-04-18 15:25:25 -07001766 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001767 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001768 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001769 } catch (Exception e) {
1770 // You shall not crash!
1771 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001772 }
1773 }
1774 }
1775
1776 /**
1777 * Remove data activity tracking when network disconnects.
1778 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001779 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1780 final String iface = networkAgent.linkProperties.getInterfaceName();
1781 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001782
Robert Greenwalt7b816022014-04-18 15:25:25 -07001783 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1784 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001785 try {
1786 // the call fails silently if no idletimer setup for this interface
1787 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001788 } catch (Exception e) {
1789 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001790 }
1791 }
1792 }
1793
1794 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001795 * Reads the network specific MTU size from reources.
1796 * and set it on it's iface.
1797 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001798 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1799 final String iface = newLp.getInterfaceName();
1800 final int mtu = newLp.getMtu();
Pierre Imaiaccd5fc2016-02-08 16:01:40 +09001801 if (oldLp == null && mtu == 0) {
1802 // Silently ignore unset MTU value.
1803 return;
1804 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001805 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1806 if (VDBG) log("identical MTU - not setting");
1807 return;
1808 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001809 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001810 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001811 return;
1812 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001813
w1997615afd812014-08-05 15:18:11 -07001814 // Cannot set MTU without interface name
1815 if (TextUtils.isEmpty(iface)) {
1816 loge("Setting MTU size with null iface.");
1817 return;
1818 }
1819
Robert Greenwalt7b816022014-04-18 15:25:25 -07001820 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001821 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001822 mNetd.setMtu(iface, mtu);
1823 } catch (Exception e) {
1824 Slog.e(TAG, "exception in setMtu()" + e);
1825 }
1826 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001827
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001828 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001829 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1830
1831 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001832 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001833 protected MockableSystemProperties getSystemProperties() {
1834 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001835 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001836
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001837 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1838 if (isDefaultNetwork(nai) == false) {
1839 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001840 }
1841
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001842 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1843 String[] values = null;
1844 if (tcpBufferSizes != null) {
1845 values = tcpBufferSizes.split(",");
1846 }
1847
1848 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001849 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001850 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1851 values = tcpBufferSizes.split(",");
1852 }
1853
1854 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1855
1856 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001857 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001858
1859 final String prefix = "/sys/kernel/ipv4/tcp_";
1860 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1861 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1862 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1863 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1864 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1865 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1866 mCurrentTcpBufferSizes = tcpBufferSizes;
1867 } catch (IOException e) {
1868 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001869 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001870
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001871 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001872 Settings.Global.TCP_DEFAULT_INIT_RWND,
1873 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001874 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1875 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001876 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001877 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001878 }
1879
Mattias Falk8b47b362011-08-23 14:15:13 +02001880 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001881 /*
1882 * Tell the VMs to toss their DNS caches
1883 */
1884 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1885 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001886 /*
1887 * Connectivity events can happen before boot has completed ...
1888 */
1889 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001890 final long ident = Binder.clearCallingIdentity();
1891 try {
1892 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1893 } finally {
1894 Binder.restoreCallingIdentity(ident);
1895 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001896 }
1897
Robert Greenwalt562cc542014-05-15 18:07:26 -07001898 @Override
1899 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001900 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001901 NETWORK_RESTORE_DELAY_PROP_NAME);
1902 if(restoreDefaultNetworkDelayStr != null &&
1903 restoreDefaultNetworkDelayStr.length() != 0) {
1904 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001905 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001906 } catch (NumberFormatException e) {
1907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001909 // if the system property isn't set, use the value for the apn type
1910 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1911
1912 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1913 (mNetConfigs[networkType] != null)) {
1914 ret = mNetConfigs[networkType].restoreTime;
1915 }
1916 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 }
1918
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001919 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001920 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001921 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001922 }
1923 return false;
1924 }
1925
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001926 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1927 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1928 final long DIAG_TIME_MS = 5000;
1929 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1930 // Start gathering diagnostic information.
1931 netDiags.add(new NetworkDiagnostics(
1932 nai.network,
1933 new LinkProperties(nai.linkProperties), // Must be a copy.
1934 DIAG_TIME_MS));
1935 }
1936
1937 for (NetworkDiagnostics netDiag : netDiags) {
1938 pw.println();
1939 netDiag.waitForMeasurements();
1940 netDiag.dump(pw);
1941 }
1942 }
1943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001945 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1946 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001947 if (mContext.checkCallingOrSelfPermission(
1948 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001950 pw.println("Permission Denial: can't dump ConnectivityService " +
1951 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1952 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 return;
1954 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001955
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001956 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001957 dumpNetworkDiagnostics(pw);
1958 return;
1959 }
Erik Kline379747a2015-06-05 17:47:34 +09001960
Lorenzo Colittie3805462015-06-03 11:18:24 +09001961 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001962 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001963 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001964 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001965 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001966 pw.println();
1967
Paul Jensen85cf78e2015-06-25 13:25:07 -04001968 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001969 pw.print("Active default network: ");
1970 if (defaultNai == null) {
1971 pw.println("none");
1972 } else {
1973 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001975 pw.println();
1976
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001977 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001978 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001979 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1980 pw.println(nai.toString());
1981 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001982 pw.println(String.format(
1983 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1984 nai.numForegroundNetworkRequests(),
1985 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1986 nai.numBackgroundNetworkRequests(),
1987 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001988 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001989 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1990 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001991 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001992 pw.decreaseIndent();
1993 pw.println("Lingered:");
1994 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001995 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001996 pw.decreaseIndent();
1997 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001998 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001999 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002000 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002001
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002002 pw.println("Metered Interfaces:");
2003 pw.increaseIndent();
2004 for (String value : mMeteredIfaces) {
2005 pw.println(value);
2006 }
2007 pw.decreaseIndent();
2008 pw.println();
2009
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002010 pw.print("Restrict background: ");
2011 pw.println(mRestrictBackground);
2012 pw.println();
2013
Felipe Leme46c4fc32016-05-04 09:21:43 -07002014 pw.println("Status for known UIDs:");
2015 pw.increaseIndent();
2016 final int size = mUidRules.size();
2017 for (int i = 0; i < size; i++) {
2018 final int uid = mUidRules.keyAt(i);
2019 pw.print("UID=");
2020 pw.print(uid);
2021 final int uidRules = mUidRules.get(uid, RULE_NONE);
2022 pw.print(" rules=");
2023 pw.print(uidRulesToString(uidRules));
2024 pw.println();
2025 }
2026 pw.println();
2027 pw.decreaseIndent();
2028
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002029 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002030 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002031 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2032 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002033 }
2034 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002035 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002036
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002037 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002038
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002039 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002040 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002041
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002042 pw.println();
2043 mKeepaliveTracker.dump(pw);
2044
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002045 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002046 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002047
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002048 if (argsContain(args, "--short") == false) {
2049 pw.println();
2050 synchronized (mValidationLogs) {
2051 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002052 for (ValidationLog p : mValidationLogs) {
2053 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002054 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002055 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002056 pw.decreaseIndent();
2057 }
2058 }
Erik Kline7523eb32015-07-09 18:24:03 +09002059
2060 pw.println();
2061 pw.println("mNetworkRequestInfoLogs (most recent first):");
2062 pw.increaseIndent();
2063 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2064 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002065
2066 pw.println();
2067 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2068 pw.increaseIndent();
2069 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2070 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002071
2072 pw.println();
2073 pw.println("NetTransition WakeLock activity (most recent first):");
2074 pw.increaseIndent();
2075 mWakelockLogs.reverseDump(fd, pw, args);
2076 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 }
2079
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002080 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002081 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002082 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002083 if (officialNai != null && officialNai.equals(nai)) return true;
2084 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002085 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002086 " - " + nai);
2087 }
2088 return false;
2089 }
2090
Robert Greenwalt42acef32009-08-12 16:08:25 -07002091 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002092 private class NetworkStateTrackerHandler extends Handler {
2093 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002094 super(looper);
2095 }
2096
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002097 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002099 default:
2100 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002101 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002102 handleAsyncChannelHalfConnect(msg);
2103 break;
2104 }
2105 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2106 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2107 if (nai != null) nai.asyncChannel.disconnect();
2108 break;
2109 }
2110 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2111 handleAsyncChannelDisconnected(msg);
2112 break;
2113 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002114 }
2115 return true;
2116 }
2117
2118 private void maybeHandleNetworkAgentMessage(Message msg) {
2119 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2120 if (nai == null) {
2121 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002122 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002123 }
2124 return;
2125 }
2126
2127 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002128 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002129 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2130 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002131 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2132 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002133 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002134 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002135 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002136 break;
2137 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002138 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002139 if (VDBG) {
2140 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002141 "; created=" + nai.created +
2142 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002144 LinkProperties oldLp = nai.linkProperties;
2145 synchronized (nai) {
2146 nai.linkProperties = (LinkProperties)msg.obj;
2147 }
Robin Lee585e2482016-05-01 23:00:00 +01002148 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002149 break;
2150 }
2151 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002152 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002153 updateNetworkInfo(nai, info);
2154 break;
2155 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002156 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002157 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002158 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002159 break;
2160 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002161 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002162 try {
2163 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002164 } catch (Exception e) {
2165 // Never crash!
2166 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002167 }
2168 break;
2169 }
2170 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002171 try {
2172 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002173 } catch (Exception e) {
2174 // Never crash!
2175 loge("Exception in removeVpnUidRanges: " + e);
2176 }
2177 break;
2178 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002179 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002180 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2181 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002182 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002183 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002184 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002185 break;
2186 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002187 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002188 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2189 break;
2190 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002191 }
2192 }
2193
2194 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2195 switch (msg.what) {
2196 default:
2197 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002198 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002199 final NetworkAgentInfo nai;
2200 synchronized (mNetworkForNetId) {
2201 nai = mNetworkForNetId.get(msg.arg2);
2202 }
2203 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002204 final boolean valid =
2205 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002206 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002207 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2208 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002209 if (valid != nai.lastValidated) {
2210 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002211 nai.lastValidated = valid;
2212 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002213 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002214 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2215 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002216 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002217 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002218 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002219 Bundle redirectUrlBundle = new Bundle();
2220 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002221 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002222 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002223 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002224 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002225 if (wasValidated && !nai.lastValidated) {
2226 handleNetworkUnvalidated(nai);
2227 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002228 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002229 break;
2230 }
Paul Jensen869868be2014-05-15 10:33:05 -04002231 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002232 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002233 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002234 final NetworkAgentInfo nai;
2235 synchronized (mNetworkForNetId) {
2236 nai = mNetworkForNetId.get(netId);
2237 }
Calvin On1f64f3f2016-10-11 15:10:46 -07002238 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002239 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002240 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002241 nai.lastCaptivePortalDetected = visible;
2242 nai.everCaptivePortalDetected |= visible;
Calvin On1f64f3f2016-10-11 15:10:46 -07002243 if (nai.lastCaptivePortalDetected &&
2244 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2245 if (DBG) log("Avoiding captive portal network: " + nai.name());
2246 nai.asyncChannel.sendMessage(
2247 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2248 teardownUnneededNetwork(nai);
2249 break;
2250 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002251 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002252 }
2253 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002254 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002255 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002256 if (nai == null) {
2257 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2258 break;
2259 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002260 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002261 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002262 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002263 }
Paul Jensen869868be2014-05-15 10:33:05 -04002264 }
Paul Jensen869868be2014-05-15 10:33:05 -04002265 break;
2266 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002267 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002268 return true;
2269 }
2270
Calvin On1f64f3f2016-10-11 15:10:46 -07002271 private int getCaptivePortalMode() {
2272 return Settings.Global.getInt(mContext.getContentResolver(),
2273 Settings.Global.CAPTIVE_PORTAL_MODE,
2274 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2275 }
2276
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002277 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2278 switch (msg.what) {
2279 default:
2280 return false;
2281 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2282 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2283 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2284 handleLingerComplete(nai);
2285 }
2286 break;
2287 }
2288 }
2289 return true;
2290 }
2291
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002292 @Override
2293 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002294 if (!maybeHandleAsyncChannelMessage(msg) &&
2295 !maybeHandleNetworkMonitorMessage(msg) &&
2296 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002297 maybeHandleNetworkAgentMessage(msg);
2298 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002299 }
2300 }
2301
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002302 private void updateLingerState(NetworkAgentInfo nai, long now) {
2303 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2304 // 2. If the network was lingering and there are now requests, unlinger it.
2305 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2306 // one lingered request, start lingering.
2307 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002308 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002309 if (DBG) log("Unlingering " + nai.name());
2310 nai.unlinger();
2311 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002312 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002313 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002314 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002315 nai.linger();
2316 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2317 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2318 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002319 }
2320
Robert Greenwalt7b816022014-04-18 15:25:25 -07002321 private void handleAsyncChannelHalfConnect(Message msg) {
2322 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002323 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002324 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2325 if (VDBG) log("NetworkFactory connected");
2326 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002327 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002328 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002329 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002330 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002331 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002332 }
2333 } else {
2334 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002335 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002336 }
2337 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2338 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2339 if (VDBG) log("NetworkAgent connected");
2340 // A network agent has requested a connection. Establish the connection.
2341 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2342 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2343 } else {
2344 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002345 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002346 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002347 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002348 synchronized (mNetworkForNetId) {
2349 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002350 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002351 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002352 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002353 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002354 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002355 }
2356 }
2357 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002358
Robert Greenwalt7b816022014-04-18 15:25:25 -07002359 private void handleAsyncChannelDisconnected(Message msg) {
2360 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2361 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002362 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002363 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002364 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002365 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002366 // TODO - if we move the logic to the network agent (have them disconnect
2367 // because they lost all their requests or because their score isn't good)
2368 // then they would disconnect organically, report their new state and then
2369 // disconnect the channel.
2370 if (nai.networkInfo.isConnected()) {
2371 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2372 null, null);
2373 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002374 final boolean wasDefault = isDefaultNetwork(nai);
2375 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002376 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002377 // Log default network disconnection before required book-keeping.
2378 // Let rematchAllNetworksAndRequests() below record a new default network event
2379 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2380 // whose timestamps tell how long it takes to recover a default network.
2381 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002382 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002383 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002384 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2385 // by other networks that are already connected. Perhaps that can be done by
2386 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2387 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002388 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002389 mKeepaliveTracker.handleStopAllKeepalives(nai,
2390 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002391 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002392 mNetworkAgentInfos.remove(msg.replyTo);
2393 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002394 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002395 // Remove the NetworkAgent, but don't mark the netId as
2396 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002397 mNetworkForNetId.remove(nai.network.netId);
2398 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002399 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002400 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2401 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002402 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2403 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2404 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002405 sendUpdatedScoreToFactories(request, 0);
2406 }
2407 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002408 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002409 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002410 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002411 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002412 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002413 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002414 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002415 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002416 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002417 if (nai.created) {
2418 // Tell netd to clean up the configuration for this network
2419 // (routing rules, DNS, etc).
2420 // This may be slow as it requires a lot of netd shelling out to ip and
2421 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2422 // after we've rematched networks with requests which should make a potential
2423 // fallback network the default or requested a new network from the
2424 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2425 // long time.
2426 try {
2427 mNetd.removeNetwork(nai.network.netId);
2428 } catch (Exception e) {
2429 loge("Exception removing network: " + e);
2430 }
2431 }
2432 synchronized (mNetworkForNetId) {
2433 mNetIdInUse.delete(nai.network.netId);
2434 }
2435 } else {
2436 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2437 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002438 }
2439 }
2440
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002441 // If this method proves to be too slow then we can maintain a separate
2442 // pendingIntent => NetworkRequestInfo map.
2443 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2444 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2445 Intent intent = pendingIntent.getIntent();
2446 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2447 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2448 if (existingPendingIntent != null &&
2449 existingPendingIntent.getIntent().filterEquals(intent)) {
2450 return entry.getValue();
2451 }
2452 }
2453 return null;
2454 }
2455
2456 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2457 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2458
2459 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2460 if (existingRequest != null) { // remove the existing request.
2461 if (DBG) log("Replacing " + existingRequest.request + " with "
2462 + nri.request + " because their intents matched.");
2463 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2464 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002465 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002466 }
2467
Erik Klineda4bfa82015-04-30 12:58:40 +09002468 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002469 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002470 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002471 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002472 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002473 if (nri.request.networkCapabilities.hasSignalStrength() &&
2474 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2475 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002476 }
2477 }
2478 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002479 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002480 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002481 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002482 }
2483 }
2484
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002485 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2486 int callingUid) {
2487 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2488 if (nri != null) {
2489 handleReleaseNetworkRequest(nri.request, callingUid);
2490 }
2491 }
2492
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002493 // Determines whether the network is the best (or could become the best, if it validated), for
2494 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2495 // on the value of reason:
2496 //
2497 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2498 // then it should be torn down.
2499 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2500 // then it should be lingered.
2501 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2502 final int numRequests;
2503 switch (reason) {
2504 case TEARDOWN:
2505 numRequests = nai.numRequestNetworkRequests();
2506 break;
2507 case LINGER:
2508 numRequests = nai.numForegroundNetworkRequests();
2509 break;
2510 default:
2511 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2512 return true;
2513 }
2514
2515 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002516 return false;
2517 }
Paul Jensene0988542015-06-25 15:30:08 -04002518 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002519 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2520 // Background requests don't affect lingering.
2521 continue;
2522 }
2523
Paul Jensene0988542015-06-25 15:30:08 -04002524 // If this Network is already the highest scoring Network for a request, or if
2525 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002526 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002527 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002528 // Note that this catches two important cases:
2529 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2530 // is currently satisfying the request. This is desirable when
2531 // cellular ends up validating but WiFi does not.
2532 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002533 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002534 // WiFi ends up validating and out scoring cellular.
2535 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2536 nai.getCurrentScoreAsValidated())) {
2537 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002538 }
2539 }
Paul Jensene0988542015-06-25 15:30:08 -04002540 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002541 }
2542
Erik Klineacdd6392016-07-07 16:50:58 +09002543 private NetworkRequestInfo getNriForAppRequest(
2544 NetworkRequest request, int callingUid, String requestedOperation) {
2545 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2546
Robert Greenwalt9258c642014-03-26 16:47:06 -07002547 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002548 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002549 log(String.format("UID %d attempted to %s for unowned request %s",
2550 callingUid, requestedOperation, nri));
2551 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002552 }
Erik Klineacdd6392016-07-07 16:50:58 +09002553 }
2554
2555 return nri;
2556 }
2557
Erik Kline3841a482015-11-25 12:49:38 +09002558 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002559 if (mNetworkRequests.get(nri.request) == null) {
2560 return;
Erik Kline3841a482015-11-25 12:49:38 +09002561 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002562 if (mNetworkForRequestId.get(nri.request.requestId) != null) {
2563 return;
2564 }
2565 if (VDBG || (DBG && nri.request.isRequest())) {
2566 log("releasing " + nri.request + " (timeout)");
2567 }
2568 handleRemoveNetworkRequest(nri);
2569 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline3841a482015-11-25 12:49:38 +09002570 }
2571
Erik Klineacdd6392016-07-07 16:50:58 +09002572 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002573 final NetworkRequestInfo nri =
2574 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2575 if (nri == null) {
2576 return;
Erik Kline3841a482015-11-25 12:49:38 +09002577 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002578 if (VDBG || (DBG && nri.request.isRequest())) {
2579 log("releasing " + nri.request + " (release request)");
2580 }
2581 handleRemoveNetworkRequest(nri);
Erik Kline3841a482015-11-25 12:49:38 +09002582 }
Erik Klineacdd6392016-07-07 16:50:58 +09002583
Hugo Benichidba33db2017-03-23 22:40:44 +09002584 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002585 nri.unlinkDeathRecipient();
Erik Kline3841a482015-11-25 12:49:38 +09002586 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002587 synchronized (mUidToNetworkRequestCount) {
2588 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2589 if (requests < 1) {
2590 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2591 nri.mUid);
2592 } else if (requests == 1) {
2593 mUidToNetworkRequestCount.removeAt(
2594 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2595 } else {
2596 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2597 }
2598 }
2599 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2600 if (nri.request.isRequest()) {
2601 boolean wasKept = false;
2602 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2603 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002604 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002605 nai.removeRequest(nri.request.requestId);
2606 if (VDBG) {
2607 log(" Removing from current network " + nai.name() +
2608 ", leaving " + nai.numNetworkRequests() + " requests.");
2609 }
2610 // If there are still lingered requests on this network, don't tear it down,
2611 // but resume lingering instead.
2612 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002613 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002614 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2615 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002616 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002617 wasKept = true;
2618 }
2619 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002620 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2621 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002622 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002623 }
Erik Klineacdd6392016-07-07 16:50:58 +09002624 }
2625
2626 // TODO: remove this code once we know that the Slog.wtf is never hit.
2627 //
2628 // Find all networks that are satisfying this request and remove the request
2629 // from their request lists.
2630 // TODO - it's my understanding that for a request there is only a single
2631 // network satisfying it, so this loop is wasteful
2632 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2633 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2634 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2635 otherNai.name() + ", but mNetworkAgentInfos says " +
2636 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002637 }
2638 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002639
Erik Klineacdd6392016-07-07 16:50:58 +09002640 // Maintain the illusion. When this request arrived, we might have pretended
2641 // that a network connected to serve it, even though the network was already
2642 // connected. Now that this request has gone away, we might have to pretend
2643 // that the network disconnected. LegacyTypeTracker will generate that
2644 // phantom disconnect for this type.
2645 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2646 boolean doRemove = true;
2647 if (wasKept) {
2648 // check if any of the remaining requests for this network are for the
2649 // same legacy type - if so, don't remove the nai
2650 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2651 NetworkRequest otherRequest = nai.requestAt(i);
2652 if (otherRequest.legacyType == nri.request.legacyType &&
2653 otherRequest.isRequest()) {
2654 if (DBG) log(" still have other legacy request - leaving");
2655 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002656 }
2657 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002658 }
2659
Erik Klineacdd6392016-07-07 16:50:58 +09002660 if (doRemove) {
2661 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002662 }
2663 }
Erik Klineacdd6392016-07-07 16:50:58 +09002664
2665 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2666 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2667 nri.request);
2668 }
2669 } else {
2670 // listens don't have a singular affectedNetwork. Check all networks to see
2671 // if this listen request applies and remove it.
2672 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2673 nai.removeRequest(nri.request.requestId);
2674 if (nri.request.networkCapabilities.hasSignalStrength() &&
2675 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2676 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2677 }
2678 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002679 }
2680 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002681
Lorenzo Colitti18660282016-07-04 12:55:44 +09002682 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002683 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2684 enforceConnectivityInternalPermission();
2685 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002686 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002687 }
2688
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002689 @Override
2690 public void setAvoidUnvalidated(Network network) {
2691 enforceConnectivityInternalPermission();
2692 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2693 }
2694
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002695 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2696 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2697 " accept=" + accept + " always=" + always);
2698
2699 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2700 if (nai == null) {
2701 // Nothing to do.
2702 return;
2703 }
2704
2705 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002706 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002707 return;
2708 }
2709
2710 if (!nai.networkMisc.explicitlySelected) {
2711 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2712 }
2713
2714 if (accept != nai.networkMisc.acceptUnvalidated) {
2715 int oldScore = nai.getCurrentScore();
2716 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002717 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002718 sendUpdatedScoreToFactories(nai);
2719 }
2720
2721 if (always) {
2722 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002723 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002724 }
2725
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002726 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002727 // Tell the NetworkAgent to not automatically reconnect to the network.
2728 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2729 // Teardown the nework.
2730 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002731 }
2732
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002733 }
2734
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002735 private void handleSetAvoidUnvalidated(Network network) {
2736 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2737 if (nai == null || nai.lastValidated) {
2738 // Nothing to do. The network either disconnected or revalidated.
2739 return;
2740 }
2741 if (!nai.avoidUnvalidated) {
2742 int oldScore = nai.getCurrentScore();
2743 nai.avoidUnvalidated = true;
2744 rematchAllNetworksAndRequests(nai, oldScore);
2745 sendUpdatedScoreToFactories(nai);
2746 }
2747 }
2748
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002749 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002750 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002751 mHandler.sendMessageDelayed(
2752 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2753 PROMPT_UNVALIDATED_DELAY_MS);
2754 }
2755
Hugo Benichic8e9e122016-09-14 23:23:08 +00002756 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002757 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002758 }
2759
Erik Kline065ab6e2016-10-02 18:02:14 +09002760 private void rematchForAvoidBadWifiUpdate() {
2761 rematchAllNetworksAndRequests(null, 0);
2762 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2763 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2764 sendUpdatedScoreToFactories(nai);
2765 }
2766 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002767 }
2768
Erik Kline065ab6e2016-10-02 18:02:14 +09002769 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002770 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002771 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002772 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002773 if (!configRestrict) {
2774 pw.println("Bad Wi-Fi avoidance: unrestricted");
2775 return;
2776 }
2777
2778 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2779 pw.increaseIndent();
2780 pw.println("Config restrict: " + configRestrict);
2781
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002782 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002783 String description;
2784 // Can't use a switch statement because strings are legal case labels, but null is not.
2785 if ("0".equals(value)) {
2786 description = "get stuck";
2787 } else if (value == null) {
2788 description = "prompt";
2789 } else if ("1".equals(value)) {
2790 description = "avoid";
2791 } else {
2792 description = value + " (?)";
2793 }
2794 pw.println("User setting: " + description);
2795 pw.println("Network overrides:");
2796 pw.increaseIndent();
2797 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2798 if (nai.avoidUnvalidated) {
2799 pw.println(nai.name());
2800 }
2801 }
2802 pw.decreaseIndent();
2803 pw.decreaseIndent();
2804 }
2805
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002806 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2807 final String action;
2808 switch (type) {
2809 case NO_INTERNET:
2810 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2811 break;
2812 case LOST_INTERNET:
2813 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2814 break;
2815 default:
2816 Slog.wtf(TAG, "Unknown notification type " + type);
2817 return;
2818 }
2819
2820 Intent intent = new Intent(action);
2821 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2822 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2823 intent.setClassName("com.android.settings",
2824 "com.android.settings.wifi.WifiNoInternetDialog");
2825
2826 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2827 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2828 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2829 }
2830
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002831 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002832 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002833 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2834
2835 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2836 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002837 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002838 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002839 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2840 return;
2841 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002842 showValidationNotification(nai, NotificationType.NO_INTERNET);
2843 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002844
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002845 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2846 NetworkCapabilities nc = nai.networkCapabilities;
2847 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002848
Erik Kline065ab6e2016-10-02 18:02:14 +09002849 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002850 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002851 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2852 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002853 }
2854
Lorenzo Colitti46aa9c02017-01-24 18:08:41 +09002855 @Override
2856 public int getMultipathPreference(Network network) {
2857 enforceAccessPermission();
2858
2859 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2860 if (nai != null && !nai.networkInfo.isMetered()) {
2861 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2862 }
2863
2864 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2865 }
2866
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002867 private class InternalHandler extends Handler {
2868 public InternalHandler(Looper looper) {
2869 super(looper);
2870 }
2871
2872 @Override
2873 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002874 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002875 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002876 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002877 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002878 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002879 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002880 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002881 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002882 break;
2883 }
Jason Monkdecd2952013-10-10 14:02:51 -04002884 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002885 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002886 break;
2887 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002888 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002889 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2890 break;
2891 }
2892 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2893 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002894 break;
2895 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002896 case EVENT_REGISTER_NETWORK_AGENT: {
2897 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2898 break;
2899 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002900 case EVENT_REGISTER_NETWORK_REQUEST:
2901 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002902 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002903 break;
2904 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002905 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2906 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002907 handleRegisterNetworkRequestWithIntent(msg);
2908 break;
2909 }
Erik Kline3841a482015-11-25 12:49:38 +09002910 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2911 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2912 handleTimedOutNetworkRequest(nri);
2913 break;
2914 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002915 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2916 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2917 break;
2918 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002919 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002920 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002921 break;
2922 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002923 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002924 Network network = (Network) msg.obj;
2925 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002926 break;
2927 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002928 case EVENT_SET_AVOID_UNVALIDATED: {
2929 handleSetAvoidUnvalidated((Network) msg.obj);
2930 break;
2931 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002932 case EVENT_PROMPT_UNVALIDATED: {
2933 handlePromptUnvalidated((Network) msg.obj);
2934 break;
2935 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002936 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2937 handleMobileDataAlwaysOn();
2938 break;
2939 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002940 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2941 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2942 mKeepaliveTracker.handleStartKeepalive(msg);
2943 break;
2944 }
2945 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2946 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2947 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2948 int slot = msg.arg1;
2949 int reason = msg.arg2;
2950 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2951 break;
2952 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002953 case EVENT_SYSTEM_READY: {
2954 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2955 nai.networkMonitor.systemReady = true;
2956 }
2957 break;
2958 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002959 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002960 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002961 break;
2962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 }
2964 }
2965 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002966
2967 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002968 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002969 public int tether(String iface, String callerPkg) {
2970 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002971 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002972 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002973 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002974 } else {
2975 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2976 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002977 }
2978
2979 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002980 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002981 public int untether(String iface, String callerPkg) {
2982 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002983
2984 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002985 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002986 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002987 } else {
2988 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2989 }
2990 }
2991
2992 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002993 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002994 public int getLastTetherError(String iface) {
2995 enforceTetherAccessPermission();
2996
2997 if (isTetheringSupported()) {
2998 return mTethering.getLastTetherError(iface);
2999 } else {
3000 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3001 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003002 }
3003
3004 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003005 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003006 public String[] getTetherableUsbRegexs() {
3007 enforceTetherAccessPermission();
3008 if (isTetheringSupported()) {
3009 return mTethering.getTetherableUsbRegexs();
3010 } else {
3011 return new String[0];
3012 }
3013 }
3014
Lorenzo Colitti18660282016-07-04 12:55:44 +09003015 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003016 public String[] getTetherableWifiRegexs() {
3017 enforceTetherAccessPermission();
3018 if (isTetheringSupported()) {
3019 return mTethering.getTetherableWifiRegexs();
3020 } else {
3021 return new String[0];
3022 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003023 }
3024
Lorenzo Colitti18660282016-07-04 12:55:44 +09003025 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003026 public String[] getTetherableBluetoothRegexs() {
3027 enforceTetherAccessPermission();
3028 if (isTetheringSupported()) {
3029 return mTethering.getTetherableBluetoothRegexs();
3030 } else {
3031 return new String[0];
3032 }
3033 }
3034
Lorenzo Colitti18660282016-07-04 12:55:44 +09003035 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003036 public int setUsbTethering(boolean enable, String callerPkg) {
3037 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003038 if (isTetheringSupported()) {
3039 return mTethering.setUsbTethering(enable);
3040 } else {
3041 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3042 }
3043 }
3044
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003045 // TODO - move iface listing, queries, etc to new module
3046 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003047 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003048 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003049 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003050 return mTethering.getTetherableIfaces();
3051 }
3052
Lorenzo Colitti18660282016-07-04 12:55:44 +09003053 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003054 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003055 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003056 return mTethering.getTetheredIfaces();
3057 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003058
Lorenzo Colitti18660282016-07-04 12:55:44 +09003059 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003060 public String[] getTetheringErroredIfaces() {
3061 enforceTetherAccessPermission();
3062 return mTethering.getErroredIfaces();
3063 }
3064
Lorenzo Colitti18660282016-07-04 12:55:44 +09003065 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003066 public String[] getTetheredDhcpRanges() {
3067 enforceConnectivityInternalPermission();
3068 return mTethering.getTetheredDhcpRanges();
3069 }
3070
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003071 // if ro.tether.denied = true we default to no tethering
3072 // gservices could set the secure setting to 1 though to enable it on a build where it
3073 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003074 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003075 public boolean isTetheringSupported() {
3076 enforceTetherAccessPermission();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003077 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3078 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3079 Settings.Global.TETHER_SUPPORTED, defaultVal));
3080 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003081 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003082
3083 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3084 boolean adminUser = false;
3085 final long token = Binder.clearCallingIdentity();
3086 try {
3087 adminUser = mUserManager.isAdminUser();
3088 } finally {
3089 Binder.restoreCallingIdentity(token);
3090 }
3091
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003092 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003093 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003094
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003095 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003096 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3097 String callerPkg) {
3098 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003099 if (!isTetheringSupported()) {
3100 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3101 return;
3102 }
3103 mTethering.startTethering(type, receiver, showProvisioningUi);
3104 }
3105
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003106 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003107 public void stopTethering(int type, String callerPkg) {
3108 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003109 mTethering.stopTethering(type);
3110 }
3111
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003112 // Called when we lose the default network and have no replacement yet.
3113 // This will automatically be cleared after X seconds or a new default network
3114 // becomes CONNECTED, whichever happens first. The timer is started by the
3115 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003116 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003117 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003118 if (mNetTransitionWakeLock.isHeld()) {
3119 return;
3120 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003121 mNetTransitionWakeLock.acquire();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003122 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003123 mWakelockLogs.log("ACQUIRE for " + forWhom);
3124 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3125 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003126 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003127
Hugo Benichi4c31b342017-03-30 23:18:10 +09003128 // Called when we gain a new default network to release the network transition wakelock in a
3129 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3130 // message is cancelled.
3131 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003132 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003133 if (!mNetTransitionWakeLock.isHeld()) {
3134 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003135 }
3136 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003137 // Cancel self timeout on wakelock hold.
3138 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3139 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3140 mHandler.sendMessageDelayed(msg, 1000);
3141 }
3142
3143 // Called when either message of ensureNetworkTransitionWakelock or
3144 // scheduleReleaseNetworkTransitionWakelock is processed.
3145 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3146 String event = eventName(eventId);
3147 synchronized (this) {
3148 if (!mNetTransitionWakeLock.isHeld()) {
3149 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3150 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3151 return;
3152 }
3153 mNetTransitionWakeLock.release();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003154 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003155 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003156 }
3157
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003158 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003159 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003160 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003161 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003162 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003163 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003164 }
3165
Lorenzo Colitti18660282016-07-04 12:55:44 +09003166 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003167 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003168 enforceAccessPermission();
3169 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003170 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003171 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003172 mHandler.sendMessage(
3173 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3174 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003175
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003176 private void handleReportNetworkConnectivity(
3177 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi29551722017-04-06 16:01:44 +09003178 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003179 if (network == null) {
3180 nai = getDefaultNetwork();
3181 } else {
3182 nai = getNetworkAgentInfoForNetwork(network);
3183 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003184 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3185 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3186 return;
3187 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003188 // Revalidate if the app report does not match our current validated state.
Hugo Benichi29551722017-04-06 16:01:44 +09003189 if (hasConnectivity == nai.lastValidated) {
3190 return;
3191 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003192 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003193 int netid = nai.network.netId;
3194 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003195 }
Hugo Benichi29551722017-04-06 16:01:44 +09003196 // Validating a network that has not yet connected could result in a call to
3197 // rematchNetworkAndRequests() which is not meant to work on such networks.
3198 if (!nai.everConnected) {
3199 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003200 }
Hugo Benichi29551722017-04-06 16:01:44 +09003201 LinkProperties lp = getLinkProperties(nai);
3202 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3203 return;
3204 }
3205 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003206 }
3207
Paul Jensencee9b512015-05-06 07:32:40 -04003208 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003209 // this information is already available as a world read/writable jvm property
3210 // so this API change wouldn't have a benifit. It also breaks the passing
3211 // of proxy info to all the JVMs.
3212 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003213 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003214 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003215 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3216 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003217 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003218 }
3219
Lorenzo Colitti18660282016-07-04 12:55:44 +09003220 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003221 public ProxyInfo getProxyForNetwork(Network network) {
3222 if (network == null) return getDefaultProxy();
3223 final ProxyInfo globalProxy = getGlobalProxy();
3224 if (globalProxy != null) return globalProxy;
3225 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3226 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3227 // caller may not have.
3228 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3229 if (nai == null) return null;
3230 synchronized (nai) {
3231 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3232 if (proxyInfo == null) return null;
3233 return new ProxyInfo(proxyInfo);
3234 }
3235 }
3236
Paul Jensene0bef712014-12-10 15:12:18 -05003237 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3238 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3239 // proxy is null then there is no proxy in place).
3240 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3241 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3242 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3243 proxy = null;
3244 }
3245 return proxy;
3246 }
3247
3248 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3249 // better for determining if a new proxy broadcast is necessary:
3250 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3251 // avoid unnecessary broadcasts.
3252 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3253 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3254 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3255 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3256 // all set.
3257 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3258 a = canonicalizeProxyInfo(a);
3259 b = canonicalizeProxyInfo(b);
3260 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3261 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3262 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3263 }
3264
Jason Monk207900c2014-04-25 15:00:09 -04003265 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003266 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003267
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003268 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003269 if (proxyProperties == mGlobalProxy) return;
3270 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3271 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3272
3273 String host = "";
3274 int port = 0;
3275 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003276 String pacFileUrl = "";
3277 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003278 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003279 if (!proxyProperties.isValid()) {
3280 if (DBG)
3281 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3282 return;
3283 }
Jason Monk207900c2014-04-25 15:00:09 -04003284 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003285 host = mGlobalProxy.getHost();
3286 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003287 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003288 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003289 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003290 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003291 } else {
3292 mGlobalProxy = null;
3293 }
3294 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003295 final long token = Binder.clearCallingIdentity();
3296 try {
3297 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3298 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3299 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3300 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003301 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003302 } finally {
3303 Binder.restoreCallingIdentity(token);
3304 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003305
Jason Monkcf0f97a2014-10-02 15:39:38 -04003306 if (mGlobalProxy == null) {
3307 proxyProperties = mDefaultProxy;
3308 }
3309 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003310 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003311 }
3312
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003313 private void loadGlobalProxy() {
3314 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003315 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3316 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3317 String exclList = Settings.Global.getString(res,
3318 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003319 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3320 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003321 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003322 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003323 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003324 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003325 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003326 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003327 if (!proxyProperties.isValid()) {
3328 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3329 return;
3330 }
3331
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003332 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003333 mGlobalProxy = proxyProperties;
3334 }
3335 }
3336 }
3337
Jason Monk207900c2014-04-25 15:00:09 -04003338 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003339 // this information is already available as a world read/writable jvm property
3340 // so this API change wouldn't have a benifit. It also breaks the passing
3341 // of proxy info to all the JVMs.
3342 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003343 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003344 return mGlobalProxy;
3345 }
3346 }
3347
Jason Monk207900c2014-04-25 15:00:09 -04003348 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003349 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003350 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003351 proxy = null;
3352 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003353 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003354 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003355 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003356 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003357 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3358 return;
3359 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003360
3361 // This call could be coming from the PacManager, containing the port of the local
3362 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3363 // global (to get the correct local port), and send a broadcast.
3364 // TODO: Switch PacManager to have its own message to send back rather than
3365 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003366 if ((mGlobalProxy != null) && (proxy != null)
3367 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003368 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3369 mGlobalProxy = proxy;
3370 sendProxyBroadcast(mGlobalProxy);
3371 return;
3372 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003373 mDefaultProxy = proxy;
3374
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003375 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003376 if (!mDefaultProxyDisabled) {
3377 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003378 }
3379 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003380 }
3381
Paul Jensene0bef712014-12-10 15:12:18 -05003382 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3383 // This method gets called when any network changes proxy, but the broadcast only ever contains
3384 // the default proxy (even if it hasn't changed).
3385 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3386 // world where an app might be bound to a non-default network.
3387 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3388 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3389 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3390
3391 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3392 sendProxyBroadcast(getDefaultProxy());
3393 }
3394 }
3395
Robert Greenwalt434203a2010-10-11 16:00:27 -07003396 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003397 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3398 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003399 if (!TextUtils.isEmpty(proxy)) {
3400 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003401 if (data.length == 0) {
3402 return;
3403 }
3404
Robert Greenwalt434203a2010-10-11 16:00:27 -07003405 String proxyHost = data[0];
3406 int proxyPort = 8080;
3407 if (data.length > 1) {
3408 try {
3409 proxyPort = Integer.parseInt(data[1]);
3410 } catch (NumberFormatException e) {
3411 return;
3412 }
3413 }
Jason Monk207900c2014-04-25 15:00:09 -04003414 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003415 setGlobalProxy(p);
3416 }
3417 }
3418
Jason Monk207900c2014-04-25 15:00:09 -04003419 private void sendProxyBroadcast(ProxyInfo proxy) {
3420 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003421 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003422 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003423 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003424 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3425 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003426 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003427 final long ident = Binder.clearCallingIdentity();
3428 try {
3429 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3430 } finally {
3431 Binder.restoreCallingIdentity(ident);
3432 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003433 }
3434
3435 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003436 final private HashMap<Uri, Integer> mUriEventMap;
3437 final private Context mContext;
3438 final private Handler mHandler;
3439
3440 SettingsObserver(Context context, Handler handler) {
3441 super(null);
3442 mUriEventMap = new HashMap<Uri, Integer>();
3443 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003444 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003445 }
3446
Erik Klineda4bfa82015-04-30 12:58:40 +09003447 void observe(Uri uri, int what) {
3448 mUriEventMap.put(uri, what);
3449 final ContentResolver resolver = mContext.getContentResolver();
3450 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003451 }
3452
3453 @Override
3454 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003455 Slog.wtf(TAG, "Should never be reached.");
3456 }
3457
3458 @Override
3459 public void onChange(boolean selfChange, Uri uri) {
3460 final Integer what = mUriEventMap.get(uri);
3461 if (what != null) {
3462 mHandler.obtainMessage(what.intValue()).sendToTarget();
3463 } else {
3464 loge("No matching event to send for URI=" + uri);
3465 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003466 }
3467 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003468
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003469 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003470 Slog.d(TAG, s);
3471 }
3472
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003473 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003474 Slog.e(TAG, s);
3475 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003476
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003477 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003478 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003479 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3480 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3481 *
3482 * @param oldPackage Package name of the application which currently controls VPN, which will
3483 * be replaced. If there is no such application, this should should either be
3484 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3485 * @param newPackage Package name of the application which should gain control of VPN, or
3486 * {@code null} to disable.
3487 * @param userId User for whom to prepare the new VPN.
3488 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003489 * @hide
3490 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003491 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003492 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3493 int userId) {
3494 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003495 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003496
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003497 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003498 Vpn vpn = mVpns.get(userId);
3499 if (vpn != null) {
3500 return vpn.prepare(oldPackage, newPackage);
3501 } else {
3502 return false;
3503 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003504 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003505 }
3506
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003507 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003508 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3509 * This method is used by system-privileged apps.
3510 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3511 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3512 *
3513 * @param packageName The package for which authorization state should change.
3514 * @param userId User for whom {@code packageName} is installed.
3515 * @param authorized {@code true} if this app should be able to start a VPN connection without
3516 * explicit user approval, {@code false} if not.
3517 *
Jeff Davidson05542602014-08-11 14:07:27 -07003518 * @hide
3519 */
3520 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003521 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3522 enforceCrossUserPermission(userId);
3523
Jeff Davidson05542602014-08-11 14:07:27 -07003524 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003525 Vpn vpn = mVpns.get(userId);
3526 if (vpn != null) {
3527 vpn.setPackageAuthorization(packageName, authorized);
3528 }
Jeff Davidson05542602014-08-11 14:07:27 -07003529 }
3530 }
3531
3532 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003533 * Configure a TUN interface and return its file descriptor. Parameters
3534 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003535 * and not available in ConnectivityManager. Permissions are checked in
3536 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003537 * @hide
3538 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003539 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003540 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003541 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003542 int user = UserHandle.getUserId(Binder.getCallingUid());
3543 synchronized(mVpns) {
3544 return mVpns.get(user).establish(config);
3545 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003546 }
3547
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003548 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003549 * Start legacy VPN, controlling native daemons as needed. Creates a
3550 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003551 */
3552 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003553 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003554 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003555 final LinkProperties egress = getActiveLinkProperties();
3556 if (egress == null) {
3557 throw new IllegalStateException("Missing active network connection");
3558 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003559 int user = UserHandle.getUserId(Binder.getCallingUid());
3560 synchronized(mVpns) {
3561 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3562 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003563 }
3564
3565 /**
3566 * Return the information of the ongoing legacy VPN. This method is used
3567 * by VpnSettings and not available in ConnectivityManager. Permissions
3568 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003569 */
3570 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003571 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3572 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003573
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003574 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003575 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003576 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003577 }
3578
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003579 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003580 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3581 * and not available in ConnectivityManager.
3582 */
3583 @Override
3584 public VpnInfo[] getAllVpnInfo() {
3585 enforceConnectivityInternalPermission();
3586 if (mLockdownEnabled) {
3587 return new VpnInfo[0];
3588 }
3589
3590 synchronized(mVpns) {
3591 List<VpnInfo> infoList = new ArrayList<>();
3592 for (int i = 0; i < mVpns.size(); i++) {
3593 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3594 if (info != null) {
3595 infoList.add(info);
3596 }
3597 }
3598 return infoList.toArray(new VpnInfo[infoList.size()]);
3599 }
3600 }
3601
3602 /**
3603 * @return VPN information for accounting, or null if we can't retrieve all required
3604 * information, e.g primary underlying iface.
3605 */
3606 @Nullable
3607 private VpnInfo createVpnInfo(Vpn vpn) {
3608 VpnInfo info = vpn.getVpnInfo();
3609 if (info == null) {
3610 return null;
3611 }
3612 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3613 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3614 // the underlyingNetworks list.
3615 if (underlyingNetworks == null) {
3616 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3617 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3618 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3619 }
3620 } else if (underlyingNetworks.length > 0) {
3621 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3622 if (linkProperties != null) {
3623 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3624 }
3625 }
3626 return info.primaryUnderlyingIface == null ? null : info;
3627 }
3628
3629 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003630 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3631 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003632 * Permissions are checked in Vpn class.
3633 * @hide
3634 */
3635 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003636 public VpnConfig getVpnConfig(int userId) {
3637 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003638 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003639 Vpn vpn = mVpns.get(userId);
3640 if (vpn != null) {
3641 return vpn.getVpnConfig();
3642 } else {
3643 return null;
3644 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003645 }
3646 }
3647
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003648 @Override
3649 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003650 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3651 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3652 return false;
3653 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003654
3655 // Tear down existing lockdown if profile was removed
3656 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3657 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003658 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3659 if (profileTag == null) {
3660 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3661 return false;
3662 }
3663 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003664 final VpnProfile profile = VpnProfile.decode(
3665 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003666 if (profile == null) {
3667 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3668 setLockdownTracker(null);
3669 return true;
3670 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003671 int user = UserHandle.getUserId(Binder.getCallingUid());
3672 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003673 Vpn vpn = mVpns.get(user);
3674 if (vpn == null) {
3675 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3676 return false;
3677 }
3678 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003679 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003680 } else {
3681 setLockdownTracker(null);
3682 }
3683
3684 return true;
3685 }
3686
3687 /**
3688 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3689 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3690 */
3691 private void setLockdownTracker(LockdownVpnTracker tracker) {
3692 // Shutdown any existing tracker
3693 final LockdownVpnTracker existing = mLockdownTracker;
3694 mLockdownTracker = null;
3695 if (existing != null) {
3696 existing.shutdown();
3697 }
3698
3699 try {
3700 if (tracker != null) {
3701 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003702 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003703 mLockdownTracker = tracker;
3704 mLockdownTracker.init();
3705 } else {
3706 mNetd.setFirewallEnabled(false);
3707 }
3708 } catch (RemoteException e) {
3709 // ignored; NMS lives inside system_server
3710 }
3711 }
3712
3713 private void throwIfLockdownEnabled() {
3714 if (mLockdownEnabled) {
3715 throw new IllegalStateException("Unavailable in lockdown mode");
3716 }
3717 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003718
Robin Lee244ce8e2016-01-05 18:03:46 +00003719 /**
Robin Lee17e61832016-05-09 13:46:28 +01003720 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3721 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003722 *
Robin Lee17e61832016-05-09 13:46:28 +01003723 * @return {@code true} if the service was started, the service was already connected, or there
3724 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003725 */
Robin Lee17e61832016-05-09 13:46:28 +01003726 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003727 synchronized (mVpns) {
3728 Vpn vpn = mVpns.get(userId);
3729 if (vpn == null) {
3730 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3731 // exists already.
3732 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3733 return false;
3734 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003735
Robin Lee812800c2016-05-13 15:38:08 +01003736 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003737 }
3738 }
3739
3740 @Override
Robin Leedc679712016-05-03 13:23:03 +01003741 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003742 enforceConnectivityInternalPermission();
3743 enforceCrossUserPermission(userId);
3744
3745 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3746 if (LockdownVpnTracker.isEnabled()) {
3747 return false;
3748 }
3749
Robin Lee244ce8e2016-01-05 18:03:46 +00003750 synchronized (mVpns) {
3751 Vpn vpn = mVpns.get(userId);
3752 if (vpn == null) {
3753 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3754 return false;
3755 }
Robin Lee17e61832016-05-09 13:46:28 +01003756 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003757 return false;
3758 }
Robin Lee17e61832016-05-09 13:46:28 +01003759 if (!startAlwaysOnVpn(userId)) {
3760 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003761 return false;
3762 }
3763 }
3764 return true;
3765 }
3766
3767 @Override
3768 public String getAlwaysOnVpnPackage(int userId) {
3769 enforceConnectivityInternalPermission();
3770 enforceCrossUserPermission(userId);
3771
3772 synchronized (mVpns) {
3773 Vpn vpn = mVpns.get(userId);
3774 if (vpn == null) {
3775 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3776 return null;
3777 }
3778 return vpn.getAlwaysOnPackage();
3779 }
3780 }
3781
Wink Savilleab9321d2013-06-29 21:10:57 -07003782 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003783 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003784 // TODO: Remove? Any reason to trigger a provisioning check?
3785 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003786 }
3787
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003788 /** Location to an updatable file listing carrier provisioning urls.
3789 * An example:
3790 *
3791 * <?xml version="1.0" encoding="utf-8"?>
3792 * <provisioningUrls>
3793 * <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 -07003794 * </provisioningUrls>
3795 */
3796 private static final String PROVISIONING_URL_PATH =
3797 "/data/misc/radio/provisioning_urls.xml";
3798 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003799
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003800 /** XML tag for root element. */
3801 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3802 /** XML tag for individual url */
3803 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003804 /** XML attribute for mcc */
3805 private static final String ATTR_MCC = "mcc";
3806 /** XML attribute for mnc */
3807 private static final String ATTR_MNC = "mnc";
3808
Paul Jensen434dde82015-06-11 09:43:30 -04003809 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003810 FileReader fileReader = null;
3811 XmlPullParser parser = null;
3812 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003813
3814 try {
3815 fileReader = new FileReader(mProvisioningUrlFile);
3816 parser = Xml.newPullParser();
3817 parser.setInput(fileReader);
3818 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3819
3820 while (true) {
3821 XmlUtils.nextElement(parser);
3822
3823 String element = parser.getName();
3824 if (element == null) break;
3825
Paul Jensen434dde82015-06-11 09:43:30 -04003826 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003827 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3828 try {
3829 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3830 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3831 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3832 parser.next();
3833 if (parser.getEventType() == XmlPullParser.TEXT) {
3834 return parser.getText();
3835 }
3836 }
3837 }
3838 } catch (NumberFormatException e) {
3839 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3840 }
3841 }
3842 }
3843 return null;
3844 } catch (FileNotFoundException e) {
3845 loge("Carrier Provisioning Urls file not found");
3846 } catch (XmlPullParserException e) {
3847 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3848 } catch (IOException e) {
3849 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3850 } finally {
3851 if (fileReader != null) {
3852 try {
3853 fileReader.close();
3854 } catch (IOException e) {}
3855 }
3856 }
3857 return null;
3858 }
3859
Wink Saville42d4f082013-07-20 20:31:59 -07003860 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003861 public String getMobileProvisioningUrl() {
3862 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003863 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003864 if (TextUtils.isEmpty(url)) {
3865 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003866 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003867 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003868 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003869 }
Wink Saville8cf35602013-07-10 23:00:07 -07003870 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003871 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003872 String phoneNumber = mTelephonyManager.getLine1Number();
3873 if (TextUtils.isEmpty(phoneNumber)) {
3874 phoneNumber = "0000000000";
3875 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003876 url = String.format(url,
3877 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3878 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003879 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003880 }
3881
Wink Savilleab9321d2013-06-29 21:10:57 -07003882 return url;
3883 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003884
Wink Saville948282b2013-08-29 08:55:16 -07003885 @Override
3886 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003887 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003888 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003889 final long ident = Binder.clearCallingIdentity();
3890 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003891 // Concatenate the range of types onto the range of NetIDs.
3892 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3893 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003894 } finally {
3895 Binder.restoreCallingIdentity(ident);
3896 }
Wink Saville948282b2013-08-29 08:55:16 -07003897 }
Wink Saville7788c612013-08-29 14:57:08 -07003898
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003899 @Override
3900 public void setAirplaneMode(boolean enable) {
3901 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003902 final long ident = Binder.clearCallingIdentity();
3903 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003904 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003905 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003906 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3907 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003908 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003909 } finally {
3910 Binder.restoreCallingIdentity(ident);
3911 }
3912 }
3913
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003914 private void onUserStart(int userId) {
3915 synchronized(mVpns) {
3916 Vpn userVpn = mVpns.get(userId);
3917 if (userVpn != null) {
3918 loge("Starting user already has a VPN");
3919 return;
3920 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003921 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003922 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003923 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003924 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3925 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003926 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003927 }
3928
3929 private void onUserStop(int userId) {
3930 synchronized(mVpns) {
3931 Vpn userVpn = mVpns.get(userId);
3932 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003933 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003934 return;
3935 }
Robin Lee17e61832016-05-09 13:46:28 +01003936 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003937 mVpns.delete(userId);
3938 }
3939 }
3940
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003941 private void onUserAdded(int userId) {
3942 synchronized(mVpns) {
3943 final int vpnsSize = mVpns.size();
3944 for (int i = 0; i < vpnsSize; i++) {
3945 Vpn vpn = mVpns.valueAt(i);
3946 vpn.onUserAdded(userId);
3947 }
3948 }
3949 }
3950
3951 private void onUserRemoved(int userId) {
3952 synchronized(mVpns) {
3953 final int vpnsSize = mVpns.size();
3954 for (int i = 0; i < vpnsSize; i++) {
3955 Vpn vpn = mVpns.valueAt(i);
3956 vpn.onUserRemoved(userId);
3957 }
3958 }
3959 }
3960
Robin Lee89e7a692016-02-29 14:38:17 +00003961 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003962 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3963 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3964 updateLockdownVpn();
3965 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003966 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003967 }
3968 }
3969
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003970 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3971 @Override
3972 public void onReceive(Context context, Intent intent) {
3973 final String action = intent.getAction();
3974 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3975 if (userId == UserHandle.USER_NULL) return;
3976
Robin Lee323f29d2016-05-04 16:38:06 +01003977 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003978 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003979 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003980 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003981 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3982 onUserAdded(userId);
3983 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3984 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003985 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3986 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003987 }
3988 }
3989 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003990
Robin Lee95204e02017-01-27 11:59:22 +00003991 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3992 @Override
3993 public void onReceive(Context context, Intent intent) {
3994 // Try creating lockdown tracker, since user present usually means
3995 // unlocked keystore.
3996 updateLockdownVpn();
3997 mContext.unregisterReceiver(this);
3998 }
3999 };
4000
Robert Greenwalta67be032014-05-16 15:49:14 -07004001 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4002 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004003 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4004 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004005
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004006 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4007 // Map from UID to number of NetworkRequests that UID has filed.
4008 @GuardedBy("mUidToNetworkRequestCount")
4009 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4010
Robert Greenwalta67be032014-05-16 15:49:14 -07004011 private static class NetworkFactoryInfo {
4012 public final String name;
4013 public final Messenger messenger;
4014 public final AsyncChannel asyncChannel;
4015
4016 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4017 this.name = name;
4018 this.messenger = messenger;
4019 this.asyncChannel = asyncChannel;
4020 }
4021 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004022
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004023 private void ensureNetworkRequestHasType(NetworkRequest request) {
4024 if (request.type == NetworkRequest.Type.NONE) {
4025 throw new IllegalArgumentException(
4026 "All NetworkRequests in ConnectivityService must have a type");
4027 }
4028 }
4029
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004030 /**
4031 * Tracks info about the requester.
4032 * Also used to notice when the calling process dies so we can self-expire
4033 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004034 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004035 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004036 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004037 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004038 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004039 final int mPid;
4040 final int mUid;
4041 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004042
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004043 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004044 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004045 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004046 mPendingIntent = pi;
4047 messenger = null;
4048 mBinder = null;
4049 mPid = getCallingPid();
4050 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004051 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004052 }
4053
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004054 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004055 super();
4056 messenger = m;
4057 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004058 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004059 mBinder = binder;
4060 mPid = getCallingPid();
4061 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004062 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004063 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004064
4065 try {
4066 mBinder.linkToDeath(this, 0);
4067 } catch (RemoteException e) {
4068 binderDied();
4069 }
4070 }
4071
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004072 private void enforceRequestCountLimit() {
4073 synchronized (mUidToNetworkRequestCount) {
4074 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4075 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4076 throw new IllegalArgumentException("Too many NetworkRequests filed");
4077 }
4078 mUidToNetworkRequestCount.put(mUid, networkRequests);
4079 }
4080 }
4081
Robert Greenwalt9258c642014-03-26 16:47:06 -07004082 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004083 if (mBinder != null) {
4084 mBinder.unlinkToDeath(this, 0);
4085 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004086 }
4087
4088 public void binderDied() {
4089 log("ConnectivityService NetworkRequestInfo binderDied(" +
4090 request + ", " + mBinder + ")");
4091 releaseNetworkRequest(request);
4092 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004093
4094 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004095 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004096 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004097 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004098 }
4099
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004100 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4101 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4102 if (badCapability != null) {
4103 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004104 }
4105 }
4106
Erik Kline9d598e12015-07-13 16:37:51 +09004107 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004108 final SortedSet<Integer> thresholds = new TreeSet();
4109 synchronized (nai) {
4110 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4111 if (nri.request.networkCapabilities.hasSignalStrength() &&
4112 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4113 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4114 }
4115 }
4116 }
Erik Kline9d598e12015-07-13 16:37:51 +09004117 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004118 }
4119
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004120 private void updateSignalStrengthThresholds(
4121 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4122 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004123 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004124 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4125
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004126 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004127 String detail;
4128 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4129 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4130 } else {
4131 detail = reason;
4132 }
4133 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4134 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4135 }
4136
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004137 nai.asyncChannel.sendMessage(
4138 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004139 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004140 }
4141
Robert Greenwalt9258c642014-03-26 16:47:06 -07004142 @Override
4143 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004144 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004145 final NetworkRequest.Type type = (networkCapabilities == null)
4146 ? NetworkRequest.Type.TRACK_DEFAULT
4147 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004148 // If the requested networkCapabilities is null, take them instead from
4149 // the default network request. This allows callers to keep track of
4150 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004151 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004152 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4153 enforceAccessPermission();
4154 } else {
4155 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4156 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004157 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4158 // of the app when the request is filed, but we never change the request if the app
4159 // changes network state. http://b/29964605
4160 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004161 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004162 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004163
Etan Cohenba07c8c2017-02-05 10:42:27 -08004164 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004165 throw new IllegalArgumentException("Bad timeout specified");
4166 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004167
Etan Cohena7434272017-04-03 12:17:51 -07004168 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4169 networkCapabilities.getNetworkSpecifier());
Etan Cohenddb9ef02015-11-18 10:56:15 -08004170
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004171 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004172 nextNetworkRequestId(), type);
4173 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004174 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004175
4176 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004177 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004178 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004179 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004180 }
4181 return networkRequest;
4182 }
4183
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004184 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004185 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004186 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004187 } else {
4188 enforceChangePermission();
4189 }
4190 }
4191
fenglub15e72b2015-03-20 11:29:56 -07004192 @Override
fengludb571472015-04-21 17:12:05 -07004193 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004194 enforceAccessPermission();
4195 NetworkAgentInfo nai = null;
4196 if (network == null) {
4197 return false;
4198 }
4199 synchronized (mNetworkForNetId) {
4200 nai = mNetworkForNetId.get(network.netId);
4201 }
4202 if (nai != null) {
4203 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4204 return true;
4205 }
4206 return false;
4207 }
4208
Felipe Lemeee27cab2016-06-20 16:36:29 -07004209 private boolean isSystem(int uid) {
4210 return uid < Process.FIRST_APPLICATION_UID;
4211 }
fenglub15e72b2015-03-20 11:29:56 -07004212
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004213 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004214 final int uid = Binder.getCallingUid();
4215 if (isSystem(uid)) {
4216 return;
4217 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004218 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004219 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004220 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004221 synchronized(mRulesLock) {
4222 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4223 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004224 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4225 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004226 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004227 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004228 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004229 }
4230 }
4231 }
4232
Robert Greenwalt9258c642014-03-26 16:47:06 -07004233 @Override
4234 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4235 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004236 checkNotNull(operation, "PendingIntent cannot be null.");
4237 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4238 enforceNetworkRequestPermissions(networkCapabilities);
4239 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004240 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004241
Etan Cohena7434272017-04-03 12:17:51 -07004242 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4243 networkCapabilities.getNetworkSpecifier());
4244
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004245 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004246 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4247 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004248 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004249 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4250 nri));
4251 return networkRequest;
4252 }
4253
Jeremy Joslin79294842014-12-03 17:15:28 -08004254 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4255 mHandler.sendMessageDelayed(
4256 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4257 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4258 }
4259
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004260 @Override
4261 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004262 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004263 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4264 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004265 }
4266
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004267 // In order to implement the compatibility measure for pre-M apps that call
4268 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4269 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4270 // This ensures it has permission to do so.
4271 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4272 if (nc == null) {
4273 return false;
4274 }
4275 int[] transportTypes = nc.getTransportTypes();
4276 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4277 return false;
4278 }
4279 try {
4280 mContext.enforceCallingOrSelfPermission(
4281 android.Manifest.permission.ACCESS_WIFI_STATE,
4282 "ConnectivityService");
4283 } catch (SecurityException e) {
4284 return false;
4285 }
4286 return true;
4287 }
4288
Robert Greenwalt9258c642014-03-26 16:47:06 -07004289 @Override
4290 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4291 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004292 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4293 enforceAccessPermission();
4294 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004295
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004296 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4297 if (!ConnectivityManager.checkChangePermission(mContext)) {
4298 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4299 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4300 // onLost and onAvailable callbacks when networks move in and out of the background.
4301 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4302 // can't request networks.
4303 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4304 }
4305
Etan Cohena7434272017-04-03 12:17:51 -07004306 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4307 networkCapabilities.getNetworkSpecifier());
4308
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004309 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004310 NetworkRequest.Type.LISTEN);
4311 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004312 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004313
4314 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4315 return networkRequest;
4316 }
4317
4318 @Override
4319 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4320 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004321 checkNotNull(operation, "PendingIntent cannot be null.");
4322 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4323 enforceAccessPermission();
4324 }
4325
Etan Cohena7434272017-04-03 12:17:51 -07004326 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4327 networkCapabilities.getNetworkSpecifier());
4328
Erik Kline7523eb32015-07-09 18:24:03 +09004329 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004330 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4331 NetworkRequest.Type.LISTEN);
4332 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004333 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004334
4335 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004336 }
4337
Erik Klineacdd6392016-07-07 16:50:58 +09004338 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004339 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004340 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004341 mHandler.sendMessage(mHandler.obtainMessage(
4342 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004343 }
4344
4345 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004346 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004347 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004348 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4349 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004350 }
4351
Robert Greenwalta67be032014-05-16 15:49:14 -07004352 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004353 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004354 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4355 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4356 }
4357
4358 @Override
4359 public void unregisterNetworkFactory(Messenger messenger) {
4360 enforceConnectivityInternalPermission();
4361 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4362 }
4363
4364 private void handleUnregisterNetworkFactory(Messenger messenger) {
4365 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4366 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004367 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004368 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004369 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004370 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004371 }
4372
Robert Greenwalt7b816022014-04-18 15:25:25 -07004373 /**
4374 * NetworkAgentInfo supporting a request by requestId.
4375 * These have already been vetted (their Capabilities satisfy the request)
4376 * and the are the highest scored network available.
4377 * the are keyed off the Requests requestId.
4378 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004379 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004380 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4381 new SparseArray<NetworkAgentInfo>();
4382
Paul Jensen31a94f42015-02-13 14:18:39 -05004383 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4384 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004385 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4386 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004387 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4388 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4389 // there may not be a strict 1:1 correlation between the two.
4390 @GuardedBy("mNetworkForNetId")
4391 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004392
Robert Greenwalt7b816022014-04-18 15:25:25 -07004393 // NetworkAgentInfo keyed off its connecting messenger
4394 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004395 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004396 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4397 new HashMap<Messenger, NetworkAgentInfo>();
4398
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004399 @GuardedBy("mBlockedAppUids")
4400 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4401
Paul Jensen2c311d62014-11-17 12:34:51 -05004402 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004403 private final NetworkRequest mDefaultRequest;
4404
Erik Klineda4bfa82015-04-30 12:58:40 +09004405 // Request used to optionally keep mobile data active even when higher
4406 // priority networks like Wi-Fi are active.
4407 private final NetworkRequest mDefaultMobileDataRequest;
4408
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004409 private NetworkAgentInfo getDefaultNetwork() {
4410 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4411 }
4412
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004413 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004414 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004415 }
4416
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004417 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4418 return nri.request.requestId == mDefaultRequest.requestId;
4419 }
4420
Paul Jensen31a94f42015-02-13 14:18:39 -05004421 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004422 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004423 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004424 enforceConnectivityInternalPermission();
4425
Paul Jensen2c311d62014-11-17 12:34:51 -05004426 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4427 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004428 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004429 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4430 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004431 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004432 synchronized (this) {
4433 nai.networkMonitor.systemReady = mSystemReady;
4434 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004435 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4436 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004437 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004438 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004439 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004440 }
4441
4442 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4443 if (VDBG) log("Got NetworkAgent Messenger");
4444 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004445 synchronized (mNetworkForNetId) {
4446 mNetworkForNetId.put(na.network.netId, na);
4447 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004448 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4449 NetworkInfo networkInfo = na.networkInfo;
4450 na.networkInfo = null;
4451 updateNetworkInfo(na, networkInfo);
4452 }
4453
4454 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4455 LinkProperties newLp = networkAgent.linkProperties;
4456 int netId = networkAgent.network.netId;
4457
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004458 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4459 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004460 if (networkAgent.clatd != null) {
4461 networkAgent.clatd.fixupLinkProperties(oldLp);
4462 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004463
Paul Jensen992f2522014-04-28 10:33:11 -04004464 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004465 updateMtu(newLp, oldLp);
4466 // TODO - figure out what to do for clat
4467// for (LinkProperties lp : newLp.getStackedLinks()) {
4468// updateMtu(lp, null);
4469// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004470 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004471
Erik Kline94887872016-04-05 13:30:49 +09004472 updateRoutes(newLp, oldLp, netId);
4473 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004474
Paul Jensen3b759822014-05-13 11:44:01 -04004475 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004476 if (isDefaultNetwork(networkAgent)) {
4477 handleApplyDefaultProxy(newLp.getHttpProxy());
4478 } else {
4479 updateProxy(newLp, oldLp, networkAgent);
4480 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004481 // TODO - move this check to cover the whole function
4482 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004483 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004484 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4485 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004486
4487 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004488 }
4489
Lorenzo Colitti95439462014-10-09 13:44:48 +09004490 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4491 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4492 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004493
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004494 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004495 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4496 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004497 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004498 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004499 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004500 }
Paul Jensen992f2522014-04-28 10:33:11 -04004501
4502 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4503 CompareResult<String> interfaceDiff = new CompareResult<String>();
4504 if (oldLp != null) {
4505 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4506 } else if (newLp != null) {
4507 interfaceDiff.added = newLp.getAllInterfaceNames();
4508 }
4509 for (String iface : interfaceDiff.added) {
4510 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004511 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004512 mNetd.addInterfaceToNetwork(iface, netId);
4513 } catch (Exception e) {
4514 loge("Exception adding interface: " + e);
4515 }
4516 }
4517 for (String iface : interfaceDiff.removed) {
4518 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004519 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004520 mNetd.removeInterfaceFromNetwork(iface, netId);
4521 } catch (Exception e) {
4522 loge("Exception removing interface: " + e);
4523 }
4524 }
4525 }
4526
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004527 /**
4528 * Have netd update routes from oldLp to newLp.
4529 * @return true if routes changed between oldLp and newLp
4530 */
4531 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4533 if (oldLp != null) {
4534 routeDiff = oldLp.compareAllRoutes(newLp);
4535 } else if (newLp != null) {
4536 routeDiff.added = newLp.getAllRoutes();
4537 }
4538
4539 // add routes before removing old in case it helps with continuous connectivity
4540
4541 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4542 for (RouteInfo route : routeDiff.added) {
4543 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004544 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004545 try {
4546 mNetd.addRoute(netId, route);
4547 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004548 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4549 loge("Exception in addRoute for non-gateway: " + e);
4550 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004551 }
4552 }
4553 for (RouteInfo route : routeDiff.added) {
4554 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004555 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004556 try {
4557 mNetd.addRoute(netId, route);
4558 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004559 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4560 loge("Exception in addRoute for gateway: " + e);
4561 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004562 }
4563 }
4564
4565 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004566 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004567 try {
4568 mNetd.removeRoute(netId, route);
4569 } catch (Exception e) {
4570 loge("Exception in removeRoute: " + e);
4571 }
4572 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004573 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004574 }
Erik Kline41368502015-06-17 13:19:54 +09004575
Erik Kline94887872016-04-05 13:30:49 +09004576 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4577 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4578 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004579 }
Erik Kline94887872016-04-05 13:30:49 +09004580
4581 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004582 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004583 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004584 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004585 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4586 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004587 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004588 }
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004589 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4590 if (defaultNai != null && defaultNai.network.netId == netId) {
4591 setDefaultDnsSystemProperties(dnses);
4592 }
Erik Kline94887872016-04-05 13:30:49 +09004593 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004594 }
4595
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004596 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4597 int last = 0;
4598 for (InetAddress dns : dnses) {
4599 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004600 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004601 }
4602 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004603 setNetDnsProperty(i, "");
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004604 }
4605 mNumDnsEntries = last;
4606 }
4607
Erik Kline4edba012017-04-07 15:29:29 +09004608 private void setNetDnsProperty(int which, String value) {
4609 final String key = "net.dns" + which;
4610 // Log and forget errors setting unsupported properties.
4611 try {
4612 mSystemProperties.set(key, value);
4613 } catch (Exception e) {
4614 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4615 }
4616 }
4617
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004618 private String getNetworkPermission(NetworkCapabilities nc) {
4619 // TODO: make these permission strings AIDL constants instead.
4620 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4621 return NetworkManagementService.PERMISSION_SYSTEM;
4622 }
4623 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4624 return NetworkManagementService.PERMISSION_NETWORK;
4625 }
4626 return null;
4627 }
4628
Paul Jensen3d194ea2015-06-16 14:27:36 -04004629 /**
4630 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4631 * augmented with any stateful capabilities implied from {@code networkAgent}
4632 * (e.g., validated status and captive portal status).
4633 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004634 * @param oldScore score of the network before any of the changes that prompted us
4635 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004636 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004637 * @param networkCapabilities the new network capabilities.
4638 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004639 private void updateCapabilities(
4640 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004641 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4642 networkCapabilities)) {
4643 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4644 + nai.networkCapabilities + " -> " + networkCapabilities);
4645 }
4646
Paul Jensen3d194ea2015-06-16 14:27:36 -04004647 // Don't modify caller's NetworkCapabilities.
4648 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004649 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004650 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4651 } else {
4652 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4653 }
Paul Jensene0988542015-06-25 15:30:08 -04004654 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004655 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4656 } else {
4657 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4658 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004659 if (nai.isBackgroundNetwork()) {
4660 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4661 } else {
4662 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4663 }
4664
4665 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4666
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004667 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4668 final String newPermission = getNetworkPermission(networkCapabilities);
4669 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004670 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004671 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004672 } catch (RemoteException e) {
4673 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004674 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004675 }
4676
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004677 final NetworkCapabilities prevNc = nai.networkCapabilities;
4678 synchronized (nai) {
4679 nai.networkCapabilities = networkCapabilities;
4680 }
4681 if (nai.getCurrentScore() == oldScore &&
4682 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4683 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4684 // the change we're processing can't affect any requests, it can only affect the listens
4685 // on this network. We might have been called by rematchNetworkAndRequests when a
4686 // network changed foreground state.
4687 processListenRequests(nai, true);
4688 } else {
4689 // If the requestable capabilities have changed or the score changed, we can't have been
4690 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004691 rematchAllNetworksAndRequests(nai, oldScore);
4692 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004693 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004694 }
4695
Paul Jensenc8b9a742014-09-30 15:37:41 -04004696 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004697 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4698 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004699 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004700 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004701 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4702 }
4703 }
4704
Robert Greenwalt7b816022014-04-18 15:25:25 -07004705 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4706 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004707 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004708 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4709 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004710 }
4711 }
4712
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004713 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4714 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004715 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004716 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004717 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4718 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004719 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004720 sendIntent(nri.mPendingIntent, intent);
4721 }
4722 // else not handled
4723 }
4724
4725 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4726 mPendingIntentWakeLock.acquire();
4727 try {
4728 if (DBG) log("Sending " + pendingIntent);
4729 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4730 } catch (PendingIntent.CanceledException e) {
4731 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4732 mPendingIntentWakeLock.release();
4733 releasePendingNetworkRequest(pendingIntent);
4734 }
4735 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4736 }
4737
4738 @Override
4739 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4740 String resultData, Bundle resultExtras) {
4741 if (DBG) log("Finished sending " + pendingIntent);
4742 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004743 // Release with a delay so the receiving client has an opportunity to put in its
4744 // own request.
4745 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004746 }
4747
Hugo Benichidba33db2017-03-23 22:40:44 +09004748 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004749 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004750 if (nri.messenger == null) {
4751 return; // Default request has no msgr
4752 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004753 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004754 // TODO: check if defensive copies of data is needed.
4755 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004756 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004757 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4758 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004759 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004760 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004761 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004762 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004763 break;
4764 }
4765 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004766 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004767 break;
4768 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004769 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004770 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004771 break;
4772 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004773 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004774 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004775 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004776 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004777 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004778 String notification = ConnectivityManager.getCallbackName(notificationType);
4779 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004780 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004781 nri.messenger.send(msg);
4782 } catch (RemoteException e) {
4783 // may occur naturally in the race of binder death.
4784 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4785 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004786 }
4787
Hugo Benichidba33db2017-03-23 22:40:44 +09004788 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4789 bundle.putParcelable(t.getClass().getSimpleName(), t);
4790 }
4791
Paul Jensenc8b9a742014-09-30 15:37:41 -04004792 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004793 if (nai.numRequestNetworkRequests() != 0) {
4794 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4795 NetworkRequest nr = nai.requestAt(i);
4796 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004797 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004798 loge("Dead network still had at least " + nr);
4799 break;
4800 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004801 }
4802 nai.asyncChannel.disconnect();
4803 }
4804
Robert Greenwalt7b816022014-04-18 15:25:25 -07004805 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4806 if (oldNetwork == null) {
4807 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4808 return;
4809 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004810 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004811
4812 // If we get here it means that the last linger timeout for this network expired. So there
4813 // must be no other active linger timers, and we must stop lingering.
4814 oldNetwork.clearLingerState();
4815
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004816 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004817 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004818 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004819 } else {
4820 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004821 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4822 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004823 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004824 }
4825
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004826 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004827 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004828 setupDataActivityTracking(newNetwork);
4829 try {
4830 mNetd.setDefaultNetId(newNetwork.network.netId);
4831 } catch (Exception e) {
4832 loge("Exception setting default network :" + e);
4833 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004834 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004835 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004836 updateTcpBufferSizes(newNetwork);
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004837 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004838 }
4839
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004840 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004841 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4842 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4843 NetworkRequest nr = nri.request;
4844 if (!nr.isListen()) continue;
4845 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4846 nai.removeRequest(nri.request.requestId);
4847 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4848 }
4849 }
4850
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004851 if (capabilitiesChanged) {
4852 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4853 }
4854
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004855 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4856 NetworkRequest nr = nri.request;
4857 if (!nr.isListen()) continue;
4858 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4859 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004860 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004861 }
4862 }
4863 }
4864
Paul Jensen2161a8e2014-09-11 11:00:39 -04004865 // Handles a network appearing or improving its score.
4866 //
4867 // - Evaluates all current NetworkRequests that can be
4868 // satisfied by newNetwork, and reassigns to newNetwork
4869 // any such requests for which newNetwork is the best.
4870 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004871 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004872 // needed. A network is needed if it is the best network for
4873 // one or more NetworkRequests, or if it is a VPN.
4874 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004875 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004876 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004877 //
4878 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4879 // networks that have no chance (i.e. even if validated)
4880 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004881 //
4882 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4883 // it does not remove NetworkRequests that other Networks could better satisfy.
4884 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4885 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4886 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004887 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004888 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004889 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4890 // performed to tear down unvalidated networks that have no chance (i.e. even if
4891 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004892 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004893 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004894 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004895 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004896 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004897 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004898
4899 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4900 final int score = newNetwork.getCurrentScore();
4901
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004902 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004903
Paul Jensen2161a8e2014-09-11 11:00:39 -04004904 // Find and migrate to this Network any NetworkRequests for
4905 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004906 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004907 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004908 NetworkCapabilities nc = newNetwork.networkCapabilities;
4909 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004910 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004911 // Process requests in the first pass and listens in the second pass. This allows us to
4912 // change a network's capabilities depending on which requests it has. This is only
4913 // correct if the change in capabilities doesn't affect whether the network satisfies
4914 // requests or not, and doesn't affect the network's score.
4915 if (nri.request.isListen()) continue;
4916
Paul Jensencf4c2c62015-07-01 14:16:32 -04004917 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4918 final boolean satisfies = newNetwork.satisfies(nri.request);
4919 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004920 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004921 log("Network " + newNetwork.name() + " was already satisfying" +
4922 " request " + nri.request.requestId + ". No change.");
4923 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004924 keep = true;
4925 continue;
4926 }
4927
4928 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004929 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004930 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004931 // next check if it's better than any current network we're using for
4932 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004933 if (VDBG) {
4934 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004935 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004936 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004937 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004938 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004939 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004940 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004941 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004942 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004943 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004944 affectedNetworks.add(currentNetwork);
4945 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004946 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004947 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004948 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004949 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004950 if (!newNetwork.addRequest(nri.request)) {
4951 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4952 }
4953 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004954 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004955 // Tell NetworkFactories about the new score, so they can stop
4956 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004957 // TODO - this could get expensive if we have alot of requests for this
4958 // network. Think about if there is a way to reduce this. Push
4959 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004960 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004961 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004962 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004963 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004964 if (currentNetwork != null) {
4965 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4966 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004967 }
4968 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004969 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004970 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4971 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004972 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004973 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4974 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4975 // This means this code doesn't have to handle the case where "currentNetwork" no
4976 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4977 if (DBG) {
4978 log("Network " + newNetwork.name() + " stopped satisfying" +
4979 " request " + nri.request.requestId);
4980 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004981 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004982 if (currentNetwork == newNetwork) {
4983 mNetworkForRequestId.remove(nri.request.requestId);
4984 sendUpdatedScoreToFactories(nri.request, 0);
4985 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004986 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4987 newNetwork.name() +
4988 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004989 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004990 // TODO: Technically, sending CALLBACK_LOST here is
4991 // incorrect if there is a replacement network currently
4992 // connected that can satisfy nri, which is a request
4993 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004994 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4995 // so this code is only incorrect for a network that loses
4996 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004997 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004998 }
4999 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005000 if (isNewDefault) {
5001 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005002 makeDefault(newNetwork);
5003 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
5004 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005005 // Have a new default network, release the transition wakelock in
5006 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005007 }
5008
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005009 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5010 Slog.wtf(TAG, String.format(
5011 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
5012 nc, newNetwork.networkCapabilities));
5013 }
5014 if (newNetwork.getCurrentScore() != score) {
5015 Slog.wtf(TAG, String.format(
5016 "BUG: %s changed score during rematch: %d -> %d",
5017 score, newNetwork.getCurrentScore()));
5018 }
5019
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005020 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005021 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5022 // If the network went from background to foreground or vice versa, we need to update
5023 // its foreground state. It is safe to do this after rematching the requests because
5024 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5025 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005026 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005027 } else {
5028 processListenRequests(newNetwork, false);
5029 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005030
Paul Jensencf4c2c62015-07-01 14:16:32 -04005031 // do this after the default net is switched, but
5032 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005033 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005034
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005035 // Linger any networks that are no longer needed. This should be done after sending the
5036 // available callback for newNetwork.
5037 for (NetworkAgentInfo nai : affectedNetworks) {
5038 updateLingerState(nai, now);
5039 }
5040 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5041 // does not need to be done in any particular order.
5042 updateLingerState(newNetwork, now);
5043
Paul Jensencf4c2c62015-07-01 14:16:32 -04005044 if (isNewDefault) {
5045 // Maintain the illusion: since the legacy API only
5046 // understands one network at a time, we must pretend
5047 // that the current default network disconnected before
5048 // the new one connected.
5049 if (oldDefaultNetwork != null) {
5050 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5051 oldDefaultNetwork, true);
5052 }
5053 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5054 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5055 notifyLockdownVpn(newNetwork);
5056 }
5057
Robert Greenwalt7b816022014-04-18 15:25:25 -07005058 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005059 // Notify battery stats service about this network, both the normal
5060 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005061 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005062 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005063 final IBatteryStats bs = BatteryStatsService.getService();
5064 final int type = newNetwork.networkInfo.getType();
5065
5066 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5067 bs.noteNetworkInterfaceType(baseIface, type);
5068 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5069 final String stackedIface = stacked.getInterfaceName();
5070 bs.noteNetworkInterfaceType(stackedIface, type);
5071 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5072 }
5073 } catch (RemoteException ignored) {
5074 }
5075
Robert Greenwalt152ed372014-12-17 17:19:53 -08005076 // This has to happen after the notifyNetworkCallbacks as that tickles each
5077 // ConnectivityManager instance so that legacy requests correctly bind dns
5078 // requests to this network. The legacy users are listening for this bcast
5079 // and will generally do a dns request so they can ensureRouteToHost and if
5080 // they do that before the callbacks happen they'll use the default network.
5081 //
5082 // TODO: Is there still a race here? We send the broadcast
5083 // after sending the callback, but if the app can receive the
5084 // broadcast before the callback, it might still break.
5085 //
5086 // This *does* introduce a race where if the user uses the new api
5087 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5088 // they may get old info. Reverse this after the old startUsing api is removed.
5089 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005090 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5091 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005092 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005093 // legacy type tracker filters out repeat adds
5094 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5095 }
5096 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005097
5098 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5099 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5100 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5101 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5102 if (newNetwork.isVPN()) {
5103 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5104 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005105 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005106 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5107 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005108 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005109 if (nai.getLingerExpiry() > 0) {
5110 // This network has active linger timers and no requests, but is not
5111 // lingering. Linger it.
5112 //
5113 // One way (the only way?) this can happen if this network is unvalidated
5114 // and became unneeded due to another network improving its score to the
5115 // point where this network will no longer be able to satisfy any requests
5116 // even if it validates.
5117 updateLingerState(nai, now);
5118 } else {
5119 if (DBG) log("Reaping " + nai.name());
5120 teardownUnneededNetwork(nai);
5121 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005122 }
5123 }
5124 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005125 }
5126
Paul Jensen1c7ba022015-06-16 14:27:36 -04005127 /**
5128 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5129 * being disconnected.
5130 * @param changed If only one Network's score or capabilities have been modified since the last
5131 * time this function was called, pass this Network in this argument, otherwise pass
5132 * null.
5133 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5134 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5135 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5136 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5137 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005138 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005139 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005140 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5141 // to avoid the slowness. It is not simply enough to process just "changed", for
5142 // example in the case where "changed"'s score decreases and another network should begin
5143 // satifying a NetworkRequest that "changed" currently satisfies.
5144
5145 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5146 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5147 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005148 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005149 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005150 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005151 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005152 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5153 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5154 // Rematch higher scoring networks first to prevent requests first matching a lower
5155 // scoring network and then a higher scoring network, which could produce multiple
5156 // callbacks and inadvertently unlinger networks.
5157 Arrays.sort(nais);
5158 for (NetworkAgentInfo nai : nais) {
5159 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005160 // Only reap the last time through the loop. Reaping before all rematching
5161 // is complete could incorrectly teardown a network that hasn't yet been
5162 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005163 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005164 : ReapUnvalidatedNetworks.REAP,
5165 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005166 }
5167 }
5168 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005169
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005170 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005171 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005172 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005173 // For now only update icons for default connection.
5174 // TODO: Update WiFi and cellular icons separately. b/17237507
5175 if (!isDefaultNetwork(nai)) return;
5176
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005177 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005178 // Don't repeat publish.
5179 if (newInetCondition == mDefaultInetConditionPublished) return;
5180
5181 mDefaultInetConditionPublished = newInetCondition;
5182 sendInetConditionBroadcast(nai.networkInfo);
5183 }
5184
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005185 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5186 if (mLockdownTracker != null) {
5187 if (nai != null && nai.isVPN()) {
5188 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5189 } else {
5190 mLockdownTracker.onNetworkInfoChanged();
5191 }
5192 }
5193 }
5194
Robert Greenwalt7b816022014-04-18 15:25:25 -07005195 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005196 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005197 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005198 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005199 synchronized (networkAgent) {
5200 oldInfo = networkAgent.networkInfo;
5201 networkAgent.networkInfo = newInfo;
5202 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005203 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005204
5205 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005206 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5207 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5208 notifyIfacesChangedForNetworkStats();
5209 } else if (VDBG) log("ignoring duplicate network state non-change");
5210 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005211 return;
5212 }
5213 if (DBG) {
5214 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5215 (oldInfo == null ? "null" : oldInfo.getState()) +
5216 " to " + state);
5217 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005218
Robin Lee585e2482016-05-01 23:00:00 +01005219 if (!networkAgent.created
5220 && (state == NetworkInfo.State.CONNECTED
5221 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005222
5223 // A network that has just connected has zero requests and is thus a foreground network.
5224 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5225
Robert Greenwalt7b816022014-04-18 15:25:25 -07005226 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005227 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005228 if (networkAgent.isVPN()) {
5229 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005230 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5231 (networkAgent.networkMisc == null ||
5232 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005233 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005234 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005235 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005236 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005237 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005238 loge("Error creating network " + networkAgent.network.netId + ": "
5239 + e.getMessage());
5240 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005241 }
Paul Jenseneec75412014-08-04 12:21:19 -04005242 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005243 }
5244
5245 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5246 networkAgent.everConnected = true;
5247
Robert Greenwalt7b816022014-04-18 15:25:25 -07005248 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005249 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005250
Paul Jensenca8f16a2014-05-09 12:47:55 -04005251 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005252 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005253
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005254 if (networkAgent.isVPN()) {
5255 // Temporarily disable the default proxy (not global).
5256 synchronized (mProxyLock) {
5257 if (!mDefaultProxyDisabled) {
5258 mDefaultProxyDisabled = true;
5259 if (mGlobalProxy == null && mDefaultProxy != null) {
5260 sendProxyBroadcast(null);
5261 }
5262 }
5263 }
5264 // TODO: support proxy per network.
5265 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005266
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005267 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5268 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5269 // capabilities, so it only needs to be done once on initial connect, not every time the
5270 // network's capabilities change. Note that we do this before rematching the network,
5271 // so we could decide to tear it down immediately afterwards. That's fine though - on
5272 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5273 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005274 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005275
Paul Jensen2161a8e2014-09-11 11:00:39 -04005276 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005277 final long now = SystemClock.elapsedRealtime();
5278 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005279
5280 // This has to happen after matching the requests, because callbacks are just requests.
5281 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005282 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005283 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005284 if (networkAgent.isVPN()) {
5285 synchronized (mProxyLock) {
5286 if (mDefaultProxyDisabled) {
5287 mDefaultProxyDisabled = false;
5288 if (mGlobalProxy == null && mDefaultProxy != null) {
5289 sendProxyBroadcast(mDefaultProxy);
5290 }
5291 }
5292 }
5293 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005294 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5295 state == NetworkInfo.State.SUSPENDED) {
5296 // going into or coming out of SUSPEND: rescore and notify
5297 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005298 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005299 }
5300 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5301 ConnectivityManager.CALLBACK_SUSPENDED :
5302 ConnectivityManager.CALLBACK_RESUMED));
5303 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005304 }
5305 }
5306
Robert Greenwaltac96c522014-06-03 16:43:57 -07005307 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005308 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005309 if (score < 0) {
5310 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5311 "). Bumping score to min of 0");
5312 score = 0;
5313 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005314
Paul Jensen2161a8e2014-09-11 11:00:39 -04005315 final int oldScore = nai.getCurrentScore();
5316 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005317
Paul Jensen85cf78e2015-06-25 13:25:07 -04005318 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005319
Paul Jensenc8b9a742014-09-30 15:37:41 -04005320 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005321 }
5322
Erik Klinec75d4fa2017-02-15 19:59:17 +09005323 // Notify only this one new request of the current state. Transfer all the
5324 // current state by calling NetworkCapabilities and LinkProperties callbacks
5325 // so that callers can be guaranteed to have as close to atomicity in state
5326 // transfer as can be supported by this current API.
5327 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohenbf3b1ba2016-10-27 15:05:50 -07005328 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005329 if (nri.mPendingIntent != null) {
5330 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5331 // Attempt no subsequent state pushes where intents are involved.
5332 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005333 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005334
5335 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5336 // Whether a network is currently suspended is also an important
5337 // element of state to be transferred (it would not otherwise be
5338 // delivered by any currently available mechanism).
5339 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5340 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5341 }
5342 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5343 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005344 }
5345
Robert Greenwalt8d482522015-06-24 13:23:42 -07005346 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005347 // The NetworkInfo we actually send out has no bearing on the real
5348 // state of affairs. For example, if the default connection is mobile,
5349 // and a request for HIPRI has just gone away, we need to pretend that
5350 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5351 // the state to DISCONNECTED, even though the network is of type MOBILE
5352 // and is still connected.
5353 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5354 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005355 if (state != DetailedState.DISCONNECTED) {
5356 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005357 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005358 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005359 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005360 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5361 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5362 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5363 if (info.isFailover()) {
5364 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5365 nai.networkInfo.setFailover(false);
5366 }
5367 if (info.getReason() != null) {
5368 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5369 }
5370 if (info.getExtraInfo() != null) {
5371 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5372 }
5373 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005374 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005375 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005376 if (newDefaultAgent != null) {
5377 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5378 newDefaultAgent.networkInfo);
5379 } else {
5380 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5381 }
5382 }
5383 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5384 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005385 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005386 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005387 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005388 }
5389 }
5390 }
5391
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005392 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005393 if (VDBG) {
5394 String notification = ConnectivityManager.getCallbackName(notifyType);
5395 log("notifyType " + notification + " for " + networkAgent.name());
5396 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005397 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5398 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005399 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5400 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005401 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5402 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005403 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005404 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005405 } else {
5406 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5407 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005408 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005409 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005410
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005411 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5412 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5413 }
5414
Jeff Sharkey69736342014-12-08 14:50:12 -08005415 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005416 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5417 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005418 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005419 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005420 try {
5421 mStatsService.forceUpdateIfaces();
5422 } catch (Exception ignored) {
5423 }
5424 }
5425
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005426 @Override
5427 public boolean addVpnAddress(String address, int prefixLength) {
5428 throwIfLockdownEnabled();
5429 int user = UserHandle.getUserId(Binder.getCallingUid());
5430 synchronized (mVpns) {
5431 return mVpns.get(user).addAddress(address, prefixLength);
5432 }
5433 }
5434
5435 @Override
5436 public boolean removeVpnAddress(String address, int prefixLength) {
5437 throwIfLockdownEnabled();
5438 int user = UserHandle.getUserId(Binder.getCallingUid());
5439 synchronized (mVpns) {
5440 return mVpns.get(user).removeAddress(address, prefixLength);
5441 }
5442 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005443
5444 @Override
5445 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5446 throwIfLockdownEnabled();
5447 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005448 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005449 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005450 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005451 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005452 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005453 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005454 }
5455 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005456 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005457
5458 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005459 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005460 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005461 }
5462
5463 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005464 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5465 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5466 enforceKeepalivePermission();
5467 mKeepaliveTracker.startNattKeepalive(
5468 getNetworkAgentInfoForNetwork(network),
5469 intervalSeconds, messenger, binder,
5470 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5471 }
5472
5473 @Override
5474 public void stopKeepalive(Network network, int slot) {
5475 mHandler.sendMessage(mHandler.obtainMessage(
5476 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5477 }
5478
5479 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005480 public void factoryReset() {
5481 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005482
5483 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5484 return;
5485 }
5486
Robin Lee3b3dd942015-05-12 18:14:58 +01005487 final int userId = UserHandle.getCallingUserId();
5488
Stuart Scottf1fb3972015-04-02 18:00:02 -07005489 // Turn airplane mode off
5490 setAirplaneMode(false);
5491
Stuart Scotte3e314d2015-04-20 14:07:45 -07005492 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5493 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005494 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005495 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005496 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005497 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005498 }
5499
Stuart Scotte3e314d2015-04-20 14:07:45 -07005500 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005501 // Remove always-on package
5502 synchronized (mVpns) {
5503 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5504 if (alwaysOnPackage != null) {
5505 setAlwaysOnVpnPackage(userId, null, false);
5506 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5507 }
5508 }
5509
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005510 // Turn Always-on VPN off
5511 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5512 final long ident = Binder.clearCallingIdentity();
5513 try {
5514 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5515 mLockdownEnabled = false;
5516 setLockdownTracker(null);
5517 } finally {
5518 Binder.restoreCallingIdentity(ident);
5519 }
5520 }
5521
Stuart Scotte3e314d2015-04-20 14:07:45 -07005522 // Turn VPN off
5523 VpnConfig vpnConfig = getVpnConfig(userId);
5524 if (vpnConfig != null) {
5525 if (vpnConfig.legacy) {
5526 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5527 } else {
5528 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5529 // in the future without user intervention.
5530 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005531
Victor Changb04a5ea2016-05-30 20:36:30 +01005532 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005533 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005534 }
5535 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005536
5537 Settings.Global.putString(mContext.getContentResolver(),
5538 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005539 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005540
5541 @VisibleForTesting
5542 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5543 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5544 return new NetworkMonitor(context, handler, nai, defaultRequest);
5545 }
Erik Kline48f12f22016-04-14 17:30:59 +09005546
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005547 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005548 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5549 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005550 }
5551
5552 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005553 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5554 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5555 }
5556
Hugo Benichicfddd682016-05-31 16:28:06 +09005557 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005558 int newNetid = NETID_UNSET;
5559 int prevNetid = NETID_UNSET;
5560 int[] transports = new int[0];
5561 boolean hadIPv4 = false;
5562 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005563
Hugo Benichi5f16f762016-04-20 12:09:33 +09005564 if (newNai != null) {
5565 newNetid = newNai.network.netId;
5566 transports = newNai.networkCapabilities.getTransportTypes();
5567 }
5568 if (prevNai != null) {
5569 prevNetid = prevNai.network.netId;
5570 final LinkProperties lp = prevNai.linkProperties;
5571 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5572 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5573 }
5574
Hugo Benichicfddd682016-05-31 16:28:06 +09005575 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5576 }
5577
5578 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5579 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005580 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005581
5582 private static boolean toBool(int encodedBoolean) {
5583 return encodedBoolean != 0; // Only 0 means false.
5584 }
5585
5586 private static int encodeBool(boolean b) {
5587 return b ? 1 : 0;
5588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589}