blob: 19badbd605368c2d46e19b2f519b1b948d93293e [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;
Robert Greenwalt434203a2010-10-11 16:00:27 -070052import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090054import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070056import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.INetworkPolicyListener;
58import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070059import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070063import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkCapabilities;
Etan Cohena7434272017-04-03 12:17:51 -070065import android.net.MatchAllNetworkSpecifier;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070066import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070068import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070069import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070070import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070071import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070072import android.net.NetworkSpecifier;
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;
Hugo Benichicb883232017-05-11 13:16:17 +0900101import android.os.ServiceSpecificException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900102import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700103import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400104import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700106import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700107import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700108import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700109import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600110import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700111import android.util.LocalLog;
112import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600113import android.util.Log;
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;
Erik Kline5a7c8a02017-04-30 19:36:15 +0900148import com.android.server.connectivity.tethering.TetheringDependencies;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700149import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700150import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700151import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600152
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700153import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700154
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700155import org.xmlpull.v1.XmlPullParser;
156import org.xmlpull.v1.XmlPullParserException;
157
158import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700160import java.io.FileNotFoundException;
161import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700162import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700164import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700165import java.net.InetAddress;
166import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700167import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700168import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700169import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700170import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700171import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700172import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700173import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700174import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700175import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600176import java.util.SortedSet;
177import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
179/**
180 * @hide
181 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800182public class ConnectivityService extends IConnectivityManager.Stub
183 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900184 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Erik Kline7747fd42017-05-12 16:52:48 +0900186 public static final String DIAG_ARG = "--diag";
187 public static final String SHORT_ARG = "--short";
188
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900189 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700190 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Jake Hamby786e71a2014-02-06 14:43:50 -0800192 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900193 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700194
Jeff Sharkey899223b2012-08-04 15:24:58 -0700195 // TODO: create better separation between radio types and network types
196
Robert Greenwalt42acef32009-08-12 16:08:25 -0700197 // how long to wait before switching back to a radio's default network
198 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
199 // system property that can override the above value
200 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
201 "android.telephony.apn-restore";
202
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900203 // How long to wait before putting up a "This network doesn't have an Internet connection,
204 // connect anyway?" dialog after the user selects a network that doesn't validate.
205 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
206
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900207 // Default to 30s linger time-out. Modifiable only for testing.
208 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
209 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
210 @VisibleForTesting
211 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
212
Jeremy Joslin79294842014-12-03 17:15:28 -0800213 // How long to delay to removal of a pending intent based request.
214 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
215 private final int mReleasePendingIntentDelayMs;
216
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900217 private MockableSystemProperties mSystemProperties;
218
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800219 private Tethering mTethering;
220
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700221 private final PermissionMonitor mPermissionMonitor;
222
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700223 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700224
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700225 @GuardedBy("mVpns")
226 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700227
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700228 private boolean mLockdownEnabled;
229 private LockdownVpnTracker mLockdownTracker;
230
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700231 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
232 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700233 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600234 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700235 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700236 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600237 @GuardedBy("mRulesLock")
238 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
239 /** Flag indicating if background data is restricted. */
240 @GuardedBy("mRulesLock")
241 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700242
Erik Klineda4bfa82015-04-30 12:58:40 +0900243 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700245 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700246 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800248 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249
250 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700251 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700253 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800254 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700255 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700256
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700257 private String mCurrentTcpBufferSizes;
258
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700259 private static final int ENABLED = 1;
260 private static final int DISABLED = 0;
261
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900262 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900263 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
264 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900265
Paul Jensenb10e37f2014-11-25 12:33:08 -0500266 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400267 // Tear down networks that have no chance (e.g. even if validated) of becoming
268 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500269 // all networks have been rematched against all NetworkRequests.
270 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400271 // Don't reap networks. This should be passed when some networks have not yet been
272 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500273 DONT_REAP
274 };
275
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900276 private enum UnneededFor {
277 LINGER, // Determine whether this network is unneeded and should be lingered.
278 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
279 }
280
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700281 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700282 * used internally to change our mobile data enabled flag
283 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700284 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700285
286 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700287 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700288 * from one net to another. Clear happens when we get a new
289 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
290 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700291 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700292 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700293
Robert Greenwalt434203a2010-10-11 16:00:27 -0700294 /**
295 * used internally to reload global proxy settings
296 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700297 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700298
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700299 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400300 * PAC manager has received new port.
301 */
302 private static final int EVENT_PROXY_HAS_CHANGED = 16;
303
Robert Greenwalte049c232014-04-11 15:53:27 -0700304 /**
305 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700306 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700307 */
308 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
309
Robert Greenwalt7b816022014-04-18 15:25:25 -0700310 /**
311 * used internally when registering NetworkAgents
312 * obj = Messenger
313 */
314 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
315
Robert Greenwalt9258c642014-03-26 16:47:06 -0700316 /**
317 * used to add a network request
318 * includes a NetworkRequestInfo
319 */
320 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
321
322 /**
323 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900324 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700325 * cancel it.
326 * includes a NetworkRequestInfo
327 */
328 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
329
330 /**
331 * used to add a network listener - no request
332 * includes a NetworkRequestInfo
333 */
334 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
335
336 /**
337 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400338 * arg1 = UID of caller
339 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700340 */
341 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
342
Robert Greenwalta67be032014-05-16 15:49:14 -0700343 /**
344 * used internally when registering NetworkFactories
345 * obj = Messenger
346 */
347 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
348
Robert Greenwalt27711812014-06-25 16:45:57 -0700349 /**
350 * used internally to expire a wakelock when transitioning
351 * from one net to another. Expire happens when we fail to find
352 * a new network (typically after 1 minute) -
353 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
354 * a replacement network.
355 */
356 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
357
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700358 /**
359 * Used internally to indicate the system is ready.
360 */
361 private static final int EVENT_SYSTEM_READY = 25;
362
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800363 /**
364 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400365 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800366 */
367 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
368
369 /**
370 * used to remove a pending intent and its associated network request.
371 * arg1 = UID of caller
372 * obj = PendingIntent
373 */
374 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
375
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900376 /**
377 * used to specify whether a network should be used even if unvalidated.
378 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
379 * arg2 = whether to remember this choice in the future (1 or 0)
380 * obj = network
381 */
382 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
383
384 /**
385 * used to ask the user to confirm a connection to an unvalidated network.
386 * obj = network
387 */
388 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700389
Erik Klineda4bfa82015-04-30 12:58:40 +0900390 /**
391 * used internally to (re)configure mobile data always-on settings.
392 */
393 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
394
Paul Jensen694f2b82015-06-17 14:15:39 -0400395 /**
396 * used to add a network listener with a pending intent
397 * obj = NetworkRequestInfo
398 */
399 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
400
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900401 /**
402 * used to specify whether a network should not be penalized when it becomes unvalidated.
403 */
404 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
405
406 /**
407 * used to trigger revalidation of a network.
408 */
409 private static final int EVENT_REVALIDATE_NETWORK = 36;
410
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900411 private static String eventName(int what) {
412 return sMagicDecoderRing.get(what, Integer.toString(what));
413 }
414
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900415 /** Handler thread used for both of the handlers below. */
416 @VisibleForTesting
417 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700418 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700419 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700420 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700421 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700422
Mike Lockwood0f79b542009-08-14 14:18:49 -0400423 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800424 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400425
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700426 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700427 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800428 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700429
Robert Greenwalt434203a2010-10-11 16:00:27 -0700430 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400431 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700432 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700433 private boolean mDefaultProxyDisabled = false;
434
Robert Greenwalt434203a2010-10-11 16:00:27 -0700435 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400436 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700437
Jason Monk602b2322013-07-03 17:04:33 -0400438 private PacManager mPacManager = null;
439
Erik Klineda4bfa82015-04-30 12:58:40 +0900440 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700441
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400442 private UserManager mUserManager;
443
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700444 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700445 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700446
Robert Greenwalt50393202011-06-21 17:26:14 -0700447 // the set of network types that can only be enabled by system/sig apps
448 List mProtectedNetworks;
449
John Spurlockbf991a82013-06-24 14:20:23 -0400450 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700451
Wink Savilleab9321d2013-06-29 21:10:57 -0700452 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400453
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900454 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900455 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900456 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900457
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700458 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
459 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700460 private final static int MAX_NET_ID = 65535;
461 private int mNextNetId = MIN_NET_ID;
462
Robert Greenwalt34524f02014-05-18 16:22:10 -0700463 // sequence number of NetworkRequests
464 private int mNextNetworkRequestId = 1;
465
Erik Kline7523eb32015-07-09 18:24:03 +0900466 // NetworkRequest activity String log entries.
467 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
468 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
469
Hugo Benichic2ae2872016-07-11 11:05:12 +0900470 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900471 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900472 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
473
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900474 private static final int MAX_WAKELOCK_LOGS = 20;
475 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
476
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700477 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
478 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400479 private static class ValidationLog {
480 final Network mNetwork;
481 final String mNetworkExtraInfo;
482 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700483
Paul Jensen0808eb82016-06-03 13:51:21 -0400484 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
485 mNetwork = network;
486 mNetworkExtraInfo = networkExtraInfo;
487 mLog = log;
488 }
489 }
490 private final ArrayDeque<ValidationLog> mValidationLogs =
491 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
492
493 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900494 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700495 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
496 mValidationLogs.removeLast();
497 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400498 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700499 }
500 }
501
Hugo Benichif9fdf872016-07-28 17:53:06 +0900502 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900503
Erik Kline065ab6e2016-10-02 18:02:14 +0900504 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900505 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900506
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700507 /**
508 * Implements support for the legacy "one network per network type" model.
509 *
510 * We used to have a static array of NetworkStateTrackers, one for each
511 * network type, but that doesn't work any more now that we can have,
512 * for example, more that one wifi network. This class stores all the
513 * NetworkAgentInfo objects that support a given type, but the legacy
514 * API will only see the first one.
515 *
516 * It serves two main purposes:
517 *
518 * 1. Provide information about "the network for a given type" (since this
519 * API only supports one).
520 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
521 * the first network for a given type changes, or if the default network
522 * changes.
523 */
524 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900525
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900526 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900527 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900528
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700529 /**
530 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
531 * Each list holds references to all NetworkAgentInfos that are used to
532 * satisfy requests for that network type.
533 *
534 * This array is built out at startup such that an unsupported network
535 * doesn't get an ArrayList instance, making this a tristate:
536 * unsupported, supported but not active and active.
537 *
538 * The actual lists are populated when we scan the network types that
539 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900540 *
541 * Threading model:
542 * - addSupportedType() is only called in the constructor
543 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
544 * They are therefore not thread-safe with respect to each other.
545 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
546 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
547 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700548 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900549 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700550
551 public LegacyTypeTracker() {
552 mTypeLists = (ArrayList<NetworkAgentInfo>[])
553 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
554 }
555
556 public void addSupportedType(int type) {
557 if (mTypeLists[type] != null) {
558 throw new IllegalStateException(
559 "legacy list for type " + type + "already initialized");
560 }
561 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
562 }
563
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700564 public boolean isTypeSupported(int type) {
565 return isNetworkTypeValid(type) && mTypeLists[type] != null;
566 }
567
568 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900569 synchronized (mTypeLists) {
570 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
571 return mTypeLists[type].get(0);
572 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700573 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900574 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700575 }
576
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900578 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900579 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700580 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900581 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900582 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900583 }
584 }
585
586 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700587 public void add(int type, NetworkAgentInfo nai) {
588 if (!isTypeSupported(type)) {
589 return; // Invalid network type.
590 }
591 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
592
593 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
594 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700595 return;
596 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900597 synchronized (mTypeLists) {
598 list.add(nai);
599 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900600
601 // 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 +0900602 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900603 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700604 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
605 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700606 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700607 }
608
Lorenzo Colittia793a672014-07-31 23:20:17 +0900609 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900610 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900611 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
612 if (list == null || list.isEmpty()) {
613 return;
614 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900615 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900616
Hugo Benichi78caa2582016-06-21 09:48:07 +0900617 synchronized (mTypeLists) {
618 if (!list.remove(nai)) {
619 return;
620 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900621 }
622
Robert Greenwalt8d482522015-06-24 13:23:42 -0700623 final DetailedState state = DetailedState.DISCONNECTED;
624
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900625 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700626 maybeLogBroadcast(nai, state, type, wasDefault);
627 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900628 }
629
630 if (!list.isEmpty() && wasFirstNetwork) {
631 if (DBG) log("Other network available for type " + type +
632 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900633 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700634 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
635 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900636 }
637 }
638
639 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900640 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
641 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700642 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900643 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700644 }
645 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700646
Robert Greenwalt8d482522015-06-24 13:23:42 -0700647 // send out another legacy broadcast - currently only used for suspend/unsuspend
648 // toggle
649 public void update(NetworkAgentInfo nai) {
650 final boolean isDefault = isDefaultNetwork(nai);
651 final DetailedState state = nai.networkInfo.getDetailedState();
652 for (int type = 0; type < mTypeLists.length; type++) {
653 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700654 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900655 final boolean isFirst = contains && (nai == list.get(0));
656 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700657 maybeLogBroadcast(nai, state, type, isDefault);
658 sendLegacyNetworkBroadcast(nai, state, type);
659 }
660 }
661 }
662
Lorenzo Colittia793a672014-07-31 23:20:17 +0900663 private String naiToString(NetworkAgentInfo nai) {
664 String name = (nai != null) ? nai.name() : "null";
665 String state = (nai.networkInfo != null) ?
666 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
667 "???/???";
668 return name + " " + state;
669 }
670
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700671 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900672 pw.println("mLegacyTypeTracker:");
673 pw.increaseIndent();
674 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700675 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900676 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700677 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900678 pw.println();
679 pw.println("Current state:");
680 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900681 synchronized (mTypeLists) {
682 for (int type = 0; type < mTypeLists.length; type++) {
683 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
684 for (NetworkAgentInfo nai : mTypeLists[type]) {
685 pw.println(type + " " + naiToString(nai));
686 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900687 }
688 }
689 pw.decreaseIndent();
690 pw.decreaseIndent();
691 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700692 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700693 }
694 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
695
Jeff Sharkey899223b2012-08-04 15:24:58 -0700696 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700697 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900698 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
699 }
700
701 @VisibleForTesting
702 protected ConnectivityService(Context context, INetworkManagementService netManager,
703 INetworkStatsService statsService, INetworkPolicyManager policyManager,
704 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800705 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800706
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900707 mSystemProperties = getSystemProperties();
708
Hugo Benichif9fdf872016-07-28 17:53:06 +0900709 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900710 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900711 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900712 mNetworkRequests.put(mDefaultRequest, defaultNRI);
713 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900714
715 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900716 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700717
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900718 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900719 mHandlerThread.start();
720 mHandler = new InternalHandler(mHandlerThread.getLooper());
721 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700722
Jeremy Joslin79294842014-12-03 17:15:28 -0800723 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
724 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
725
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900726 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900727
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700728 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700729 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800730 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700731 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700732 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700733 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700734
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700735 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600736 mPolicyManager.setConnectivityListener(mPolicyListener);
737 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700738 } catch (RemoteException e) {
739 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700740 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700741 }
742
743 final PowerManager powerManager = (PowerManager) context.getSystemService(
744 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700745 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
746 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
747 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800748 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700749
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700750 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700751
Wink Saville51f456f2013-04-23 14:26:51 -0700752 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900753 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700754 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700755 String[] naStrings = context.getResources().getStringArray(
756 com.android.internal.R.array.networkAttributes);
757 for (String naString : naStrings) {
758 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700759 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700760 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700761 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800762 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700763 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700764 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700765 }
Wink Saville51f456f2013-04-23 14:26:51 -0700766 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
767 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
768 n.type);
769 continue;
770 }
Wink Saville975c8482011-04-07 14:23:45 -0700771 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800772 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700773 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700774 continue;
775 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700776 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700777
Wink Saville975c8482011-04-07 14:23:45 -0700778 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700779 mNetworksDefined++;
780 } catch(Exception e) {
781 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700782 }
783 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700784
785 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
786 if (mNetConfigs[TYPE_VPN] == null) {
787 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
788 // don't need to add TYPE_VPN to mNetConfigs.
789 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
790 mNetworksDefined++; // used only in the log() statement below.
791 }
792
Wink Saville5e56bc52013-07-29 15:00:57 -0700793 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700794
Robert Greenwalt50393202011-06-21 17:26:14 -0700795 mProtectedNetworks = new ArrayList<Integer>();
796 int[] protectedNetworks = context.getResources().getIntArray(
797 com.android.internal.R.array.config_protectedNetworks);
798 for (int p : protectedNetworks) {
799 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
800 mProtectedNetworks.add(p);
801 } else {
802 if (DBG) loge("Ignoring protectedNetwork " + p);
803 }
804 }
805
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900806 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
807 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700808
Erik Kline5a7c8a02017-04-30 19:36:15 +0900809 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800810
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700811 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
812
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700813 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700814 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100815 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700816 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700817 intentFilter.addAction(Intent.ACTION_USER_ADDED);
818 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000819 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700820 mContext.registerReceiverAsUser(
821 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000822 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
823 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900824
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700825 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700826 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700827 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700828 } catch (RemoteException e) {
829 loge("Error registering observer :" + e);
830 }
831
Erik Klineda4bfa82015-04-30 12:58:40 +0900832 mSettingsObserver = new SettingsObserver(mContext, mHandler);
833 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800834
John Spurlockbf991a82013-06-24 14:20:23 -0400835 mDataConnectionStats = new DataConnectionStats(mContext);
836 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400837
Jason Monkdecd2952013-10-10 14:02:51 -0400838 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700839
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400840 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900841
842 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900843 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
844 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900845
846 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
847 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
848 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
849 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
850 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
851 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
852 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900853
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900854 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900855 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900856 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700858
Erik Kline5a7c8a02017-04-30 19:36:15 +0900859 private Tethering makeTethering() {
860 // TODO: Move other elements into @Overridden getters.
861 final TetheringDependencies deps = new TetheringDependencies();
862 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
863 IoThread.get().getLooper(), new MockableSystemProperties(),
864 deps);
865 }
866
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900867 private NetworkRequest createInternetRequestForTransport(
868 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900869 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900870 netCap.addCapability(NET_CAPABILITY_INTERNET);
871 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900872 if (transportType > -1) {
873 netCap.addTransportType(transportType);
874 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900875 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900876 }
877
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900878 // Used only for testing.
879 // TODO: Delete this and either:
880 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
881 // changing ContentResolver to make registerContentObserver non-final).
882 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
883 // by subclassing SettingsObserver.
884 @VisibleForTesting
885 void updateMobileDataAlwaysOn() {
886 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
887 }
888
Erik Klineda4bfa82015-04-30 12:58:40 +0900889 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900890 final boolean enable = toBool(Settings.Global.getInt(
891 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900892 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
893 if (enable == isEnabled) {
894 return; // Nothing to do.
895 }
896
897 if (enable) {
898 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900899 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900900 } else {
901 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
902 }
903 }
904
905 private void registerSettingsCallbacks() {
906 // Watch for global HTTP proxy changes.
907 mSettingsObserver.observe(
908 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
909 EVENT_APPLY_GLOBAL_HTTP_PROXY);
910
911 // Watch for whether or not to keep mobile data always on.
912 mSettingsObserver.observe(
913 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
914 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
915 }
916
Robert Greenwalt34524f02014-05-18 16:22:10 -0700917 private synchronized int nextNetworkRequestId() {
918 return mNextNetworkRequestId++;
919 }
920
Paul Jensen67b0b072015-06-10 11:22:17 -0400921 @VisibleForTesting
922 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400923 synchronized (mNetworkForNetId) {
924 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
925 int netId = mNextNetId;
926 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
927 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500928 if (!mNetIdInUse.get(netId)) {
929 mNetIdInUse.put(netId, true);
930 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400931 }
932 }
933 }
934 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700935 }
936
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600937 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800938 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600939 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
940 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800941 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600942 state = nai.getNetworkState();
943 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800944 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600945 final NetworkInfo info = new NetworkInfo(networkType, 0,
946 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800947 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
948 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600949 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
950 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800951 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600952 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600953 return state;
954 } else {
955 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800956 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400957 }
958
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800959 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
960 if (network == null) {
961 return null;
962 }
963 synchronized (mNetworkForNetId) {
964 return mNetworkForNetId.get(network.netId);
965 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600966 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800967
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900968 private Network[] getVpnUnderlyingNetworks(int uid) {
969 if (!mLockdownEnabled) {
970 int user = UserHandle.getUserId(uid);
971 synchronized (mVpns) {
972 Vpn vpn = mVpns.get(user);
973 if (vpn != null && vpn.appliesToUid(uid)) {
974 return vpn.getUnderlyingNetworks();
975 }
976 }
977 }
978 return null;
979 }
980
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800981 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400982 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800983
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900984 final Network[] networks = getVpnUnderlyingNetworks(uid);
985 if (networks != null) {
986 // getUnderlyingNetworks() returns:
987 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
988 // empty array => the VPN explicitly said "no default network".
989 // non-empty array => the VPN specified one or more default networks; we use the
990 // first one.
991 if (networks.length > 0) {
992 nai = getNetworkAgentInfoForNetwork(networks[0]);
993 } else {
994 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800995 }
996 }
997
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800998 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600999 return nai.getNetworkState();
1000 } else {
1001 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001002 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001003 }
1004
1005 /**
1006 * Check if UID should be blocked from using the network with the given LinkProperties.
1007 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001008 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1009 boolean ignoreBlocked) {
1010 // Networks aren't blocked when ignoring blocked status
1011 if (ignoreBlocked) return false;
1012 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001013 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001014
1015 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001016 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001017
Robin Lee17e61832016-05-09 13:46:28 +01001018 synchronized (mVpns) {
1019 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1020 if (vpn != null && vpn.isBlockingUid(uid)) {
1021 return true;
1022 }
1023 }
1024
Robert Greenwalt12e67352014-05-13 21:41:06 -07001025 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001026 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001027 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001028 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001029 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001030
Felipe Lemed31a97f2016-05-06 14:53:50 -07001031 boolean allowed = true;
1032 // Check Data Saver Mode first...
1033 if (networkMetered) {
1034 if ((uidRules & RULE_REJECT_METERED) != 0) {
1035 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1036 // Explicitly blacklisted.
1037 allowed = false;
1038 } else {
1039 allowed = !mRestrictBackground
1040 || (uidRules & RULE_ALLOW_METERED) != 0
1041 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1042 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1043 + " mRestrictBackground=" + mRestrictBackground
1044 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1045 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1046 + ": " + allowed);
1047 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001048 }
Felipe Leme781ba142016-05-09 16:24:48 -07001049 // ...then power restrictions.
1050 if (allowed) {
1051 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001052 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001053 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001054 }
1055 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001056 }
1057
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001058 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001059 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1060 return;
1061 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001062 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001063 synchronized (mBlockedAppUids) {
1064 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001065 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001066 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001067 blocked = false;
1068 } else {
1069 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001070 }
1071 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001072 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1073 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1074 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001075 }
1076
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001077 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001078 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1079 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1080 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1081 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001082 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001083 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001084 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1085
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001086 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001087 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001088 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001089 if (mLockdownTracker != null) {
1090 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001091 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001092
1093 // TODO: apply metered state closer to NetworkAgentInfo
1094 final long token = Binder.clearCallingIdentity();
1095 try {
1096 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1097 } catch (RemoteException e) {
1098 } finally {
1099 Binder.restoreCallingIdentity(token);
1100 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001101 }
1102
1103 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 * Return NetworkInfo for the active (i.e., connected) network interface.
1105 * It is assumed that at most one network is active at a time. If more
1106 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001107 * @return the info for the active network, or {@code null} if none is
1108 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001110 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001112 enforceAccessPermission();
1113 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001114 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001115 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001116 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1117 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 }
1119
Paul Jensen31a94f42015-02-13 14:18:39 -05001120 @Override
1121 public Network getActiveNetwork() {
1122 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001123 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001124 }
1125
1126 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001127 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001128 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001129 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001130 }
1131
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001132 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001133 final int user = UserHandle.getUserId(uid);
1134 int vpnNetId = NETID_UNSET;
1135 synchronized (mVpns) {
1136 final Vpn vpn = mVpns.get(user);
1137 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1138 }
1139 NetworkAgentInfo nai;
1140 if (vpnNetId != NETID_UNSET) {
1141 synchronized (mNetworkForNetId) {
1142 nai = mNetworkForNetId.get(vpnNetId);
1143 }
1144 if (nai != null) return nai.network;
1145 }
1146 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001147 if (nai != null
1148 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1149 nai = null;
1150 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001151 return nai != null ? nai.network : null;
1152 }
1153
Lorenzo Colitti18660282016-07-04 12:55:44 +09001154 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001155 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1156 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001157 final int uid = Binder.getCallingUid();
1158 NetworkState state = getUnfilteredActiveNetworkState(uid);
1159 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001160 }
1161
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001162 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001163 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001164 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001165 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001166 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001167 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001168 }
1169
1170 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 public NetworkInfo getNetworkInfo(int networkType) {
1172 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001173 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001174 if (getVpnUnderlyingNetworks(uid) != null) {
1175 // A VPN is active, so we may need to return one of its underlying networks. This
1176 // information is not available in LegacyTypeTracker, so we have to get it from
1177 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001178 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001179 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001180 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001181 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001182 }
1183 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001184 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001185 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
1187
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001188 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001189 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001190 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001191 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001192 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001193 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001194 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001195 return state.networkInfo;
1196 } else {
1197 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001198 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001199 }
1200
1201 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 public NetworkInfo[] getAllNetworkInfo() {
1203 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001204 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001205 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1206 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001207 NetworkInfo info = getNetworkInfo(networkType);
1208 if (info != null) {
1209 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001212 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 }
1214
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001215 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001216 public Network getNetworkForType(int networkType) {
1217 enforceAccessPermission();
1218 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001219 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1220 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001221 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001222 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001223 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001224 }
1225
1226 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001227 public Network[] getAllNetworks() {
1228 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001229 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001230 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001231 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001232 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001233 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001234 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001235 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001236 }
1237
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001238 @Override
1239 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1240 // The basic principle is: if an app's traffic could possibly go over a
1241 // network, without the app doing anything multinetwork-specific,
1242 // (hence, by "default"), then include that network's capabilities in
1243 // the array.
1244 //
1245 // In the normal case, app traffic only goes over the system's default
1246 // network connection, so that's the only network returned.
1247 //
1248 // With a VPN in force, some app traffic may go into the VPN, and thus
1249 // over whatever underlying networks the VPN specifies, while other app
1250 // traffic may go over the system default network (e.g.: a split-tunnel
1251 // VPN, or an app disallowed by the VPN), so the set of networks
1252 // returned includes the VPN's underlying networks and the system
1253 // default.
1254 enforceAccessPermission();
1255
1256 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1257
1258 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001259 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001260 if (nc != null) {
1261 result.put(nai.network, nc);
1262 }
1263
1264 if (!mLockdownEnabled) {
1265 synchronized (mVpns) {
1266 Vpn vpn = mVpns.get(userId);
1267 if (vpn != null) {
1268 Network[] networks = vpn.getUnderlyingNetworks();
1269 if (networks != null) {
1270 for (Network network : networks) {
1271 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001272 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001273 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001274 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001275 }
1276 }
1277 }
1278 }
1279 }
1280 }
1281
1282 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1283 out = result.values().toArray(out);
1284 return out;
1285 }
1286
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001287 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001288 public boolean isNetworkSupported(int networkType) {
1289 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001290 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001291 }
1292
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001293 /**
1294 * Return LinkProperties for the active (i.e., connected) default
1295 * network interface. It is assumed that at most one default network
1296 * is active at a time. If more than one is active, it is indeterminate
1297 * which will be returned.
1298 * @return the ip properties for the active network, or {@code null} if
1299 * none is active
1300 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001301 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001302 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001303 enforceAccessPermission();
1304 final int uid = Binder.getCallingUid();
1305 NetworkState state = getUnfilteredActiveNetworkState(uid);
1306 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001307 }
1308
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001309 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001310 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001311 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001312 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1313 if (nai != null) {
1314 synchronized (nai) {
1315 return new LinkProperties(nai.linkProperties);
1316 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001317 }
1318 return null;
1319 }
1320
Robert Greenwalt12e67352014-05-13 21:41:06 -07001321 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001322 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001323 public LinkProperties getLinkProperties(Network network) {
1324 enforceAccessPermission();
Hugo Benichi29551722017-04-06 16:01:44 +09001325 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1326 }
1327
1328 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1329 if (nai == null) {
1330 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001331 }
Hugo Benichi29551722017-04-06 16:01:44 +09001332 synchronized (nai) {
1333 return new LinkProperties(nai.linkProperties);
1334 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001335 }
1336
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001337 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001338 if (nai != null) {
1339 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001340 if (nai.networkCapabilities != null) {
1341 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001342 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001343 }
1344 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001345 return null;
1346 }
1347
1348 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001349 public NetworkCapabilities getNetworkCapabilities(Network network) {
1350 enforceAccessPermission();
1351 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1352 }
1353
1354 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001355 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001356 // Require internal since we're handing out IMSI details
1357 enforceConnectivityInternalPermission();
1358
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001359 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001360 for (Network network : getAllNetworks()) {
1361 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1362 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001363 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001364 }
1365 }
1366 return result.toArray(new NetworkState[result.size()]);
1367 }
1368
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001369 @Override
1370 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1371 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001372 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001373 final long token = Binder.clearCallingIdentity();
1374 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001375 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1376 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001377 try {
1378 return mPolicyManager.getNetworkQuotaInfo(state);
1379 } catch (RemoteException e) {
1380 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001381 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001382 return null;
1383 } finally {
1384 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001385 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001386 }
1387
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001388 @Override
1389 public boolean isActiveNetworkMetered() {
1390 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001391
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001392 final NetworkInfo info = getActiveNetworkInfo();
1393 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001394 }
1395
Jeff Sharkey216c1812012-08-05 14:29:23 -07001396 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1397 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001398 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001399 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001400 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001401 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001402 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001403
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001404 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 * Ensure that a network route exists to deliver traffic to the specified
1406 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001407 * @param networkType the type of the network over which traffic to the
1408 * specified host is to be routed
1409 * @param hostAddress the IP address of the host to which the route is
1410 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 * @return {@code true} on success, {@code false} on failure
1412 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001413 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001414 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001416 if (mProtectedNetworks.contains(networkType)) {
1417 enforceConnectivityInternalPermission();
1418 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001419
Chad Brubakerc0234532014-02-14 13:24:29 -08001420 InetAddress addr;
1421 try {
1422 addr = InetAddress.getByAddress(hostAddress);
1423 } catch (UnknownHostException e) {
1424 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1425 return false;
1426 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001429 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 return false;
1431 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001432
1433 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1434 if (nai == null) {
1435 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1436 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1437 } else {
1438 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1439 }
1440 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001441 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001442
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001443 DetailedState netState;
1444 synchronized (nai) {
1445 netState = nai.networkInfo.getDetailedState();
1446 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001447
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001448 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001449 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001450 log("requestRouteToHostAddress on down network "
1451 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001452 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001453 }
1454 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001456
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001457 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001458 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001459 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001460 LinkProperties lp;
1461 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001462 synchronized (nai) {
1463 lp = nai.linkProperties;
1464 netId = nai.network.netId;
1465 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001466 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001467 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1468 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001469 } finally {
1470 Binder.restoreCallingIdentity(token);
1471 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001472 }
1473
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001474 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001475 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001476 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001477 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001478 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001479 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001480 if (bestRoute.getGateway().equals(addr)) {
1481 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001482 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001483 } else {
1484 // if we will connect to this through another route, add a direct route
1485 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001486 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001487 }
1488 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001489 if (DBG) log("Adding legacy route " + bestRoute +
1490 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001491 try {
1492 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1493 } catch (Exception e) {
1494 // never crash - catch them all
1495 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001496 return false;
1497 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001498 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001501 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1502 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001503 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001504 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001505 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001506 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001507 }
1508
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001509 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001510 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001511 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001512 if (oldRules == uidRules) return;
1513
Felipe Leme781ba142016-05-09 16:24:48 -07001514 if (uidRules == RULE_NONE) {
1515 mUidRules.delete(uid);
1516 } else {
1517 mUidRules.put(uid, uidRules);
1518 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001519 }
1520
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001521 // TODO: notify UID when it has requested targeted updates
1522 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001523
1524 @Override
1525 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001526 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001527 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001528 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001529 }
1530
1531 synchronized (mRulesLock) {
1532 mMeteredIfaces.clear();
1533 for (String iface : meteredIfaces) {
1534 mMeteredIfaces.add(iface);
1535 }
1536 }
1537 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001538
1539 @Override
1540 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1541 // caller is NPMS, since we only register with them
1542 if (LOGD_RULES) {
1543 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1544 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001545
1546 synchronized (mRulesLock) {
1547 mRestrictBackground = restrictBackground;
1548 }
1549
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001550 if (restrictBackground) {
1551 log("onRestrictBackgroundChanged(true): disabling tethering");
1552 mTethering.untetherAll();
1553 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001554 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001555
1556 @Override
1557 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1558 if (LOGD_RULES) {
1559 // caller is NPMS, since we only register with them
1560 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1561 + whitelisted + ")");
1562 }
1563 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001564 @Override
1565 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1566 if (LOGD_RULES) {
1567 // caller is NPMS, since we only register with them
1568 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1569 + blacklisted + ")");
1570 }
1571 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001572 };
1573
Robin Lee3b3dd942015-05-12 18:14:58 +01001574 /**
1575 * Require that the caller is either in the same user or has appropriate permission to interact
1576 * across users.
1577 *
1578 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1579 */
1580 private void enforceCrossUserPermission(int userId) {
1581 if (userId == UserHandle.getCallingUserId()) {
1582 // Not a cross-user call.
1583 return;
1584 }
1585 mContext.enforceCallingOrSelfPermission(
1586 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1587 "ConnectivityService");
1588 }
1589
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001590 private void enforceInternetPermission() {
1591 mContext.enforceCallingOrSelfPermission(
1592 android.Manifest.permission.INTERNET,
1593 "ConnectivityService");
1594 }
1595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001597 mContext.enforceCallingOrSelfPermission(
1598 android.Manifest.permission.ACCESS_NETWORK_STATE,
1599 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 }
1601
1602 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001603 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 }
1605
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001606 private void enforceTetherAccessPermission() {
1607 mContext.enforceCallingOrSelfPermission(
1608 android.Manifest.permission.ACCESS_NETWORK_STATE,
1609 "ConnectivityService");
1610 }
1611
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001612 private void enforceConnectivityInternalPermission() {
1613 mContext.enforceCallingOrSelfPermission(
1614 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1615 "ConnectivityService");
1616 }
1617
Hugo Benichi514da602016-07-19 15:59:27 +09001618 private void enforceConnectivityRestrictedNetworksPermission() {
1619 try {
1620 mContext.enforceCallingOrSelfPermission(
1621 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1622 "ConnectivityService");
1623 return;
1624 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1625 enforceConnectivityInternalPermission();
1626 }
1627
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001628 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001629 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001630 }
1631
Lorenzo Colitti18660282016-07-04 12:55:44 +09001632 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001633 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001634 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001635 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001636 }
1637
1638 private void sendInetConditionBroadcast(NetworkInfo info) {
1639 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1640 }
1641
Wink Saville628b0852011-08-04 15:01:58 -07001642 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001643 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001644 info = new NetworkInfo(info);
1645 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001646 }
1647
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001648 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001649 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001650 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 if (info.isFailover()) {
1652 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1653 info.setFailover(false);
1654 }
1655 if (info.getReason() != null) {
1656 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1657 }
1658 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001659 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1660 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001662 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001663 return intent;
1664 }
1665
1666 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1667 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1668 }
1669
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001670 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001671 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1672 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1673 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001674 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001675 final long ident = Binder.clearCallingIdentity();
1676 try {
1677 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1678 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1679 } finally {
1680 Binder.restoreCallingIdentity(ident);
1681 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001682 }
1683
Mike Lockwood0f79b542009-08-14 14:18:49 -04001684 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001685 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001686 if (!mSystemReady) {
1687 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001688 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001689 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001690 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001691 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001692 }
1693
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001694 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001695 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001696 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001697 final NetworkInfo ni = intent.getParcelableExtra(
1698 ConnectivityManager.EXTRA_NETWORK_INFO);
1699 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1700 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1701 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001702 } else {
1703 BroadcastOptions opts = BroadcastOptions.makeBasic();
1704 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1705 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001706 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001707 final IBatteryStats bs = BatteryStatsService.getService();
1708 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001709 bs.noteConnectivityChanged(intent.getIntExtra(
1710 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1711 ni != null ? ni.getState().toString() : "?");
1712 } catch (RemoteException e) {
1713 }
1714 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001715 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001716 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001717 } finally {
1718 Binder.restoreCallingIdentity(ident);
1719 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001720 }
1721 }
1722
1723 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001724 loadGlobalProxy();
1725
Hugo Benichi20035e02017-04-26 14:53:28 +09001726 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001727 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001728 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001729 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001730 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001731 }
1732 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001733 // load the global proxy at startup
1734 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001735
Robin Lee244ce8e2016-01-05 18:03:46 +00001736 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1737 // for user to unlock device too.
1738 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001739
Erik Klineda4bfa82015-04-30 12:58:40 +09001740 // Configure whether mobile data is always on.
1741 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1742
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001743 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001744
1745 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 }
1747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001749 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001750 *
1751 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001752 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001753 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001754 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1755 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001756
1757 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001758 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001759
Robert Greenwalt7b816022014-04-18 15:25:25 -07001760 if (networkAgent.networkCapabilities.hasTransport(
1761 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001762 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1763 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001764 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001765 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001766 } else if (networkAgent.networkCapabilities.hasTransport(
1767 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001768 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1769 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001770 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001771 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001772 } else {
1773 // do not track any other networks
1774 timeout = 0;
1775 }
1776
Robert Greenwalt7b816022014-04-18 15:25:25 -07001777 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001778 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001779 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001780 } catch (Exception e) {
1781 // You shall not crash!
1782 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001783 }
1784 }
1785 }
1786
1787 /**
1788 * Remove data activity tracking when network disconnects.
1789 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001790 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1791 final String iface = networkAgent.linkProperties.getInterfaceName();
1792 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001793
Robert Greenwalt7b816022014-04-18 15:25:25 -07001794 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1795 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001796 try {
1797 // the call fails silently if no idletimer setup for this interface
1798 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001799 } catch (Exception e) {
1800 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001801 }
1802 }
1803 }
1804
1805 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001806 * Reads the network specific MTU size from reources.
1807 * and set it on it's iface.
1808 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001809 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1810 final String iface = newLp.getInterfaceName();
1811 final int mtu = newLp.getMtu();
Pierre Imaiaccd5fc2016-02-08 16:01:40 +09001812 if (oldLp == null && mtu == 0) {
1813 // Silently ignore unset MTU value.
1814 return;
1815 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001816 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1817 if (VDBG) log("identical MTU - not setting");
1818 return;
1819 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001820 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001821 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001822 return;
1823 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001824
w1997615afd812014-08-05 15:18:11 -07001825 // Cannot set MTU without interface name
1826 if (TextUtils.isEmpty(iface)) {
1827 loge("Setting MTU size with null iface.");
1828 return;
1829 }
1830
Robert Greenwalt7b816022014-04-18 15:25:25 -07001831 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001832 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001833 mNetd.setMtu(iface, mtu);
1834 } catch (Exception e) {
1835 Slog.e(TAG, "exception in setMtu()" + e);
1836 }
1837 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001838
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001839 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001840 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1841
1842 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001843 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001844 protected MockableSystemProperties getSystemProperties() {
1845 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001846 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001847
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001848 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1849 if (isDefaultNetwork(nai) == false) {
1850 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001851 }
1852
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001853 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1854 String[] values = null;
1855 if (tcpBufferSizes != null) {
1856 values = tcpBufferSizes.split(",");
1857 }
1858
1859 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001860 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001861 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1862 values = tcpBufferSizes.split(",");
1863 }
1864
1865 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1866
1867 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001868 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001869
1870 final String prefix = "/sys/kernel/ipv4/tcp_";
1871 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1872 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1873 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1874 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1875 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1876 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1877 mCurrentTcpBufferSizes = tcpBufferSizes;
1878 } catch (IOException e) {
1879 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001880 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001881
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001882 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001883 Settings.Global.TCP_DEFAULT_INIT_RWND,
1884 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001885 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1886 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001887 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001888 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001889 }
1890
Mattias Falk8b47b362011-08-23 14:15:13 +02001891 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001892 /*
1893 * Tell the VMs to toss their DNS caches
1894 */
1895 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1896 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001897 /*
1898 * Connectivity events can happen before boot has completed ...
1899 */
1900 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001901 final long ident = Binder.clearCallingIdentity();
1902 try {
1903 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1904 } finally {
1905 Binder.restoreCallingIdentity(ident);
1906 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001907 }
1908
Robert Greenwalt562cc542014-05-15 18:07:26 -07001909 @Override
1910 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001911 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001912 NETWORK_RESTORE_DELAY_PROP_NAME);
1913 if(restoreDefaultNetworkDelayStr != null &&
1914 restoreDefaultNetworkDelayStr.length() != 0) {
1915 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001916 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001917 } catch (NumberFormatException e) {
1918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001920 // if the system property isn't set, use the value for the apn type
1921 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1922
1923 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1924 (mNetConfigs[networkType] != null)) {
1925 ret = mNetConfigs[networkType].restoreTime;
1926 }
1927 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
1929
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001930 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001931 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001932 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001933 }
1934 return false;
1935 }
1936
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001937 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1938 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1939 final long DIAG_TIME_MS = 5000;
1940 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1941 // Start gathering diagnostic information.
1942 netDiags.add(new NetworkDiagnostics(
1943 nai.network,
1944 new LinkProperties(nai.linkProperties), // Must be a copy.
1945 DIAG_TIME_MS));
1946 }
1947
1948 for (NetworkDiagnostics netDiag : netDiags) {
1949 pw.println();
1950 netDiag.waitForMeasurements();
1951 netDiag.dump(pw);
1952 }
1953 }
1954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001956 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1957 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001958 if (mContext.checkCallingOrSelfPermission(
1959 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001961 pw.println("Permission Denial: can't dump ConnectivityService " +
1962 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1963 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 return;
1965 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001966
Erik Kline7747fd42017-05-12 16:52:48 +09001967 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001968 dumpNetworkDiagnostics(pw);
1969 return;
1970 }
Erik Kline379747a2015-06-05 17:47:34 +09001971
Lorenzo Colittie3805462015-06-03 11:18:24 +09001972 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001973 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001974 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001975 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001976 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001977 pw.println();
1978
Paul Jensen85cf78e2015-06-25 13:25:07 -04001979 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001980 pw.print("Active default network: ");
1981 if (defaultNai == null) {
1982 pw.println("none");
1983 } else {
1984 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001986 pw.println();
1987
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001988 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001989 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001990 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1991 pw.println(nai.toString());
1992 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001993 pw.println(String.format(
1994 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1995 nai.numForegroundNetworkRequests(),
1996 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1997 nai.numBackgroundNetworkRequests(),
1998 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001999 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002000 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2001 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002002 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002003 pw.decreaseIndent();
2004 pw.println("Lingered:");
2005 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002006 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002007 pw.decreaseIndent();
2008 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002009 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002010 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002011 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002012
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002013 pw.println("Metered Interfaces:");
2014 pw.increaseIndent();
2015 for (String value : mMeteredIfaces) {
2016 pw.println(value);
2017 }
2018 pw.decreaseIndent();
2019 pw.println();
2020
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002021 pw.print("Restrict background: ");
2022 pw.println(mRestrictBackground);
2023 pw.println();
2024
Felipe Leme46c4fc32016-05-04 09:21:43 -07002025 pw.println("Status for known UIDs:");
2026 pw.increaseIndent();
2027 final int size = mUidRules.size();
2028 for (int i = 0; i < size; i++) {
2029 final int uid = mUidRules.keyAt(i);
2030 pw.print("UID=");
2031 pw.print(uid);
2032 final int uidRules = mUidRules.get(uid, RULE_NONE);
2033 pw.print(" rules=");
2034 pw.print(uidRulesToString(uidRules));
2035 pw.println();
2036 }
2037 pw.println();
2038 pw.decreaseIndent();
2039
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002040 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002041 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002042 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2043 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002044 }
2045 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002046 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002047
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002048 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002049
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002050 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002051 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002052
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002053 pw.println();
2054 mKeepaliveTracker.dump(pw);
2055
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002056 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002057 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002058
Erik Kline7747fd42017-05-12 16:52:48 +09002059 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002060 pw.println();
2061 synchronized (mValidationLogs) {
2062 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002063 for (ValidationLog p : mValidationLogs) {
2064 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002065 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002066 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002067 pw.decreaseIndent();
2068 }
2069 }
Erik Kline7523eb32015-07-09 18:24:03 +09002070
2071 pw.println();
2072 pw.println("mNetworkRequestInfoLogs (most recent first):");
2073 pw.increaseIndent();
2074 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2075 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002076
2077 pw.println();
2078 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2079 pw.increaseIndent();
2080 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2081 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002082
2083 pw.println();
2084 pw.println("NetTransition WakeLock activity (most recent first):");
2085 pw.increaseIndent();
2086 mWakelockLogs.reverseDump(fd, pw, args);
2087 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002091 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002092 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002093 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002094 if (officialNai != null && officialNai.equals(nai)) return true;
2095 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002096 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002097 " - " + nai);
2098 }
2099 return false;
2100 }
2101
Robert Greenwalt42acef32009-08-12 16:08:25 -07002102 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002103 private class NetworkStateTrackerHandler extends Handler {
2104 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002105 super(looper);
2106 }
2107
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002108 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002110 default:
2111 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002112 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002113 handleAsyncChannelHalfConnect(msg);
2114 break;
2115 }
2116 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2117 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2118 if (nai != null) nai.asyncChannel.disconnect();
2119 break;
2120 }
2121 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2122 handleAsyncChannelDisconnected(msg);
2123 break;
2124 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002125 }
2126 return true;
2127 }
2128
2129 private void maybeHandleNetworkAgentMessage(Message msg) {
2130 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2131 if (nai == null) {
2132 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002133 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002134 }
2135 return;
2136 }
2137
2138 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002140 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2141 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002142 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2143 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002144 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002145 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002146 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002147 break;
2148 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002149 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002150 if (VDBG) {
2151 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002152 "; created=" + nai.created +
2153 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002154 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002155 LinkProperties oldLp = nai.linkProperties;
2156 synchronized (nai) {
2157 nai.linkProperties = (LinkProperties)msg.obj;
2158 }
Robin Lee585e2482016-05-01 23:00:00 +01002159 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002160 break;
2161 }
2162 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002163 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002164 updateNetworkInfo(nai, info);
2165 break;
2166 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002167 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002168 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002169 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002170 break;
2171 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002172 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002173 try {
2174 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002175 } catch (Exception e) {
2176 // Never crash!
2177 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002178 }
2179 break;
2180 }
2181 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002182 try {
2183 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002184 } catch (Exception e) {
2185 // Never crash!
2186 loge("Exception in removeVpnUidRanges: " + e);
2187 }
2188 break;
2189 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002190 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002191 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2192 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002193 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002194 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002195 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002196 break;
2197 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002198 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002199 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2200 break;
2201 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002202 }
2203 }
2204
2205 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2206 switch (msg.what) {
2207 default:
2208 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002209 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002210 final NetworkAgentInfo nai;
2211 synchronized (mNetworkForNetId) {
2212 nai = mNetworkForNetId.get(msg.arg2);
2213 }
2214 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002215 final boolean valid =
2216 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002217 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002218 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2219 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002220 if (valid != nai.lastValidated) {
2221 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002222 nai.lastValidated = valid;
2223 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002224 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002225 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2226 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002227 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002228 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002229 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002230 Bundle redirectUrlBundle = new Bundle();
2231 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002232 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002233 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002234 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002235 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002236 if (wasValidated && !nai.lastValidated) {
2237 handleNetworkUnvalidated(nai);
2238 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002239 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002240 break;
2241 }
Paul Jensen869868be2014-05-15 10:33:05 -04002242 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002243 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002244 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002245 final NetworkAgentInfo nai;
2246 synchronized (mNetworkForNetId) {
2247 nai = mNetworkForNetId.get(netId);
2248 }
Calvin On1f64f3f2016-10-11 15:10:46 -07002249 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002250 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002251 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002252 nai.lastCaptivePortalDetected = visible;
2253 nai.everCaptivePortalDetected |= visible;
Calvin On1f64f3f2016-10-11 15:10:46 -07002254 if (nai.lastCaptivePortalDetected &&
2255 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2256 if (DBG) log("Avoiding captive portal network: " + nai.name());
2257 nai.asyncChannel.sendMessage(
2258 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2259 teardownUnneededNetwork(nai);
2260 break;
2261 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002262 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002263 }
2264 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002265 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002266 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002267 if (nai == null) {
2268 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2269 break;
2270 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002271 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002272 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002273 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002274 }
Paul Jensen869868be2014-05-15 10:33:05 -04002275 }
Paul Jensen869868be2014-05-15 10:33:05 -04002276 break;
2277 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002278 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002279 return true;
2280 }
2281
Calvin On1f64f3f2016-10-11 15:10:46 -07002282 private int getCaptivePortalMode() {
2283 return Settings.Global.getInt(mContext.getContentResolver(),
2284 Settings.Global.CAPTIVE_PORTAL_MODE,
2285 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2286 }
2287
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002288 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2289 switch (msg.what) {
2290 default:
2291 return false;
2292 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2293 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2294 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2295 handleLingerComplete(nai);
2296 }
2297 break;
2298 }
2299 }
2300 return true;
2301 }
2302
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002303 @Override
2304 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002305 if (!maybeHandleAsyncChannelMessage(msg) &&
2306 !maybeHandleNetworkMonitorMessage(msg) &&
2307 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002308 maybeHandleNetworkAgentMessage(msg);
2309 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002310 }
2311 }
2312
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002313 private void updateLingerState(NetworkAgentInfo nai, long now) {
2314 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2315 // 2. If the network was lingering and there are now requests, unlinger it.
2316 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2317 // one lingered request, start lingering.
2318 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002319 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002320 if (DBG) log("Unlingering " + nai.name());
2321 nai.unlinger();
2322 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002323 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002324 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002325 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002326 nai.linger();
2327 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2328 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2329 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002330 }
2331
Robert Greenwalt7b816022014-04-18 15:25:25 -07002332 private void handleAsyncChannelHalfConnect(Message msg) {
2333 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002334 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002335 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2336 if (VDBG) log("NetworkFactory connected");
2337 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002338 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002339 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002340 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002341 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002342 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002343 }
2344 } else {
2345 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002346 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002347 }
2348 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2349 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2350 if (VDBG) log("NetworkAgent connected");
2351 // A network agent has requested a connection. Establish the connection.
2352 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2353 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2354 } else {
2355 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002356 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002357 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002358 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002359 synchronized (mNetworkForNetId) {
2360 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002361 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002362 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002363 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002364 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002365 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002366 }
2367 }
2368 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002369
Robert Greenwalt7b816022014-04-18 15:25:25 -07002370 private void handleAsyncChannelDisconnected(Message msg) {
2371 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2372 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002373 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002374 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002375 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002376 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002377 // TODO - if we move the logic to the network agent (have them disconnect
2378 // because they lost all their requests or because their score isn't good)
2379 // then they would disconnect organically, report their new state and then
2380 // disconnect the channel.
2381 if (nai.networkInfo.isConnected()) {
2382 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2383 null, null);
2384 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002385 final boolean wasDefault = isDefaultNetwork(nai);
2386 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002387 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002388 // Log default network disconnection before required book-keeping.
2389 // Let rematchAllNetworksAndRequests() below record a new default network event
2390 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2391 // whose timestamps tell how long it takes to recover a default network.
2392 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002393 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002394 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002395 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2396 // by other networks that are already connected. Perhaps that can be done by
2397 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2398 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002399 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002400 mKeepaliveTracker.handleStopAllKeepalives(nai,
2401 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002402 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002403 mNetworkAgentInfos.remove(msg.replyTo);
2404 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002405 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002406 // Remove the NetworkAgent, but don't mark the netId as
2407 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002408 mNetworkForNetId.remove(nai.network.netId);
2409 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002410 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002411 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2412 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002413 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2414 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2415 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002416 sendUpdatedScoreToFactories(request, 0);
2417 }
2418 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002419 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002420 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002421 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002422 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002423 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002424 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002425 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002426 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002427 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002428 if (nai.created) {
2429 // Tell netd to clean up the configuration for this network
2430 // (routing rules, DNS, etc).
2431 // This may be slow as it requires a lot of netd shelling out to ip and
2432 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2433 // after we've rematched networks with requests which should make a potential
2434 // fallback network the default or requested a new network from the
2435 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2436 // long time.
2437 try {
2438 mNetd.removeNetwork(nai.network.netId);
2439 } catch (Exception e) {
2440 loge("Exception removing network: " + e);
2441 }
2442 }
2443 synchronized (mNetworkForNetId) {
2444 mNetIdInUse.delete(nai.network.netId);
2445 }
2446 } else {
2447 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2448 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002449 }
2450 }
2451
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002452 // If this method proves to be too slow then we can maintain a separate
2453 // pendingIntent => NetworkRequestInfo map.
2454 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2455 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2456 Intent intent = pendingIntent.getIntent();
2457 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2458 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2459 if (existingPendingIntent != null &&
2460 existingPendingIntent.getIntent().filterEquals(intent)) {
2461 return entry.getValue();
2462 }
2463 }
2464 return null;
2465 }
2466
2467 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2468 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2469
2470 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2471 if (existingRequest != null) { // remove the existing request.
2472 if (DBG) log("Replacing " + existingRequest.request + " with "
2473 + nri.request + " because their intents matched.");
2474 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2475 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002476 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002477 }
2478
Erik Klineda4bfa82015-04-30 12:58:40 +09002479 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002480 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002481 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002482 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002483 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002484 if (nri.request.networkCapabilities.hasSignalStrength() &&
2485 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2486 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002487 }
2488 }
2489 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002490 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002491 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002492 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002493 }
2494 }
2495
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002496 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2497 int callingUid) {
2498 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2499 if (nri != null) {
2500 handleReleaseNetworkRequest(nri.request, callingUid);
2501 }
2502 }
2503
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002504 // Determines whether the network is the best (or could become the best, if it validated), for
2505 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2506 // on the value of reason:
2507 //
2508 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2509 // then it should be torn down.
2510 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2511 // then it should be lingered.
2512 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2513 final int numRequests;
2514 switch (reason) {
2515 case TEARDOWN:
2516 numRequests = nai.numRequestNetworkRequests();
2517 break;
2518 case LINGER:
2519 numRequests = nai.numForegroundNetworkRequests();
2520 break;
2521 default:
2522 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2523 return true;
2524 }
2525
2526 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002527 return false;
2528 }
Paul Jensene0988542015-06-25 15:30:08 -04002529 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002530 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2531 // Background requests don't affect lingering.
2532 continue;
2533 }
2534
Paul Jensene0988542015-06-25 15:30:08 -04002535 // If this Network is already the highest scoring Network for a request, or if
2536 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002537 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002538 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002539 // Note that this catches two important cases:
2540 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2541 // is currently satisfying the request. This is desirable when
2542 // cellular ends up validating but WiFi does not.
2543 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002544 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002545 // WiFi ends up validating and out scoring cellular.
2546 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2547 nai.getCurrentScoreAsValidated())) {
2548 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002549 }
2550 }
Paul Jensene0988542015-06-25 15:30:08 -04002551 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002552 }
2553
Erik Klineacdd6392016-07-07 16:50:58 +09002554 private NetworkRequestInfo getNriForAppRequest(
2555 NetworkRequest request, int callingUid, String requestedOperation) {
2556 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2557
Robert Greenwalt9258c642014-03-26 16:47:06 -07002558 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002559 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002560 log(String.format("UID %d attempted to %s for unowned request %s",
2561 callingUid, requestedOperation, nri));
2562 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002563 }
Erik Klineacdd6392016-07-07 16:50:58 +09002564 }
2565
2566 return nri;
2567 }
2568
Erik Kline3841a482015-11-25 12:49:38 +09002569 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002570 if (mNetworkRequests.get(nri.request) == null) {
2571 return;
Erik Kline3841a482015-11-25 12:49:38 +09002572 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002573 if (mNetworkForRequestId.get(nri.request.requestId) != null) {
2574 return;
2575 }
2576 if (VDBG || (DBG && nri.request.isRequest())) {
2577 log("releasing " + nri.request + " (timeout)");
2578 }
2579 handleRemoveNetworkRequest(nri);
2580 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline3841a482015-11-25 12:49:38 +09002581 }
2582
Erik Klineacdd6392016-07-07 16:50:58 +09002583 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002584 final NetworkRequestInfo nri =
2585 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2586 if (nri == null) {
2587 return;
Erik Kline3841a482015-11-25 12:49:38 +09002588 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002589 if (VDBG || (DBG && nri.request.isRequest())) {
2590 log("releasing " + nri.request + " (release request)");
2591 }
2592 handleRemoveNetworkRequest(nri);
Erik Kline3841a482015-11-25 12:49:38 +09002593 }
Erik Klineacdd6392016-07-07 16:50:58 +09002594
Hugo Benichidba33db2017-03-23 22:40:44 +09002595 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002596 nri.unlinkDeathRecipient();
Erik Kline3841a482015-11-25 12:49:38 +09002597 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002598 synchronized (mUidToNetworkRequestCount) {
2599 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2600 if (requests < 1) {
2601 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2602 nri.mUid);
2603 } else if (requests == 1) {
2604 mUidToNetworkRequestCount.removeAt(
2605 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2606 } else {
2607 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2608 }
2609 }
2610 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2611 if (nri.request.isRequest()) {
2612 boolean wasKept = false;
2613 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2614 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002615 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002616 nai.removeRequest(nri.request.requestId);
2617 if (VDBG) {
2618 log(" Removing from current network " + nai.name() +
2619 ", leaving " + nai.numNetworkRequests() + " requests.");
2620 }
2621 // If there are still lingered requests on this network, don't tear it down,
2622 // but resume lingering instead.
2623 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002624 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002625 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2626 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002627 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002628 wasKept = true;
2629 }
2630 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002631 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2632 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002633 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002634 }
Erik Klineacdd6392016-07-07 16:50:58 +09002635 }
2636
2637 // TODO: remove this code once we know that the Slog.wtf is never hit.
2638 //
2639 // Find all networks that are satisfying this request and remove the request
2640 // from their request lists.
2641 // TODO - it's my understanding that for a request there is only a single
2642 // network satisfying it, so this loop is wasteful
2643 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2644 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2645 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2646 otherNai.name() + ", but mNetworkAgentInfos says " +
2647 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002648 }
2649 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002650
Erik Klineacdd6392016-07-07 16:50:58 +09002651 // Maintain the illusion. When this request arrived, we might have pretended
2652 // that a network connected to serve it, even though the network was already
2653 // connected. Now that this request has gone away, we might have to pretend
2654 // that the network disconnected. LegacyTypeTracker will generate that
2655 // phantom disconnect for this type.
2656 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2657 boolean doRemove = true;
2658 if (wasKept) {
2659 // check if any of the remaining requests for this network are for the
2660 // same legacy type - if so, don't remove the nai
2661 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2662 NetworkRequest otherRequest = nai.requestAt(i);
2663 if (otherRequest.legacyType == nri.request.legacyType &&
2664 otherRequest.isRequest()) {
2665 if (DBG) log(" still have other legacy request - leaving");
2666 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002667 }
2668 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002669 }
2670
Erik Klineacdd6392016-07-07 16:50:58 +09002671 if (doRemove) {
2672 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002673 }
2674 }
Erik Klineacdd6392016-07-07 16:50:58 +09002675
2676 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2677 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2678 nri.request);
2679 }
2680 } else {
2681 // listens don't have a singular affectedNetwork. Check all networks to see
2682 // if this listen request applies and remove it.
2683 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2684 nai.removeRequest(nri.request.requestId);
2685 if (nri.request.networkCapabilities.hasSignalStrength() &&
2686 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2687 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2688 }
2689 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002690 }
2691 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002692
Lorenzo Colitti18660282016-07-04 12:55:44 +09002693 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002694 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2695 enforceConnectivityInternalPermission();
2696 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002697 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002698 }
2699
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002700 @Override
2701 public void setAvoidUnvalidated(Network network) {
2702 enforceConnectivityInternalPermission();
2703 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2704 }
2705
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002706 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2707 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2708 " accept=" + accept + " always=" + always);
2709
2710 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2711 if (nai == null) {
2712 // Nothing to do.
2713 return;
2714 }
2715
2716 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002717 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002718 return;
2719 }
2720
2721 if (!nai.networkMisc.explicitlySelected) {
2722 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2723 }
2724
2725 if (accept != nai.networkMisc.acceptUnvalidated) {
2726 int oldScore = nai.getCurrentScore();
2727 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002728 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002729 sendUpdatedScoreToFactories(nai);
2730 }
2731
2732 if (always) {
2733 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002734 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002735 }
2736
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002737 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002738 // Tell the NetworkAgent to not automatically reconnect to the network.
2739 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2740 // Teardown the nework.
2741 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002742 }
2743
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002744 }
2745
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002746 private void handleSetAvoidUnvalidated(Network network) {
2747 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2748 if (nai == null || nai.lastValidated) {
2749 // Nothing to do. The network either disconnected or revalidated.
2750 return;
2751 }
2752 if (!nai.avoidUnvalidated) {
2753 int oldScore = nai.getCurrentScore();
2754 nai.avoidUnvalidated = true;
2755 rematchAllNetworksAndRequests(nai, oldScore);
2756 sendUpdatedScoreToFactories(nai);
2757 }
2758 }
2759
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002760 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002761 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002762 mHandler.sendMessageDelayed(
2763 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2764 PROMPT_UNVALIDATED_DELAY_MS);
2765 }
2766
Hugo Benichic8e9e122016-09-14 23:23:08 +00002767 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002768 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002769 }
2770
Erik Kline065ab6e2016-10-02 18:02:14 +09002771 private void rematchForAvoidBadWifiUpdate() {
2772 rematchAllNetworksAndRequests(null, 0);
2773 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2774 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2775 sendUpdatedScoreToFactories(nai);
2776 }
2777 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002778 }
2779
Erik Kline065ab6e2016-10-02 18:02:14 +09002780 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002781 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002782 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002783 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002784 if (!configRestrict) {
2785 pw.println("Bad Wi-Fi avoidance: unrestricted");
2786 return;
2787 }
2788
2789 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2790 pw.increaseIndent();
2791 pw.println("Config restrict: " + configRestrict);
2792
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002793 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002794 String description;
2795 // Can't use a switch statement because strings are legal case labels, but null is not.
2796 if ("0".equals(value)) {
2797 description = "get stuck";
2798 } else if (value == null) {
2799 description = "prompt";
2800 } else if ("1".equals(value)) {
2801 description = "avoid";
2802 } else {
2803 description = value + " (?)";
2804 }
2805 pw.println("User setting: " + description);
2806 pw.println("Network overrides:");
2807 pw.increaseIndent();
2808 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2809 if (nai.avoidUnvalidated) {
2810 pw.println(nai.name());
2811 }
2812 }
2813 pw.decreaseIndent();
2814 pw.decreaseIndent();
2815 }
2816
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002817 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2818 final String action;
2819 switch (type) {
2820 case NO_INTERNET:
2821 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2822 break;
2823 case LOST_INTERNET:
2824 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2825 break;
2826 default:
2827 Slog.wtf(TAG, "Unknown notification type " + type);
2828 return;
2829 }
2830
2831 Intent intent = new Intent(action);
2832 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2833 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2834 intent.setClassName("com.android.settings",
2835 "com.android.settings.wifi.WifiNoInternetDialog");
2836
2837 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2838 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2839 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2840 }
2841
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002842 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002843 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002844 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2845
2846 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2847 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002848 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002849 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002850 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2851 return;
2852 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002853 showValidationNotification(nai, NotificationType.NO_INTERNET);
2854 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002855
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002856 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2857 NetworkCapabilities nc = nai.networkCapabilities;
2858 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002859
Erik Kline065ab6e2016-10-02 18:02:14 +09002860 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002861 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002862 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2863 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002864 }
2865
Lorenzo Colitti46aa9c02017-01-24 18:08:41 +09002866 @Override
2867 public int getMultipathPreference(Network network) {
2868 enforceAccessPermission();
2869
2870 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2871 if (nai != null && !nai.networkInfo.isMetered()) {
2872 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2873 }
2874
2875 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2876 }
2877
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002878 private class InternalHandler extends Handler {
2879 public InternalHandler(Looper looper) {
2880 super(looper);
2881 }
2882
2883 @Override
2884 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002885 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002886 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002887 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002888 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002889 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002890 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002891 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002892 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002893 break;
2894 }
Jason Monkdecd2952013-10-10 14:02:51 -04002895 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002896 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002897 break;
2898 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002899 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002900 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2901 break;
2902 }
2903 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2904 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002905 break;
2906 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002907 case EVENT_REGISTER_NETWORK_AGENT: {
2908 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2909 break;
2910 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002911 case EVENT_REGISTER_NETWORK_REQUEST:
2912 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002913 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002914 break;
2915 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002916 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2917 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002918 handleRegisterNetworkRequestWithIntent(msg);
2919 break;
2920 }
Erik Kline3841a482015-11-25 12:49:38 +09002921 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2922 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2923 handleTimedOutNetworkRequest(nri);
2924 break;
2925 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002926 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2927 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2928 break;
2929 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002930 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002931 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002932 break;
2933 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002934 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002935 Network network = (Network) msg.obj;
2936 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002937 break;
2938 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002939 case EVENT_SET_AVOID_UNVALIDATED: {
2940 handleSetAvoidUnvalidated((Network) msg.obj);
2941 break;
2942 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002943 case EVENT_PROMPT_UNVALIDATED: {
2944 handlePromptUnvalidated((Network) msg.obj);
2945 break;
2946 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002947 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2948 handleMobileDataAlwaysOn();
2949 break;
2950 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002951 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2952 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2953 mKeepaliveTracker.handleStartKeepalive(msg);
2954 break;
2955 }
2956 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2957 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2958 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2959 int slot = msg.arg1;
2960 int reason = msg.arg2;
2961 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2962 break;
2963 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002964 case EVENT_SYSTEM_READY: {
2965 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2966 nai.networkMonitor.systemReady = true;
2967 }
2968 break;
2969 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002970 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002971 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002972 break;
2973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
2975 }
2976 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002977
2978 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002979 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002980 public int tether(String iface, String callerPkg) {
2981 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002982 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002983 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002984 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002985 } else {
2986 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2987 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002988 }
2989
2990 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002991 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002992 public int untether(String iface, String callerPkg) {
2993 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002994
2995 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002996 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002997 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002998 } else {
2999 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3000 }
3001 }
3002
3003 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003004 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003005 public int getLastTetherError(String iface) {
3006 enforceTetherAccessPermission();
3007
3008 if (isTetheringSupported()) {
3009 return mTethering.getLastTetherError(iface);
3010 } else {
3011 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3012 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003013 }
3014
3015 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003016 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003017 public String[] getTetherableUsbRegexs() {
3018 enforceTetherAccessPermission();
3019 if (isTetheringSupported()) {
3020 return mTethering.getTetherableUsbRegexs();
3021 } else {
3022 return new String[0];
3023 }
3024 }
3025
Lorenzo Colitti18660282016-07-04 12:55:44 +09003026 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003027 public String[] getTetherableWifiRegexs() {
3028 enforceTetherAccessPermission();
3029 if (isTetheringSupported()) {
3030 return mTethering.getTetherableWifiRegexs();
3031 } else {
3032 return new String[0];
3033 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003034 }
3035
Lorenzo Colitti18660282016-07-04 12:55:44 +09003036 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003037 public String[] getTetherableBluetoothRegexs() {
3038 enforceTetherAccessPermission();
3039 if (isTetheringSupported()) {
3040 return mTethering.getTetherableBluetoothRegexs();
3041 } else {
3042 return new String[0];
3043 }
3044 }
3045
Lorenzo Colitti18660282016-07-04 12:55:44 +09003046 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003047 public int setUsbTethering(boolean enable, String callerPkg) {
3048 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003049 if (isTetheringSupported()) {
3050 return mTethering.setUsbTethering(enable);
3051 } else {
3052 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3053 }
3054 }
3055
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003056 // TODO - move iface listing, queries, etc to new module
3057 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003058 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003059 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003060 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003061 return mTethering.getTetherableIfaces();
3062 }
3063
Lorenzo Colitti18660282016-07-04 12:55:44 +09003064 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003065 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003066 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003067 return mTethering.getTetheredIfaces();
3068 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003069
Lorenzo Colitti18660282016-07-04 12:55:44 +09003070 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003071 public String[] getTetheringErroredIfaces() {
3072 enforceTetherAccessPermission();
3073 return mTethering.getErroredIfaces();
3074 }
3075
Lorenzo Colitti18660282016-07-04 12:55:44 +09003076 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003077 public String[] getTetheredDhcpRanges() {
3078 enforceConnectivityInternalPermission();
3079 return mTethering.getTetheredDhcpRanges();
3080 }
3081
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003082 // if ro.tether.denied = true we default to no tethering
3083 // gservices could set the secure setting to 1 though to enable it on a build where it
3084 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003085 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003086 public boolean isTetheringSupported() {
3087 enforceTetherAccessPermission();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003088 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3089 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3090 Settings.Global.TETHER_SUPPORTED, defaultVal));
3091 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003092 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003093
3094 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3095 boolean adminUser = false;
3096 final long token = Binder.clearCallingIdentity();
3097 try {
3098 adminUser = mUserManager.isAdminUser();
3099 } finally {
3100 Binder.restoreCallingIdentity(token);
3101 }
3102
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003103 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003104 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003105
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003106 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003107 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3108 String callerPkg) {
3109 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003110 if (!isTetheringSupported()) {
3111 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3112 return;
3113 }
3114 mTethering.startTethering(type, receiver, showProvisioningUi);
3115 }
3116
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003117 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003118 public void stopTethering(int type, String callerPkg) {
3119 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003120 mTethering.stopTethering(type);
3121 }
3122
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003123 // Called when we lose the default network and have no replacement yet.
3124 // This will automatically be cleared after X seconds or a new default network
3125 // becomes CONNECTED, whichever happens first. The timer is started by the
3126 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003127 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003128 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003129 if (mNetTransitionWakeLock.isHeld()) {
3130 return;
3131 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003132 mNetTransitionWakeLock.acquire();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003133 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003134 mWakelockLogs.log("ACQUIRE for " + forWhom);
3135 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3136 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003137 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003138
Hugo Benichi4c31b342017-03-30 23:18:10 +09003139 // Called when we gain a new default network to release the network transition wakelock in a
3140 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3141 // message is cancelled.
3142 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003143 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003144 if (!mNetTransitionWakeLock.isHeld()) {
3145 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003146 }
3147 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003148 // Cancel self timeout on wakelock hold.
3149 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3150 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3151 mHandler.sendMessageDelayed(msg, 1000);
3152 }
3153
3154 // Called when either message of ensureNetworkTransitionWakelock or
3155 // scheduleReleaseNetworkTransitionWakelock is processed.
3156 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3157 String event = eventName(eventId);
3158 synchronized (this) {
3159 if (!mNetTransitionWakeLock.isHeld()) {
3160 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3161 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3162 return;
3163 }
3164 mNetTransitionWakeLock.release();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003165 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003166 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003167 }
3168
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003169 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003170 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003171 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003172 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003173 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003174 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003175 }
3176
Lorenzo Colitti18660282016-07-04 12:55:44 +09003177 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003178 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003179 enforceAccessPermission();
3180 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003181 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003182 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003183 mHandler.sendMessage(
3184 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3185 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003186
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003187 private void handleReportNetworkConnectivity(
3188 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi29551722017-04-06 16:01:44 +09003189 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003190 if (network == null) {
3191 nai = getDefaultNetwork();
3192 } else {
3193 nai = getNetworkAgentInfoForNetwork(network);
3194 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003195 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3196 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3197 return;
3198 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003199 // Revalidate if the app report does not match our current validated state.
Hugo Benichi29551722017-04-06 16:01:44 +09003200 if (hasConnectivity == nai.lastValidated) {
3201 return;
3202 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003203 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003204 int netid = nai.network.netId;
3205 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003206 }
Hugo Benichi29551722017-04-06 16:01:44 +09003207 // Validating a network that has not yet connected could result in a call to
3208 // rematchNetworkAndRequests() which is not meant to work on such networks.
3209 if (!nai.everConnected) {
3210 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003211 }
Hugo Benichi29551722017-04-06 16:01:44 +09003212 LinkProperties lp = getLinkProperties(nai);
3213 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3214 return;
3215 }
3216 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003217 }
3218
Paul Jensencee9b512015-05-06 07:32:40 -04003219 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003220 // this information is already available as a world read/writable jvm property
3221 // so this API change wouldn't have a benifit. It also breaks the passing
3222 // of proxy info to all the JVMs.
3223 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003224 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003225 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003226 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3227 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003228 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003229 }
3230
Lorenzo Colitti18660282016-07-04 12:55:44 +09003231 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003232 public ProxyInfo getProxyForNetwork(Network network) {
3233 if (network == null) return getDefaultProxy();
3234 final ProxyInfo globalProxy = getGlobalProxy();
3235 if (globalProxy != null) return globalProxy;
3236 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3237 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3238 // caller may not have.
3239 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3240 if (nai == null) return null;
3241 synchronized (nai) {
3242 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3243 if (proxyInfo == null) return null;
3244 return new ProxyInfo(proxyInfo);
3245 }
3246 }
3247
Paul Jensene0bef712014-12-10 15:12:18 -05003248 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3249 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3250 // proxy is null then there is no proxy in place).
3251 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3252 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3253 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3254 proxy = null;
3255 }
3256 return proxy;
3257 }
3258
3259 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3260 // better for determining if a new proxy broadcast is necessary:
3261 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3262 // avoid unnecessary broadcasts.
3263 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3264 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3265 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3266 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3267 // all set.
3268 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3269 a = canonicalizeProxyInfo(a);
3270 b = canonicalizeProxyInfo(b);
3271 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3272 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3273 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3274 }
3275
Jason Monk207900c2014-04-25 15:00:09 -04003276 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003277 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003278
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003279 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003280 if (proxyProperties == mGlobalProxy) return;
3281 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3282 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3283
3284 String host = "";
3285 int port = 0;
3286 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003287 String pacFileUrl = "";
3288 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003289 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003290 if (!proxyProperties.isValid()) {
3291 if (DBG)
3292 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3293 return;
3294 }
Jason Monk207900c2014-04-25 15:00:09 -04003295 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003296 host = mGlobalProxy.getHost();
3297 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003298 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003299 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003300 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003301 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003302 } else {
3303 mGlobalProxy = null;
3304 }
3305 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003306 final long token = Binder.clearCallingIdentity();
3307 try {
3308 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3309 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3310 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3311 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003312 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003313 } finally {
3314 Binder.restoreCallingIdentity(token);
3315 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003316
Jason Monkcf0f97a2014-10-02 15:39:38 -04003317 if (mGlobalProxy == null) {
3318 proxyProperties = mDefaultProxy;
3319 }
3320 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003321 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003322 }
3323
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003324 private void loadGlobalProxy() {
3325 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003326 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3327 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3328 String exclList = Settings.Global.getString(res,
3329 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003330 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3331 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003332 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003333 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003334 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003335 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003336 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003337 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003338 if (!proxyProperties.isValid()) {
3339 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3340 return;
3341 }
3342
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003343 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003344 mGlobalProxy = proxyProperties;
3345 }
3346 }
3347 }
3348
Jason Monk207900c2014-04-25 15:00:09 -04003349 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003350 // this information is already available as a world read/writable jvm property
3351 // so this API change wouldn't have a benifit. It also breaks the passing
3352 // of proxy info to all the JVMs.
3353 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003354 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003355 return mGlobalProxy;
3356 }
3357 }
3358
Jason Monk207900c2014-04-25 15:00:09 -04003359 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003360 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003361 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003362 proxy = null;
3363 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003364 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003365 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003366 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003367 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003368 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3369 return;
3370 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003371
3372 // This call could be coming from the PacManager, containing the port of the local
3373 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3374 // global (to get the correct local port), and send a broadcast.
3375 // TODO: Switch PacManager to have its own message to send back rather than
3376 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003377 if ((mGlobalProxy != null) && (proxy != null)
3378 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003379 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3380 mGlobalProxy = proxy;
3381 sendProxyBroadcast(mGlobalProxy);
3382 return;
3383 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003384 mDefaultProxy = proxy;
3385
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003386 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003387 if (!mDefaultProxyDisabled) {
3388 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003389 }
3390 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003391 }
3392
Paul Jensene0bef712014-12-10 15:12:18 -05003393 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3394 // This method gets called when any network changes proxy, but the broadcast only ever contains
3395 // the default proxy (even if it hasn't changed).
3396 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3397 // world where an app might be bound to a non-default network.
3398 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3399 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3400 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3401
3402 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3403 sendProxyBroadcast(getDefaultProxy());
3404 }
3405 }
3406
Robert Greenwalt434203a2010-10-11 16:00:27 -07003407 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003408 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3409 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003410 if (!TextUtils.isEmpty(proxy)) {
3411 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003412 if (data.length == 0) {
3413 return;
3414 }
3415
Robert Greenwalt434203a2010-10-11 16:00:27 -07003416 String proxyHost = data[0];
3417 int proxyPort = 8080;
3418 if (data.length > 1) {
3419 try {
3420 proxyPort = Integer.parseInt(data[1]);
3421 } catch (NumberFormatException e) {
3422 return;
3423 }
3424 }
Jason Monk207900c2014-04-25 15:00:09 -04003425 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003426 setGlobalProxy(p);
3427 }
3428 }
3429
Jason Monk207900c2014-04-25 15:00:09 -04003430 private void sendProxyBroadcast(ProxyInfo proxy) {
3431 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003432 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003433 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003434 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003435 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3436 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003437 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003438 final long ident = Binder.clearCallingIdentity();
3439 try {
3440 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3441 } finally {
3442 Binder.restoreCallingIdentity(ident);
3443 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003444 }
3445
3446 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003447 final private HashMap<Uri, Integer> mUriEventMap;
3448 final private Context mContext;
3449 final private Handler mHandler;
3450
3451 SettingsObserver(Context context, Handler handler) {
3452 super(null);
3453 mUriEventMap = new HashMap<Uri, Integer>();
3454 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003455 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003456 }
3457
Erik Klineda4bfa82015-04-30 12:58:40 +09003458 void observe(Uri uri, int what) {
3459 mUriEventMap.put(uri, what);
3460 final ContentResolver resolver = mContext.getContentResolver();
3461 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003462 }
3463
3464 @Override
3465 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003466 Slog.wtf(TAG, "Should never be reached.");
3467 }
3468
3469 @Override
3470 public void onChange(boolean selfChange, Uri uri) {
3471 final Integer what = mUriEventMap.get(uri);
3472 if (what != null) {
3473 mHandler.obtainMessage(what.intValue()).sendToTarget();
3474 } else {
3475 loge("No matching event to send for URI=" + uri);
3476 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003477 }
3478 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003479
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003480 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003481 Slog.d(TAG, s);
3482 }
3483
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003484 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003485 Slog.e(TAG, s);
3486 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003487
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003488 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003489 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003490 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3491 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3492 *
3493 * @param oldPackage Package name of the application which currently controls VPN, which will
3494 * be replaced. If there is no such application, this should should either be
3495 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3496 * @param newPackage Package name of the application which should gain control of VPN, or
3497 * {@code null} to disable.
3498 * @param userId User for whom to prepare the new VPN.
3499 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003500 * @hide
3501 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003502 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003503 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3504 int userId) {
3505 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003506 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003507
Hugo Benichi20035e02017-04-26 14:53:28 +09003508 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003509 Vpn vpn = mVpns.get(userId);
3510 if (vpn != null) {
3511 return vpn.prepare(oldPackage, newPackage);
3512 } else {
3513 return false;
3514 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003515 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003516 }
3517
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003518 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003519 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3520 * This method is used by system-privileged apps.
3521 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3522 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3523 *
3524 * @param packageName The package for which authorization state should change.
3525 * @param userId User for whom {@code packageName} is installed.
3526 * @param authorized {@code true} if this app should be able to start a VPN connection without
3527 * explicit user approval, {@code false} if not.
3528 *
Jeff Davidson05542602014-08-11 14:07:27 -07003529 * @hide
3530 */
3531 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003532 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3533 enforceCrossUserPermission(userId);
3534
Hugo Benichi20035e02017-04-26 14:53:28 +09003535 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003536 Vpn vpn = mVpns.get(userId);
3537 if (vpn != null) {
3538 vpn.setPackageAuthorization(packageName, authorized);
3539 }
Jeff Davidson05542602014-08-11 14:07:27 -07003540 }
3541 }
3542
3543 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003544 * Configure a TUN interface and return its file descriptor. Parameters
3545 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003546 * and not available in ConnectivityManager. Permissions are checked in
3547 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003548 * @hide
3549 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003550 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003551 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003552 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003553 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003554 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003555 return mVpns.get(user).establish(config);
3556 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003557 }
3558
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003559 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003560 * Start legacy VPN, controlling native daemons as needed. Creates a
3561 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003562 */
3563 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003564 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003565 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003566 final LinkProperties egress = getActiveLinkProperties();
3567 if (egress == null) {
3568 throw new IllegalStateException("Missing active network connection");
3569 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003570 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003571 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003572 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3573 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003574 }
3575
3576 /**
3577 * Return the information of the ongoing legacy VPN. This method is used
3578 * by VpnSettings and not available in ConnectivityManager. Permissions
3579 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003580 */
3581 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003582 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3583 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003584
Hugo Benichi20035e02017-04-26 14:53:28 +09003585 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003586 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003587 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003588 }
3589
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003590 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003591 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3592 * and not available in ConnectivityManager.
3593 */
3594 @Override
3595 public VpnInfo[] getAllVpnInfo() {
3596 enforceConnectivityInternalPermission();
3597 if (mLockdownEnabled) {
3598 return new VpnInfo[0];
3599 }
3600
Hugo Benichi20035e02017-04-26 14:53:28 +09003601 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003602 List<VpnInfo> infoList = new ArrayList<>();
3603 for (int i = 0; i < mVpns.size(); i++) {
3604 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3605 if (info != null) {
3606 infoList.add(info);
3607 }
3608 }
3609 return infoList.toArray(new VpnInfo[infoList.size()]);
3610 }
3611 }
3612
3613 /**
3614 * @return VPN information for accounting, or null if we can't retrieve all required
3615 * information, e.g primary underlying iface.
3616 */
3617 @Nullable
3618 private VpnInfo createVpnInfo(Vpn vpn) {
3619 VpnInfo info = vpn.getVpnInfo();
3620 if (info == null) {
3621 return null;
3622 }
3623 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3624 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3625 // the underlyingNetworks list.
3626 if (underlyingNetworks == null) {
3627 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3628 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3629 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3630 }
3631 } else if (underlyingNetworks.length > 0) {
3632 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3633 if (linkProperties != null) {
3634 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3635 }
3636 }
3637 return info.primaryUnderlyingIface == null ? null : info;
3638 }
3639
3640 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003641 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3642 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003643 * Permissions are checked in Vpn class.
3644 * @hide
3645 */
3646 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003647 public VpnConfig getVpnConfig(int userId) {
3648 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003649 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003650 Vpn vpn = mVpns.get(userId);
3651 if (vpn != null) {
3652 return vpn.getVpnConfig();
3653 } else {
3654 return null;
3655 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003656 }
3657 }
3658
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003659 @Override
3660 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003661 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3662 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3663 return false;
3664 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003665
3666 // Tear down existing lockdown if profile was removed
3667 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3668 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003669 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3670 if (profileTag == null) {
3671 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3672 return false;
3673 }
3674 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003675 final VpnProfile profile = VpnProfile.decode(
3676 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003677 if (profile == null) {
3678 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3679 setLockdownTracker(null);
3680 return true;
3681 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003682 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003683 synchronized (mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003684 Vpn vpn = mVpns.get(user);
3685 if (vpn == null) {
3686 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3687 return false;
3688 }
3689 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003690 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003691 } else {
3692 setLockdownTracker(null);
3693 }
3694
3695 return true;
3696 }
3697
3698 /**
3699 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3700 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3701 */
3702 private void setLockdownTracker(LockdownVpnTracker tracker) {
3703 // Shutdown any existing tracker
3704 final LockdownVpnTracker existing = mLockdownTracker;
3705 mLockdownTracker = null;
3706 if (existing != null) {
3707 existing.shutdown();
3708 }
3709
Robin Leec3736bc2017-03-10 16:19:54 +00003710 if (tracker != null) {
3711 mLockdownTracker = tracker;
3712 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003713 }
3714 }
3715
3716 private void throwIfLockdownEnabled() {
3717 if (mLockdownEnabled) {
3718 throw new IllegalStateException("Unavailable in lockdown mode");
3719 }
3720 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003721
Robin Lee244ce8e2016-01-05 18:03:46 +00003722 /**
Robin Lee17e61832016-05-09 13:46:28 +01003723 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3724 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003725 *
Robin Lee17e61832016-05-09 13:46:28 +01003726 * @return {@code true} if the service was started, the service was already connected, or there
3727 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003728 */
Robin Lee17e61832016-05-09 13:46:28 +01003729 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003730 synchronized (mVpns) {
3731 Vpn vpn = mVpns.get(userId);
3732 if (vpn == null) {
3733 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3734 // exists already.
3735 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3736 return false;
3737 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003738
Robin Lee812800c2016-05-13 15:38:08 +01003739 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003740 }
3741 }
3742
3743 @Override
Robin Leedc679712016-05-03 13:23:03 +01003744 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003745 enforceConnectivityInternalPermission();
3746 enforceCrossUserPermission(userId);
3747
3748 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3749 if (LockdownVpnTracker.isEnabled()) {
3750 return false;
3751 }
3752
Robin Lee244ce8e2016-01-05 18:03:46 +00003753 synchronized (mVpns) {
3754 Vpn vpn = mVpns.get(userId);
3755 if (vpn == null) {
3756 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3757 return false;
3758 }
Robin Lee17e61832016-05-09 13:46:28 +01003759 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003760 return false;
3761 }
Robin Lee17e61832016-05-09 13:46:28 +01003762 if (!startAlwaysOnVpn(userId)) {
3763 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003764 return false;
3765 }
3766 }
3767 return true;
3768 }
3769
3770 @Override
3771 public String getAlwaysOnVpnPackage(int userId) {
3772 enforceConnectivityInternalPermission();
3773 enforceCrossUserPermission(userId);
3774
3775 synchronized (mVpns) {
3776 Vpn vpn = mVpns.get(userId);
3777 if (vpn == null) {
3778 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3779 return null;
3780 }
3781 return vpn.getAlwaysOnPackage();
3782 }
3783 }
3784
Wink Savilleab9321d2013-06-29 21:10:57 -07003785 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003786 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003787 // TODO: Remove? Any reason to trigger a provisioning check?
3788 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003789 }
3790
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003791 /** Location to an updatable file listing carrier provisioning urls.
3792 * An example:
3793 *
3794 * <?xml version="1.0" encoding="utf-8"?>
3795 * <provisioningUrls>
3796 * <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 -07003797 * </provisioningUrls>
3798 */
3799 private static final String PROVISIONING_URL_PATH =
3800 "/data/misc/radio/provisioning_urls.xml";
3801 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003802
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003803 /** XML tag for root element. */
3804 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3805 /** XML tag for individual url */
3806 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003807 /** XML attribute for mcc */
3808 private static final String ATTR_MCC = "mcc";
3809 /** XML attribute for mnc */
3810 private static final String ATTR_MNC = "mnc";
3811
Paul Jensen434dde82015-06-11 09:43:30 -04003812 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003813 FileReader fileReader = null;
3814 XmlPullParser parser = null;
3815 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003816
3817 try {
3818 fileReader = new FileReader(mProvisioningUrlFile);
3819 parser = Xml.newPullParser();
3820 parser.setInput(fileReader);
3821 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3822
3823 while (true) {
3824 XmlUtils.nextElement(parser);
3825
3826 String element = parser.getName();
3827 if (element == null) break;
3828
Paul Jensen434dde82015-06-11 09:43:30 -04003829 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003830 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3831 try {
3832 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3833 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3834 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3835 parser.next();
3836 if (parser.getEventType() == XmlPullParser.TEXT) {
3837 return parser.getText();
3838 }
3839 }
3840 }
3841 } catch (NumberFormatException e) {
3842 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3843 }
3844 }
3845 }
3846 return null;
3847 } catch (FileNotFoundException e) {
3848 loge("Carrier Provisioning Urls file not found");
3849 } catch (XmlPullParserException e) {
3850 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3851 } catch (IOException e) {
3852 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3853 } finally {
3854 if (fileReader != null) {
3855 try {
3856 fileReader.close();
3857 } catch (IOException e) {}
3858 }
3859 }
3860 return null;
3861 }
3862
Wink Saville42d4f082013-07-20 20:31:59 -07003863 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003864 public String getMobileProvisioningUrl() {
3865 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003866 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003867 if (TextUtils.isEmpty(url)) {
3868 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003869 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003870 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003871 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003872 }
Wink Saville8cf35602013-07-10 23:00:07 -07003873 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003874 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003875 String phoneNumber = mTelephonyManager.getLine1Number();
3876 if (TextUtils.isEmpty(phoneNumber)) {
3877 phoneNumber = "0000000000";
3878 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003879 url = String.format(url,
3880 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3881 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003882 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003883 }
3884
Wink Savilleab9321d2013-06-29 21:10:57 -07003885 return url;
3886 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003887
Wink Saville948282b2013-08-29 08:55:16 -07003888 @Override
3889 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003890 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003891 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003892 final long ident = Binder.clearCallingIdentity();
3893 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003894 // Concatenate the range of types onto the range of NetIDs.
3895 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3896 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003897 } finally {
3898 Binder.restoreCallingIdentity(ident);
3899 }
Wink Saville948282b2013-08-29 08:55:16 -07003900 }
Wink Saville7788c612013-08-29 14:57:08 -07003901
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003902 @Override
3903 public void setAirplaneMode(boolean enable) {
3904 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003905 final long ident = Binder.clearCallingIdentity();
3906 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003907 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003908 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003909 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3910 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003911 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003912 } finally {
3913 Binder.restoreCallingIdentity(ident);
3914 }
3915 }
3916
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003917 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003918 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003919 Vpn userVpn = mVpns.get(userId);
3920 if (userVpn != null) {
3921 loge("Starting user already has a VPN");
3922 return;
3923 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003924 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003925 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003926 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003927 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3928 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003929 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003930 }
3931
3932 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003933 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003934 Vpn userVpn = mVpns.get(userId);
3935 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003936 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003937 return;
3938 }
Robin Lee17e61832016-05-09 13:46:28 +01003939 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003940 mVpns.delete(userId);
3941 }
3942 }
3943
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003944 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003945 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003946 final int vpnsSize = mVpns.size();
3947 for (int i = 0; i < vpnsSize; i++) {
3948 Vpn vpn = mVpns.valueAt(i);
3949 vpn.onUserAdded(userId);
3950 }
3951 }
3952 }
3953
3954 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003955 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003956 final int vpnsSize = mVpns.size();
3957 for (int i = 0; i < vpnsSize; i++) {
3958 Vpn vpn = mVpns.valueAt(i);
3959 vpn.onUserRemoved(userId);
3960 }
3961 }
3962 }
3963
Robin Lee89e7a692016-02-29 14:38:17 +00003964 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003965 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3966 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3967 updateLockdownVpn();
3968 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003969 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003970 }
3971 }
3972
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003973 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3974 @Override
3975 public void onReceive(Context context, Intent intent) {
3976 final String action = intent.getAction();
3977 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3978 if (userId == UserHandle.USER_NULL) return;
3979
Robin Lee323f29d2016-05-04 16:38:06 +01003980 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003981 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003982 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003983 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003984 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3985 onUserAdded(userId);
3986 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3987 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003988 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3989 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003990 }
3991 }
3992 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003993
Robin Lee95204e02017-01-27 11:59:22 +00003994 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3995 @Override
3996 public void onReceive(Context context, Intent intent) {
3997 // Try creating lockdown tracker, since user present usually means
3998 // unlocked keystore.
3999 updateLockdownVpn();
4000 mContext.unregisterReceiver(this);
4001 }
4002 };
4003
Robert Greenwalta67be032014-05-16 15:49:14 -07004004 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4005 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004006 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4007 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004008
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004009 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4010 // Map from UID to number of NetworkRequests that UID has filed.
4011 @GuardedBy("mUidToNetworkRequestCount")
4012 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4013
Robert Greenwalta67be032014-05-16 15:49:14 -07004014 private static class NetworkFactoryInfo {
4015 public final String name;
4016 public final Messenger messenger;
4017 public final AsyncChannel asyncChannel;
4018
4019 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4020 this.name = name;
4021 this.messenger = messenger;
4022 this.asyncChannel = asyncChannel;
4023 }
4024 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004025
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004026 private void ensureNetworkRequestHasType(NetworkRequest request) {
4027 if (request.type == NetworkRequest.Type.NONE) {
4028 throw new IllegalArgumentException(
4029 "All NetworkRequests in ConnectivityService must have a type");
4030 }
4031 }
4032
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004033 /**
4034 * Tracks info about the requester.
4035 * Also used to notice when the calling process dies so we can self-expire
4036 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004037 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004038 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004039 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004040 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004041 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004042 final int mPid;
4043 final int mUid;
4044 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004045
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004046 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004047 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004048 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004049 mPendingIntent = pi;
4050 messenger = null;
4051 mBinder = null;
4052 mPid = getCallingPid();
4053 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004054 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004055 }
4056
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004057 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004058 super();
4059 messenger = m;
4060 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004061 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004062 mBinder = binder;
4063 mPid = getCallingPid();
4064 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004065 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004066 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004067
4068 try {
4069 mBinder.linkToDeath(this, 0);
4070 } catch (RemoteException e) {
4071 binderDied();
4072 }
4073 }
4074
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004075 private void enforceRequestCountLimit() {
4076 synchronized (mUidToNetworkRequestCount) {
4077 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4078 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004079 throw new ServiceSpecificException(
4080 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004081 }
4082 mUidToNetworkRequestCount.put(mUid, networkRequests);
4083 }
4084 }
4085
Robert Greenwalt9258c642014-03-26 16:47:06 -07004086 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004087 if (mBinder != null) {
4088 mBinder.unlinkToDeath(this, 0);
4089 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004090 }
4091
4092 public void binderDied() {
4093 log("ConnectivityService NetworkRequestInfo binderDied(" +
4094 request + ", " + mBinder + ")");
4095 releaseNetworkRequest(request);
4096 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004097
4098 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004099 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004100 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004101 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004102 }
4103
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004104 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4105 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4106 if (badCapability != null) {
4107 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004108 }
4109 }
4110
Erik Kline9d598e12015-07-13 16:37:51 +09004111 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004112 final SortedSet<Integer> thresholds = new TreeSet();
4113 synchronized (nai) {
4114 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4115 if (nri.request.networkCapabilities.hasSignalStrength() &&
4116 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4117 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4118 }
4119 }
4120 }
Erik Kline9d598e12015-07-13 16:37:51 +09004121 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004122 }
4123
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004124 private void updateSignalStrengthThresholds(
4125 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4126 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004127 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004128 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4129
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004130 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004131 String detail;
4132 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4133 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4134 } else {
4135 detail = reason;
4136 }
4137 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4138 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4139 }
4140
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004141 nai.asyncChannel.sendMessage(
4142 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004143 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004144 }
4145
Etan Cohen859748f2017-04-03 17:42:34 -07004146 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4147 if (nc == null) {
4148 return;
4149 }
4150 NetworkSpecifier ns = nc.getNetworkSpecifier();
4151 if (ns == null) {
4152 return;
4153 }
4154 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4155 ns.assertValidFromUid(Binder.getCallingUid());
4156 }
4157
Robert Greenwalt9258c642014-03-26 16:47:06 -07004158 @Override
4159 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004160 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004161 final NetworkRequest.Type type = (networkCapabilities == null)
4162 ? NetworkRequest.Type.TRACK_DEFAULT
4163 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004164 // If the requested networkCapabilities is null, take them instead from
4165 // the default network request. This allows callers to keep track of
4166 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004167 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004168 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4169 enforceAccessPermission();
4170 } else {
4171 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4172 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004173 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4174 // of the app when the request is filed, but we never change the request if the app
4175 // changes network state. http://b/29964605
4176 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004177 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004178 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004179
Etan Cohenba07c8c2017-02-05 10:42:27 -08004180 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004181 throw new IllegalArgumentException("Bad timeout specified");
4182 }
Etan Cohen859748f2017-04-03 17:42:34 -07004183 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004184
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004185 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004186 nextNetworkRequestId(), type);
4187 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004188 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004189
4190 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004191 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004192 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004193 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194 }
4195 return networkRequest;
4196 }
4197
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004198 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004199 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004200 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004201 } else {
4202 enforceChangePermission();
4203 }
4204 }
4205
fenglub15e72b2015-03-20 11:29:56 -07004206 @Override
fengludb571472015-04-21 17:12:05 -07004207 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004208 enforceAccessPermission();
4209 NetworkAgentInfo nai = null;
4210 if (network == null) {
4211 return false;
4212 }
4213 synchronized (mNetworkForNetId) {
4214 nai = mNetworkForNetId.get(network.netId);
4215 }
4216 if (nai != null) {
4217 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4218 return true;
4219 }
4220 return false;
4221 }
4222
Felipe Lemeee27cab2016-06-20 16:36:29 -07004223 private boolean isSystem(int uid) {
4224 return uid < Process.FIRST_APPLICATION_UID;
4225 }
fenglub15e72b2015-03-20 11:29:56 -07004226
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004227 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004228 final int uid = Binder.getCallingUid();
4229 if (isSystem(uid)) {
4230 return;
4231 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004232 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004233 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004234 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004235 synchronized(mRulesLock) {
4236 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4237 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004238 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4239 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004240 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004241 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004242 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004243 }
4244 }
4245 }
4246
Robert Greenwalt9258c642014-03-26 16:47:06 -07004247 @Override
4248 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4249 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004250 checkNotNull(operation, "PendingIntent cannot be null.");
4251 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4252 enforceNetworkRequestPermissions(networkCapabilities);
4253 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004254 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004255 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004256
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004257 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004258 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4259 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004260 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004261 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4262 nri));
4263 return networkRequest;
4264 }
4265
Jeremy Joslin79294842014-12-03 17:15:28 -08004266 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4267 mHandler.sendMessageDelayed(
4268 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4269 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4270 }
4271
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004272 @Override
4273 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004274 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004275 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4276 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004277 }
4278
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004279 // In order to implement the compatibility measure for pre-M apps that call
4280 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4281 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4282 // This ensures it has permission to do so.
4283 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4284 if (nc == null) {
4285 return false;
4286 }
4287 int[] transportTypes = nc.getTransportTypes();
4288 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4289 return false;
4290 }
4291 try {
4292 mContext.enforceCallingOrSelfPermission(
4293 android.Manifest.permission.ACCESS_WIFI_STATE,
4294 "ConnectivityService");
4295 } catch (SecurityException e) {
4296 return false;
4297 }
4298 return true;
4299 }
4300
Robert Greenwalt9258c642014-03-26 16:47:06 -07004301 @Override
4302 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4303 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004304 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4305 enforceAccessPermission();
4306 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004307
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004308 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4309 if (!ConnectivityManager.checkChangePermission(mContext)) {
4310 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4311 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4312 // onLost and onAvailable callbacks when networks move in and out of the background.
4313 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4314 // can't request networks.
4315 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4316 }
Etan Cohen859748f2017-04-03 17:42:34 -07004317 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004318
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004319 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004320 NetworkRequest.Type.LISTEN);
4321 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004322 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004323
4324 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4325 return networkRequest;
4326 }
4327
4328 @Override
4329 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4330 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004331 checkNotNull(operation, "PendingIntent cannot be null.");
4332 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4333 enforceAccessPermission();
4334 }
Etan Cohen859748f2017-04-03 17:42:34 -07004335 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004336
Erik Kline7523eb32015-07-09 18:24:03 +09004337 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004338 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4339 NetworkRequest.Type.LISTEN);
4340 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004341 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004342
4343 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004344 }
4345
Erik Klineacdd6392016-07-07 16:50:58 +09004346 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004347 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004348 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004349 mHandler.sendMessage(mHandler.obtainMessage(
4350 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004351 }
4352
4353 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004354 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004355 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004356 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4357 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004358 }
4359
Robert Greenwalta67be032014-05-16 15:49:14 -07004360 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004361 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004362 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4363 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4364 }
4365
4366 @Override
4367 public void unregisterNetworkFactory(Messenger messenger) {
4368 enforceConnectivityInternalPermission();
4369 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4370 }
4371
4372 private void handleUnregisterNetworkFactory(Messenger messenger) {
4373 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4374 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004375 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004376 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004377 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004378 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004379 }
4380
Robert Greenwalt7b816022014-04-18 15:25:25 -07004381 /**
4382 * NetworkAgentInfo supporting a request by requestId.
4383 * These have already been vetted (their Capabilities satisfy the request)
4384 * and the are the highest scored network available.
4385 * the are keyed off the Requests requestId.
4386 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004387 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004388 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4389 new SparseArray<NetworkAgentInfo>();
4390
Paul Jensen31a94f42015-02-13 14:18:39 -05004391 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4392 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004393 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4394 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004395 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4396 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4397 // there may not be a strict 1:1 correlation between the two.
4398 @GuardedBy("mNetworkForNetId")
4399 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004400
Robert Greenwalt7b816022014-04-18 15:25:25 -07004401 // NetworkAgentInfo keyed off its connecting messenger
4402 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004403 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004404 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4405 new HashMap<Messenger, NetworkAgentInfo>();
4406
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004407 @GuardedBy("mBlockedAppUids")
4408 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4409
Paul Jensen2c311d62014-11-17 12:34:51 -05004410 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004411 private final NetworkRequest mDefaultRequest;
4412
Erik Klineda4bfa82015-04-30 12:58:40 +09004413 // Request used to optionally keep mobile data active even when higher
4414 // priority networks like Wi-Fi are active.
4415 private final NetworkRequest mDefaultMobileDataRequest;
4416
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004417 private NetworkAgentInfo getDefaultNetwork() {
4418 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4419 }
4420
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004421 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004422 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004423 }
4424
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004425 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4426 return nri.request.requestId == mDefaultRequest.requestId;
4427 }
4428
Paul Jensen31a94f42015-02-13 14:18:39 -05004429 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004430 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004431 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004432 enforceConnectivityInternalPermission();
4433
Paul Jensen2c311d62014-11-17 12:34:51 -05004434 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4435 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004436 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004437 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4438 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004439 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004440 synchronized (this) {
4441 nai.networkMonitor.systemReady = mSystemReady;
4442 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004443 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4444 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004445 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004446 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004447 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004448 }
4449
4450 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4451 if (VDBG) log("Got NetworkAgent Messenger");
4452 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004453 synchronized (mNetworkForNetId) {
4454 mNetworkForNetId.put(na.network.netId, na);
4455 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004456 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4457 NetworkInfo networkInfo = na.networkInfo;
4458 na.networkInfo = null;
4459 updateNetworkInfo(na, networkInfo);
4460 }
4461
4462 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4463 LinkProperties newLp = networkAgent.linkProperties;
4464 int netId = networkAgent.network.netId;
4465
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004466 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4467 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004468 if (networkAgent.clatd != null) {
4469 networkAgent.clatd.fixupLinkProperties(oldLp);
4470 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004471
Paul Jensen992f2522014-04-28 10:33:11 -04004472 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004473 updateMtu(newLp, oldLp);
4474 // TODO - figure out what to do for clat
4475// for (LinkProperties lp : newLp.getStackedLinks()) {
4476// updateMtu(lp, null);
4477// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004478 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004479
Erik Kline94887872016-04-05 13:30:49 +09004480 updateRoutes(newLp, oldLp, netId);
4481 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004482
Paul Jensen3b759822014-05-13 11:44:01 -04004483 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004484 if (isDefaultNetwork(networkAgent)) {
4485 handleApplyDefaultProxy(newLp.getHttpProxy());
4486 } else {
4487 updateProxy(newLp, oldLp, networkAgent);
4488 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004489 // TODO - move this check to cover the whole function
4490 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004491 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004492 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4493 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004494
4495 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004496 }
4497
Lorenzo Colitti95439462014-10-09 13:44:48 +09004498 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4499 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4500 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004501
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004502 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004503 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4504 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004505 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004506 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004507 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004508 }
Paul Jensen992f2522014-04-28 10:33:11 -04004509
4510 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4511 CompareResult<String> interfaceDiff = new CompareResult<String>();
4512 if (oldLp != null) {
4513 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4514 } else if (newLp != null) {
4515 interfaceDiff.added = newLp.getAllInterfaceNames();
4516 }
4517 for (String iface : interfaceDiff.added) {
4518 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004519 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004520 mNetd.addInterfaceToNetwork(iface, netId);
4521 } catch (Exception e) {
4522 loge("Exception adding interface: " + e);
4523 }
4524 }
4525 for (String iface : interfaceDiff.removed) {
4526 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004527 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004528 mNetd.removeInterfaceFromNetwork(iface, netId);
4529 } catch (Exception e) {
4530 loge("Exception removing interface: " + e);
4531 }
4532 }
4533 }
4534
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004535 /**
4536 * Have netd update routes from oldLp to newLp.
4537 * @return true if routes changed between oldLp and newLp
4538 */
4539 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004540 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4541 if (oldLp != null) {
4542 routeDiff = oldLp.compareAllRoutes(newLp);
4543 } else if (newLp != null) {
4544 routeDiff.added = newLp.getAllRoutes();
4545 }
4546
4547 // add routes before removing old in case it helps with continuous connectivity
4548
4549 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4550 for (RouteInfo route : routeDiff.added) {
4551 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004552 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004553 try {
4554 mNetd.addRoute(netId, route);
4555 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004556 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4557 loge("Exception in addRoute for non-gateway: " + e);
4558 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004559 }
4560 }
4561 for (RouteInfo route : routeDiff.added) {
4562 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004563 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004564 try {
4565 mNetd.addRoute(netId, route);
4566 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004567 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4568 loge("Exception in addRoute for gateway: " + e);
4569 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004570 }
4571 }
4572
4573 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004574 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004575 try {
4576 mNetd.removeRoute(netId, route);
4577 } catch (Exception e) {
4578 loge("Exception in removeRoute: " + e);
4579 }
4580 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004581 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004582 }
Erik Kline41368502015-06-17 13:19:54 +09004583
Erik Kline94887872016-04-05 13:30:49 +09004584 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4585 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4586 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004587 }
Erik Kline94887872016-04-05 13:30:49 +09004588
4589 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004590 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004591 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004592 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004593 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4594 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004595 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004596 }
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004597 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4598 if (defaultNai != null && defaultNai.network.netId == netId) {
4599 setDefaultDnsSystemProperties(dnses);
4600 }
Erik Kline94887872016-04-05 13:30:49 +09004601 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004602 }
4603
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004604 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4605 int last = 0;
4606 for (InetAddress dns : dnses) {
4607 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004608 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004609 }
4610 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004611 setNetDnsProperty(i, "");
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004612 }
4613 mNumDnsEntries = last;
4614 }
4615
Erik Kline4edba012017-04-07 15:29:29 +09004616 private void setNetDnsProperty(int which, String value) {
4617 final String key = "net.dns" + which;
4618 // Log and forget errors setting unsupported properties.
4619 try {
4620 mSystemProperties.set(key, value);
4621 } catch (Exception e) {
4622 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4623 }
4624 }
4625
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004626 private String getNetworkPermission(NetworkCapabilities nc) {
4627 // TODO: make these permission strings AIDL constants instead.
4628 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4629 return NetworkManagementService.PERMISSION_SYSTEM;
4630 }
4631 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4632 return NetworkManagementService.PERMISSION_NETWORK;
4633 }
4634 return null;
4635 }
4636
Paul Jensen3d194ea2015-06-16 14:27:36 -04004637 /**
4638 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4639 * augmented with any stateful capabilities implied from {@code networkAgent}
4640 * (e.g., validated status and captive portal status).
4641 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004642 * @param oldScore score of the network before any of the changes that prompted us
4643 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004644 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004645 * @param networkCapabilities the new network capabilities.
4646 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004647 private void updateCapabilities(
4648 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004649 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4650 networkCapabilities)) {
4651 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4652 + nai.networkCapabilities + " -> " + networkCapabilities);
4653 }
4654
Paul Jensen3d194ea2015-06-16 14:27:36 -04004655 // Don't modify caller's NetworkCapabilities.
4656 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004657 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004658 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4659 } else {
4660 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4661 }
Paul Jensene0988542015-06-25 15:30:08 -04004662 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004663 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4664 } else {
4665 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4666 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004667 if (nai.isBackgroundNetwork()) {
4668 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4669 } else {
4670 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4671 }
4672
4673 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4674
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004675 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4676 final String newPermission = getNetworkPermission(networkCapabilities);
4677 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004678 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004679 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004680 } catch (RemoteException e) {
4681 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004682 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004683 }
4684
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004685 final NetworkCapabilities prevNc = nai.networkCapabilities;
4686 synchronized (nai) {
4687 nai.networkCapabilities = networkCapabilities;
4688 }
4689 if (nai.getCurrentScore() == oldScore &&
4690 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4691 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4692 // the change we're processing can't affect any requests, it can only affect the listens
4693 // on this network. We might have been called by rematchNetworkAndRequests when a
4694 // network changed foreground state.
4695 processListenRequests(nai, true);
4696 } else {
4697 // If the requestable capabilities have changed or the score changed, we can't have been
4698 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004699 rematchAllNetworksAndRequests(nai, oldScore);
4700 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004701 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004702 }
4703
Paul Jensenc8b9a742014-09-30 15:37:41 -04004704 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004705 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4706 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004707 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004708 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004709 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4710 }
4711 }
4712
Robert Greenwalt7b816022014-04-18 15:25:25 -07004713 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4714 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004715 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004716 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4717 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004718 }
4719 }
4720
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004721 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4722 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004723 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004724 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004725 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4726 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004727 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004728 sendIntent(nri.mPendingIntent, intent);
4729 }
4730 // else not handled
4731 }
4732
4733 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4734 mPendingIntentWakeLock.acquire();
4735 try {
4736 if (DBG) log("Sending " + pendingIntent);
4737 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4738 } catch (PendingIntent.CanceledException e) {
4739 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4740 mPendingIntentWakeLock.release();
4741 releasePendingNetworkRequest(pendingIntent);
4742 }
4743 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4744 }
4745
4746 @Override
4747 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4748 String resultData, Bundle resultExtras) {
4749 if (DBG) log("Finished sending " + pendingIntent);
4750 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004751 // Release with a delay so the receiving client has an opportunity to put in its
4752 // own request.
4753 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004754 }
4755
Hugo Benichidba33db2017-03-23 22:40:44 +09004756 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004757 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004758 if (nri.messenger == null) {
4759 return; // Default request has no msgr
4760 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004761 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004762 // TODO: check if defensive copies of data is needed.
4763 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004764 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004765 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4766 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004767 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004768 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004769 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004770 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004771 break;
4772 }
4773 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004774 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004775 break;
4776 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004777 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004778 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004779 break;
4780 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004781 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004782 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004783 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004784 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004785 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004786 String notification = ConnectivityManager.getCallbackName(notificationType);
4787 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004788 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004789 nri.messenger.send(msg);
4790 } catch (RemoteException e) {
4791 // may occur naturally in the race of binder death.
4792 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4793 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004794 }
4795
Hugo Benichidba33db2017-03-23 22:40:44 +09004796 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4797 bundle.putParcelable(t.getClass().getSimpleName(), t);
4798 }
4799
Paul Jensenc8b9a742014-09-30 15:37:41 -04004800 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004801 if (nai.numRequestNetworkRequests() != 0) {
4802 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4803 NetworkRequest nr = nai.requestAt(i);
4804 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004805 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004806 loge("Dead network still had at least " + nr);
4807 break;
4808 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004809 }
4810 nai.asyncChannel.disconnect();
4811 }
4812
Robert Greenwalt7b816022014-04-18 15:25:25 -07004813 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4814 if (oldNetwork == null) {
4815 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4816 return;
4817 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004818 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004819
4820 // If we get here it means that the last linger timeout for this network expired. So there
4821 // must be no other active linger timers, and we must stop lingering.
4822 oldNetwork.clearLingerState();
4823
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004824 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004825 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004826 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004827 } else {
4828 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004829 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4830 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004831 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004832 }
4833
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004834 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004835 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004836 setupDataActivityTracking(newNetwork);
4837 try {
4838 mNetd.setDefaultNetId(newNetwork.network.netId);
4839 } catch (Exception e) {
4840 loge("Exception setting default network :" + e);
4841 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004842 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004843 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004844 updateTcpBufferSizes(newNetwork);
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004845 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004846 }
4847
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004848 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004849 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4850 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4851 NetworkRequest nr = nri.request;
4852 if (!nr.isListen()) continue;
4853 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4854 nai.removeRequest(nri.request.requestId);
4855 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4856 }
4857 }
4858
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004859 if (capabilitiesChanged) {
4860 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4861 }
4862
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004863 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4864 NetworkRequest nr = nri.request;
4865 if (!nr.isListen()) continue;
4866 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4867 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004868 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004869 }
4870 }
4871 }
4872
Paul Jensen2161a8e2014-09-11 11:00:39 -04004873 // Handles a network appearing or improving its score.
4874 //
4875 // - Evaluates all current NetworkRequests that can be
4876 // satisfied by newNetwork, and reassigns to newNetwork
4877 // any such requests for which newNetwork is the best.
4878 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004879 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004880 // needed. A network is needed if it is the best network for
4881 // one or more NetworkRequests, or if it is a VPN.
4882 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004883 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004884 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004885 //
4886 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4887 // networks that have no chance (i.e. even if validated)
4888 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004889 //
4890 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4891 // it does not remove NetworkRequests that other Networks could better satisfy.
4892 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4893 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4894 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004895 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004896 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004897 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4898 // performed to tear down unvalidated networks that have no chance (i.e. even if
4899 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004900 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004901 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004902 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004903 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004904 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004905 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004906
4907 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4908 final int score = newNetwork.getCurrentScore();
4909
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004910 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004911
Paul Jensen2161a8e2014-09-11 11:00:39 -04004912 // Find and migrate to this Network any NetworkRequests for
4913 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004914 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004915 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004916 NetworkCapabilities nc = newNetwork.networkCapabilities;
4917 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004918 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004919 // Process requests in the first pass and listens in the second pass. This allows us to
4920 // change a network's capabilities depending on which requests it has. This is only
4921 // correct if the change in capabilities doesn't affect whether the network satisfies
4922 // requests or not, and doesn't affect the network's score.
4923 if (nri.request.isListen()) continue;
4924
Paul Jensencf4c2c62015-07-01 14:16:32 -04004925 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4926 final boolean satisfies = newNetwork.satisfies(nri.request);
4927 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004928 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004929 log("Network " + newNetwork.name() + " was already satisfying" +
4930 " request " + nri.request.requestId + ". No change.");
4931 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004932 keep = true;
4933 continue;
4934 }
4935
4936 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004937 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004938 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004939 // next check if it's better than any current network we're using for
4940 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004941 if (VDBG) {
4942 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004943 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004944 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004945 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004946 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004947 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004948 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004949 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004950 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004951 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004952 affectedNetworks.add(currentNetwork);
4953 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004954 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004955 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004956 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004957 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004958 if (!newNetwork.addRequest(nri.request)) {
4959 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4960 }
4961 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004962 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004963 // Tell NetworkFactories about the new score, so they can stop
4964 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004965 // TODO - this could get expensive if we have alot of requests for this
4966 // network. Think about if there is a way to reduce this. Push
4967 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004968 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004969 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004970 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004971 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004972 if (currentNetwork != null) {
4973 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4974 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004975 }
4976 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004977 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004978 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4979 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004980 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004981 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4982 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4983 // This means this code doesn't have to handle the case where "currentNetwork" no
4984 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4985 if (DBG) {
4986 log("Network " + newNetwork.name() + " stopped satisfying" +
4987 " request " + nri.request.requestId);
4988 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004989 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004990 if (currentNetwork == newNetwork) {
4991 mNetworkForRequestId.remove(nri.request.requestId);
4992 sendUpdatedScoreToFactories(nri.request, 0);
4993 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004994 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4995 newNetwork.name() +
4996 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004997 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004998 // TODO: Technically, sending CALLBACK_LOST here is
4999 // incorrect if there is a replacement network currently
5000 // connected that can satisfy nri, which is a request
5001 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005002 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5003 // so this code is only incorrect for a network that loses
5004 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005005 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005006 }
5007 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005008 if (isNewDefault) {
5009 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005010 makeDefault(newNetwork);
5011 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
5012 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005013 // Have a new default network, release the transition wakelock in
5014 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005015 }
5016
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005017 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5018 Slog.wtf(TAG, String.format(
5019 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
5020 nc, newNetwork.networkCapabilities));
5021 }
5022 if (newNetwork.getCurrentScore() != score) {
5023 Slog.wtf(TAG, String.format(
5024 "BUG: %s changed score during rematch: %d -> %d",
5025 score, newNetwork.getCurrentScore()));
5026 }
5027
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005028 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005029 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5030 // If the network went from background to foreground or vice versa, we need to update
5031 // its foreground state. It is safe to do this after rematching the requests because
5032 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5033 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005034 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005035 } else {
5036 processListenRequests(newNetwork, false);
5037 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005038
Paul Jensencf4c2c62015-07-01 14:16:32 -04005039 // do this after the default net is switched, but
5040 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005041 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005042
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005043 // Linger any networks that are no longer needed. This should be done after sending the
5044 // available callback for newNetwork.
5045 for (NetworkAgentInfo nai : affectedNetworks) {
5046 updateLingerState(nai, now);
5047 }
5048 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5049 // does not need to be done in any particular order.
5050 updateLingerState(newNetwork, now);
5051
Paul Jensencf4c2c62015-07-01 14:16:32 -04005052 if (isNewDefault) {
5053 // Maintain the illusion: since the legacy API only
5054 // understands one network at a time, we must pretend
5055 // that the current default network disconnected before
5056 // the new one connected.
5057 if (oldDefaultNetwork != null) {
5058 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5059 oldDefaultNetwork, true);
5060 }
5061 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5062 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5063 notifyLockdownVpn(newNetwork);
5064 }
5065
Robert Greenwalt7b816022014-04-18 15:25:25 -07005066 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005067 // Notify battery stats service about this network, both the normal
5068 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005069 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005070 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005071 final IBatteryStats bs = BatteryStatsService.getService();
5072 final int type = newNetwork.networkInfo.getType();
5073
5074 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5075 bs.noteNetworkInterfaceType(baseIface, type);
5076 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5077 final String stackedIface = stacked.getInterfaceName();
5078 bs.noteNetworkInterfaceType(stackedIface, type);
5079 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5080 }
5081 } catch (RemoteException ignored) {
5082 }
5083
Robert Greenwalt152ed372014-12-17 17:19:53 -08005084 // This has to happen after the notifyNetworkCallbacks as that tickles each
5085 // ConnectivityManager instance so that legacy requests correctly bind dns
5086 // requests to this network. The legacy users are listening for this bcast
5087 // and will generally do a dns request so they can ensureRouteToHost and if
5088 // they do that before the callbacks happen they'll use the default network.
5089 //
5090 // TODO: Is there still a race here? We send the broadcast
5091 // after sending the callback, but if the app can receive the
5092 // broadcast before the callback, it might still break.
5093 //
5094 // This *does* introduce a race where if the user uses the new api
5095 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5096 // they may get old info. Reverse this after the old startUsing api is removed.
5097 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005098 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5099 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005100 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005101 // legacy type tracker filters out repeat adds
5102 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5103 }
5104 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005105
5106 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5107 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5108 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5109 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5110 if (newNetwork.isVPN()) {
5111 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5112 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005113 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005114 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5115 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005116 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005117 if (nai.getLingerExpiry() > 0) {
5118 // This network has active linger timers and no requests, but is not
5119 // lingering. Linger it.
5120 //
5121 // One way (the only way?) this can happen if this network is unvalidated
5122 // and became unneeded due to another network improving its score to the
5123 // point where this network will no longer be able to satisfy any requests
5124 // even if it validates.
5125 updateLingerState(nai, now);
5126 } else {
5127 if (DBG) log("Reaping " + nai.name());
5128 teardownUnneededNetwork(nai);
5129 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005130 }
5131 }
5132 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005133 }
5134
Paul Jensen1c7ba022015-06-16 14:27:36 -04005135 /**
5136 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5137 * being disconnected.
5138 * @param changed If only one Network's score or capabilities have been modified since the last
5139 * time this function was called, pass this Network in this argument, otherwise pass
5140 * null.
5141 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5142 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5143 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5144 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5145 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005146 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005147 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005148 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5149 // to avoid the slowness. It is not simply enough to process just "changed", for
5150 // example in the case where "changed"'s score decreases and another network should begin
5151 // satifying a NetworkRequest that "changed" currently satisfies.
5152
5153 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5154 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5155 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005156 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005157 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005158 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005159 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005160 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5161 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5162 // Rematch higher scoring networks first to prevent requests first matching a lower
5163 // scoring network and then a higher scoring network, which could produce multiple
5164 // callbacks and inadvertently unlinger networks.
5165 Arrays.sort(nais);
5166 for (NetworkAgentInfo nai : nais) {
5167 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005168 // Only reap the last time through the loop. Reaping before all rematching
5169 // is complete could incorrectly teardown a network that hasn't yet been
5170 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005171 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005172 : ReapUnvalidatedNetworks.REAP,
5173 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005174 }
5175 }
5176 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005177
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005178 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005179 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005180 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005181 // For now only update icons for default connection.
5182 // TODO: Update WiFi and cellular icons separately. b/17237507
5183 if (!isDefaultNetwork(nai)) return;
5184
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005185 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005186 // Don't repeat publish.
5187 if (newInetCondition == mDefaultInetConditionPublished) return;
5188
5189 mDefaultInetConditionPublished = newInetCondition;
5190 sendInetConditionBroadcast(nai.networkInfo);
5191 }
5192
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005193 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5194 if (mLockdownTracker != null) {
5195 if (nai != null && nai.isVPN()) {
5196 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5197 } else {
5198 mLockdownTracker.onNetworkInfoChanged();
5199 }
5200 }
5201 }
5202
Robert Greenwalt7b816022014-04-18 15:25:25 -07005203 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005204 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005205 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005206 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005207 synchronized (networkAgent) {
5208 oldInfo = networkAgent.networkInfo;
5209 networkAgent.networkInfo = newInfo;
5210 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005211 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005212
5213 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005214 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5215 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5216 notifyIfacesChangedForNetworkStats();
5217 } else if (VDBG) log("ignoring duplicate network state non-change");
5218 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005219 return;
5220 }
5221 if (DBG) {
5222 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5223 (oldInfo == null ? "null" : oldInfo.getState()) +
5224 " to " + state);
5225 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005226
Robin Lee585e2482016-05-01 23:00:00 +01005227 if (!networkAgent.created
5228 && (state == NetworkInfo.State.CONNECTED
5229 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005230
5231 // A network that has just connected has zero requests and is thus a foreground network.
5232 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5233
Robert Greenwalt7b816022014-04-18 15:25:25 -07005234 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005235 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005236 if (networkAgent.isVPN()) {
5237 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005238 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5239 (networkAgent.networkMisc == null ||
5240 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005241 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005242 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005243 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005244 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005245 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005246 loge("Error creating network " + networkAgent.network.netId + ": "
5247 + e.getMessage());
5248 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005249 }
Paul Jenseneec75412014-08-04 12:21:19 -04005250 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005251 }
5252
5253 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5254 networkAgent.everConnected = true;
5255
Robert Greenwalt7b816022014-04-18 15:25:25 -07005256 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005257 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005258
Paul Jensenca8f16a2014-05-09 12:47:55 -04005259 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005260 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005261
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005262 if (networkAgent.isVPN()) {
5263 // Temporarily disable the default proxy (not global).
5264 synchronized (mProxyLock) {
5265 if (!mDefaultProxyDisabled) {
5266 mDefaultProxyDisabled = true;
5267 if (mGlobalProxy == null && mDefaultProxy != null) {
5268 sendProxyBroadcast(null);
5269 }
5270 }
5271 }
5272 // TODO: support proxy per network.
5273 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005274
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005275 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5276 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5277 // capabilities, so it only needs to be done once on initial connect, not every time the
5278 // network's capabilities change. Note that we do this before rematching the network,
5279 // so we could decide to tear it down immediately afterwards. That's fine though - on
5280 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5281 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005282 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005283
Paul Jensen2161a8e2014-09-11 11:00:39 -04005284 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005285 final long now = SystemClock.elapsedRealtime();
5286 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005287
5288 // This has to happen after matching the requests, because callbacks are just requests.
5289 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005290 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005291 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005292 if (networkAgent.isVPN()) {
5293 synchronized (mProxyLock) {
5294 if (mDefaultProxyDisabled) {
5295 mDefaultProxyDisabled = false;
5296 if (mGlobalProxy == null && mDefaultProxy != null) {
5297 sendProxyBroadcast(mDefaultProxy);
5298 }
5299 }
5300 }
5301 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005302 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5303 state == NetworkInfo.State.SUSPENDED) {
5304 // going into or coming out of SUSPEND: rescore and notify
5305 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005306 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005307 }
5308 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5309 ConnectivityManager.CALLBACK_SUSPENDED :
5310 ConnectivityManager.CALLBACK_RESUMED));
5311 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005312 }
5313 }
5314
Robert Greenwaltac96c522014-06-03 16:43:57 -07005315 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005316 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005317 if (score < 0) {
5318 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5319 "). Bumping score to min of 0");
5320 score = 0;
5321 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005322
Paul Jensen2161a8e2014-09-11 11:00:39 -04005323 final int oldScore = nai.getCurrentScore();
5324 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005325
Paul Jensen85cf78e2015-06-25 13:25:07 -04005326 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005327
Paul Jensenc8b9a742014-09-30 15:37:41 -04005328 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005329 }
5330
Erik Klinec75d4fa2017-02-15 19:59:17 +09005331 // Notify only this one new request of the current state. Transfer all the
5332 // current state by calling NetworkCapabilities and LinkProperties callbacks
5333 // so that callers can be guaranteed to have as close to atomicity in state
5334 // transfer as can be supported by this current API.
5335 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohenbf3b1ba2016-10-27 15:05:50 -07005336 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005337 if (nri.mPendingIntent != null) {
5338 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5339 // Attempt no subsequent state pushes where intents are involved.
5340 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005341 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005342
5343 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5344 // Whether a network is currently suspended is also an important
5345 // element of state to be transferred (it would not otherwise be
5346 // delivered by any currently available mechanism).
5347 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5348 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5349 }
5350 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5351 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005352 }
5353
Robert Greenwalt8d482522015-06-24 13:23:42 -07005354 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005355 // The NetworkInfo we actually send out has no bearing on the real
5356 // state of affairs. For example, if the default connection is mobile,
5357 // and a request for HIPRI has just gone away, we need to pretend that
5358 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5359 // the state to DISCONNECTED, even though the network is of type MOBILE
5360 // and is still connected.
5361 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5362 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005363 if (state != DetailedState.DISCONNECTED) {
5364 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005365 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005366 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005367 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005368 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5369 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5370 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5371 if (info.isFailover()) {
5372 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5373 nai.networkInfo.setFailover(false);
5374 }
5375 if (info.getReason() != null) {
5376 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5377 }
5378 if (info.getExtraInfo() != null) {
5379 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5380 }
5381 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005382 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005383 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005384 if (newDefaultAgent != null) {
5385 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5386 newDefaultAgent.networkInfo);
5387 } else {
5388 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5389 }
5390 }
5391 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5392 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005393 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005394 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005395 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005396 }
5397 }
5398 }
5399
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005400 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005401 if (VDBG) {
5402 String notification = ConnectivityManager.getCallbackName(notifyType);
5403 log("notifyType " + notification + " for " + networkAgent.name());
5404 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005405 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5406 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005407 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5408 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005409 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5410 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005411 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005412 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005413 } else {
5414 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5415 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005416 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005417 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005418
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005419 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5420 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5421 }
5422
Jeff Sharkey69736342014-12-08 14:50:12 -08005423 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005424 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5425 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005426 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005427 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005428 try {
5429 mStatsService.forceUpdateIfaces();
5430 } catch (Exception ignored) {
5431 }
5432 }
5433
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005434 @Override
5435 public boolean addVpnAddress(String address, int prefixLength) {
5436 throwIfLockdownEnabled();
5437 int user = UserHandle.getUserId(Binder.getCallingUid());
5438 synchronized (mVpns) {
5439 return mVpns.get(user).addAddress(address, prefixLength);
5440 }
5441 }
5442
5443 @Override
5444 public boolean removeVpnAddress(String address, int prefixLength) {
5445 throwIfLockdownEnabled();
5446 int user = UserHandle.getUserId(Binder.getCallingUid());
5447 synchronized (mVpns) {
5448 return mVpns.get(user).removeAddress(address, prefixLength);
5449 }
5450 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005451
5452 @Override
5453 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5454 throwIfLockdownEnabled();
5455 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005456 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005457 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005458 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005459 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005460 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005461 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005462 }
5463 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005464 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005465
5466 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005467 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005468 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005469 }
5470
5471 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005472 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5473 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5474 enforceKeepalivePermission();
5475 mKeepaliveTracker.startNattKeepalive(
5476 getNetworkAgentInfoForNetwork(network),
5477 intervalSeconds, messenger, binder,
5478 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5479 }
5480
5481 @Override
5482 public void stopKeepalive(Network network, int slot) {
5483 mHandler.sendMessage(mHandler.obtainMessage(
5484 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5485 }
5486
5487 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005488 public void factoryReset() {
5489 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005490
5491 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5492 return;
5493 }
5494
Robin Lee3b3dd942015-05-12 18:14:58 +01005495 final int userId = UserHandle.getCallingUserId();
5496
Stuart Scottf1fb3972015-04-02 18:00:02 -07005497 // Turn airplane mode off
5498 setAirplaneMode(false);
5499
Stuart Scotte3e314d2015-04-20 14:07:45 -07005500 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5501 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005502 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005503 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005504 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005505 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005506 }
5507
Stuart Scotte3e314d2015-04-20 14:07:45 -07005508 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005509 // Remove always-on package
5510 synchronized (mVpns) {
5511 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5512 if (alwaysOnPackage != null) {
5513 setAlwaysOnVpnPackage(userId, null, false);
5514 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5515 }
5516 }
5517
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005518 // Turn Always-on VPN off
5519 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5520 final long ident = Binder.clearCallingIdentity();
5521 try {
5522 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5523 mLockdownEnabled = false;
5524 setLockdownTracker(null);
5525 } finally {
5526 Binder.restoreCallingIdentity(ident);
5527 }
5528 }
5529
Stuart Scotte3e314d2015-04-20 14:07:45 -07005530 // Turn VPN off
5531 VpnConfig vpnConfig = getVpnConfig(userId);
5532 if (vpnConfig != null) {
5533 if (vpnConfig.legacy) {
5534 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5535 } else {
5536 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5537 // in the future without user intervention.
5538 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005539
Victor Changb04a5ea2016-05-30 20:36:30 +01005540 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005541 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005542 }
5543 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005544
5545 Settings.Global.putString(mContext.getContentResolver(),
5546 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005547 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005548
5549 @VisibleForTesting
5550 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5551 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5552 return new NetworkMonitor(context, handler, nai, defaultRequest);
5553 }
Erik Kline48f12f22016-04-14 17:30:59 +09005554
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005555 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005556 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5557 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005558 }
5559
5560 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005561 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5562 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5563 }
5564
Hugo Benichicfddd682016-05-31 16:28:06 +09005565 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005566 int newNetid = NETID_UNSET;
5567 int prevNetid = NETID_UNSET;
5568 int[] transports = new int[0];
5569 boolean hadIPv4 = false;
5570 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005571
Hugo Benichi5f16f762016-04-20 12:09:33 +09005572 if (newNai != null) {
5573 newNetid = newNai.network.netId;
5574 transports = newNai.networkCapabilities.getTransportTypes();
5575 }
5576 if (prevNai != null) {
5577 prevNetid = prevNai.network.netId;
5578 final LinkProperties lp = prevNai.linkProperties;
5579 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5580 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5581 }
5582
Hugo Benichicfddd682016-05-31 16:28:06 +09005583 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5584 }
5585
5586 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5587 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005588 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005589
5590 private static boolean toBool(int encodedBoolean) {
5591 return encodedBoolean != 0; // Only 0 means false.
5592 }
5593
5594 private static int encodeBool(boolean b) {
5595 return b ? 1 : 0;
5596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597}