blob: a1ee71a520c3c2494bddd5b4754a6995c0d80759 [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";
Erik Klineee363c42017-05-29 09:11:03 +0900188 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900189
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900190 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700191 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
Jake Hamby786e71a2014-02-06 14:43:50 -0800193 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900194 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700195
Jeff Sharkey899223b2012-08-04 15:24:58 -0700196 // TODO: create better separation between radio types and network types
197
Robert Greenwalt42acef32009-08-12 16:08:25 -0700198 // how long to wait before switching back to a radio's default network
199 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
200 // system property that can override the above value
201 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
202 "android.telephony.apn-restore";
203
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900204 // How long to wait before putting up a "This network doesn't have an Internet connection,
205 // connect anyway?" dialog after the user selects a network that doesn't validate.
206 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
207
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900208 // Default to 30s linger time-out. Modifiable only for testing.
209 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
210 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
211 @VisibleForTesting
212 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
213
Jeremy Joslin79294842014-12-03 17:15:28 -0800214 // How long to delay to removal of a pending intent based request.
215 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
216 private final int mReleasePendingIntentDelayMs;
217
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900218 private MockableSystemProperties mSystemProperties;
219
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800220 private Tethering mTethering;
221
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700222 private final PermissionMonitor mPermissionMonitor;
223
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700224 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700225
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700226 @GuardedBy("mVpns")
227 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700228
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700229 private boolean mLockdownEnabled;
230 private LockdownVpnTracker mLockdownTracker;
231
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700232 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
233 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700234 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600235 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700236 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700237 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600238 @GuardedBy("mRulesLock")
239 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
240 /** Flag indicating if background data is restricted. */
241 @GuardedBy("mRulesLock")
242 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700243
Erik Klineda4bfa82015-04-30 12:58:40 +0900244 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700246 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700247 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800249 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250
251 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700252 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700254 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800255 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700256 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700257
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700258 private String mCurrentTcpBufferSizes;
259
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700260 private static final int ENABLED = 1;
261 private static final int DISABLED = 0;
262
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900263 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900264 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
265 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900266
Paul Jensenb10e37f2014-11-25 12:33:08 -0500267 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400268 // Tear down networks that have no chance (e.g. even if validated) of becoming
269 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500270 // all networks have been rematched against all NetworkRequests.
271 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400272 // Don't reap networks. This should be passed when some networks have not yet been
273 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500274 DONT_REAP
275 };
276
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900277 private enum UnneededFor {
278 LINGER, // Determine whether this network is unneeded and should be lingered.
279 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
280 }
281
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700282 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700283 * used internally to change our mobile data enabled flag
284 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700285 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700286
287 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700288 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700289 * from one net to another. Clear happens when we get a new
290 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
291 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700292 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700293 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700294
Robert Greenwalt434203a2010-10-11 16:00:27 -0700295 /**
296 * used internally to reload global proxy settings
297 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700298 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700299
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700300 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400301 * PAC manager has received new port.
302 */
303 private static final int EVENT_PROXY_HAS_CHANGED = 16;
304
Robert Greenwalte049c232014-04-11 15:53:27 -0700305 /**
306 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700307 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700308 */
309 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
310
Robert Greenwalt7b816022014-04-18 15:25:25 -0700311 /**
312 * used internally when registering NetworkAgents
313 * obj = Messenger
314 */
315 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
316
Robert Greenwalt9258c642014-03-26 16:47:06 -0700317 /**
318 * used to add a network request
319 * includes a NetworkRequestInfo
320 */
321 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
322
323 /**
324 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900325 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700326 * cancel it.
327 * includes a NetworkRequestInfo
328 */
329 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
330
331 /**
332 * used to add a network listener - no request
333 * includes a NetworkRequestInfo
334 */
335 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
336
337 /**
338 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400339 * arg1 = UID of caller
340 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700341 */
342 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
343
Robert Greenwalta67be032014-05-16 15:49:14 -0700344 /**
345 * used internally when registering NetworkFactories
346 * obj = Messenger
347 */
348 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
349
Robert Greenwalt27711812014-06-25 16:45:57 -0700350 /**
351 * used internally to expire a wakelock when transitioning
352 * from one net to another. Expire happens when we fail to find
353 * a new network (typically after 1 minute) -
354 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
355 * a replacement network.
356 */
357 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
358
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700359 /**
360 * Used internally to indicate the system is ready.
361 */
362 private static final int EVENT_SYSTEM_READY = 25;
363
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800364 /**
365 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400366 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800367 */
368 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
369
370 /**
371 * used to remove a pending intent and its associated network request.
372 * arg1 = UID of caller
373 * obj = PendingIntent
374 */
375 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
376
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900377 /**
378 * used to specify whether a network should be used even if unvalidated.
379 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
380 * arg2 = whether to remember this choice in the future (1 or 0)
381 * obj = network
382 */
383 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
384
385 /**
386 * used to ask the user to confirm a connection to an unvalidated network.
387 * obj = network
388 */
389 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700390
Erik Klineda4bfa82015-04-30 12:58:40 +0900391 /**
392 * used internally to (re)configure mobile data always-on settings.
393 */
394 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
395
Paul Jensen694f2b82015-06-17 14:15:39 -0400396 /**
397 * used to add a network listener with a pending intent
398 * obj = NetworkRequestInfo
399 */
400 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
401
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900402 /**
403 * used to specify whether a network should not be penalized when it becomes unvalidated.
404 */
405 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
406
407 /**
408 * used to trigger revalidation of a network.
409 */
410 private static final int EVENT_REVALIDATE_NETWORK = 36;
411
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900412 private static String eventName(int what) {
413 return sMagicDecoderRing.get(what, Integer.toString(what));
414 }
415
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900416 /** Handler thread used for both of the handlers below. */
417 @VisibleForTesting
418 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700419 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700420 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700421 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700422 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700423
Mike Lockwood0f79b542009-08-14 14:18:49 -0400424 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800425 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400426
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700427 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700428 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800429 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700430
Robert Greenwalt434203a2010-10-11 16:00:27 -0700431 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400432 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700433 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700434 private boolean mDefaultProxyDisabled = false;
435
Robert Greenwalt434203a2010-10-11 16:00:27 -0700436 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400437 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700438
Jason Monk602b2322013-07-03 17:04:33 -0400439 private PacManager mPacManager = null;
440
Erik Klineda4bfa82015-04-30 12:58:40 +0900441 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700442
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400443 private UserManager mUserManager;
444
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700445 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700446 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700447
Robert Greenwalt50393202011-06-21 17:26:14 -0700448 // the set of network types that can only be enabled by system/sig apps
449 List mProtectedNetworks;
450
John Spurlockbf991a82013-06-24 14:20:23 -0400451 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700452
Wink Savilleab9321d2013-06-29 21:10:57 -0700453 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400454
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900455 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900456 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900457 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900458
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700459 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
460 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700461 private final static int MAX_NET_ID = 65535;
462 private int mNextNetId = MIN_NET_ID;
463
Robert Greenwalt34524f02014-05-18 16:22:10 -0700464 // sequence number of NetworkRequests
465 private int mNextNetworkRequestId = 1;
466
Erik Kline7523eb32015-07-09 18:24:03 +0900467 // NetworkRequest activity String log entries.
468 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
469 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
470
Hugo Benichic2ae2872016-07-11 11:05:12 +0900471 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900472 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900473 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
474
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900475 private static final int MAX_WAKELOCK_LOGS = 20;
476 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
477
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700478 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
479 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400480 private static class ValidationLog {
481 final Network mNetwork;
482 final String mNetworkExtraInfo;
483 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700484
Paul Jensen0808eb82016-06-03 13:51:21 -0400485 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
486 mNetwork = network;
487 mNetworkExtraInfo = networkExtraInfo;
488 mLog = log;
489 }
490 }
491 private final ArrayDeque<ValidationLog> mValidationLogs =
492 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
493
494 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900495 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700496 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
497 mValidationLogs.removeLast();
498 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400499 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700500 }
501 }
502
Hugo Benichif9fdf872016-07-28 17:53:06 +0900503 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900504
Erik Kline065ab6e2016-10-02 18:02:14 +0900505 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900506 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900507
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700508 /**
509 * Implements support for the legacy "one network per network type" model.
510 *
511 * We used to have a static array of NetworkStateTrackers, one for each
512 * network type, but that doesn't work any more now that we can have,
513 * for example, more that one wifi network. This class stores all the
514 * NetworkAgentInfo objects that support a given type, but the legacy
515 * API will only see the first one.
516 *
517 * It serves two main purposes:
518 *
519 * 1. Provide information about "the network for a given type" (since this
520 * API only supports one).
521 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
522 * the first network for a given type changes, or if the default network
523 * changes.
524 */
525 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900526
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900527 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900528 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900529
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700530 /**
531 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
532 * Each list holds references to all NetworkAgentInfos that are used to
533 * satisfy requests for that network type.
534 *
535 * This array is built out at startup such that an unsupported network
536 * doesn't get an ArrayList instance, making this a tristate:
537 * unsupported, supported but not active and active.
538 *
539 * The actual lists are populated when we scan the network types that
540 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900541 *
542 * Threading model:
543 * - addSupportedType() is only called in the constructor
544 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
545 * They are therefore not thread-safe with respect to each other.
546 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
547 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
548 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700549 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900550 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700551
552 public LegacyTypeTracker() {
553 mTypeLists = (ArrayList<NetworkAgentInfo>[])
554 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
555 }
556
557 public void addSupportedType(int type) {
558 if (mTypeLists[type] != null) {
559 throw new IllegalStateException(
560 "legacy list for type " + type + "already initialized");
561 }
562 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
563 }
564
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700565 public boolean isTypeSupported(int type) {
566 return isNetworkTypeValid(type) && mTypeLists[type] != null;
567 }
568
569 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900570 synchronized (mTypeLists) {
571 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
572 return mTypeLists[type].get(0);
573 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700574 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900575 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700576 }
577
Robert Greenwalt8d482522015-06-24 13:23:42 -0700578 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900579 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700581 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900582 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900583 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900584 }
585 }
586
587 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700588 public void add(int type, NetworkAgentInfo nai) {
589 if (!isTypeSupported(type)) {
590 return; // Invalid network type.
591 }
592 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
593
594 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
595 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 return;
597 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900598 synchronized (mTypeLists) {
599 list.add(nai);
600 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900601
602 // 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 +0900603 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900604 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700605 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
606 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700607 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700608 }
609
Lorenzo Colittia793a672014-07-31 23:20:17 +0900610 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900611 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900612 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
613 if (list == null || list.isEmpty()) {
614 return;
615 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900616 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900617
Hugo Benichi78caa2582016-06-21 09:48:07 +0900618 synchronized (mTypeLists) {
619 if (!list.remove(nai)) {
620 return;
621 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900622 }
623
Robert Greenwalt8d482522015-06-24 13:23:42 -0700624 final DetailedState state = DetailedState.DISCONNECTED;
625
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900626 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700627 maybeLogBroadcast(nai, state, type, wasDefault);
628 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900629 }
630
631 if (!list.isEmpty() && wasFirstNetwork) {
632 if (DBG) log("Other network available for type " + type +
633 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900634 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700635 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
636 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900637 }
638 }
639
640 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900641 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
642 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700643 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900644 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700645 }
646 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700647
Robert Greenwalt8d482522015-06-24 13:23:42 -0700648 // send out another legacy broadcast - currently only used for suspend/unsuspend
649 // toggle
650 public void update(NetworkAgentInfo nai) {
651 final boolean isDefault = isDefaultNetwork(nai);
652 final DetailedState state = nai.networkInfo.getDetailedState();
653 for (int type = 0; type < mTypeLists.length; type++) {
654 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700655 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900656 final boolean isFirst = contains && (nai == list.get(0));
657 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700658 maybeLogBroadcast(nai, state, type, isDefault);
659 sendLegacyNetworkBroadcast(nai, state, type);
660 }
661 }
662 }
663
Lorenzo Colittia793a672014-07-31 23:20:17 +0900664 private String naiToString(NetworkAgentInfo nai) {
665 String name = (nai != null) ? nai.name() : "null";
666 String state = (nai.networkInfo != null) ?
667 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
668 "???/???";
669 return name + " " + state;
670 }
671
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700672 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900673 pw.println("mLegacyTypeTracker:");
674 pw.increaseIndent();
675 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700676 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900677 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700678 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900679 pw.println();
680 pw.println("Current state:");
681 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900682 synchronized (mTypeLists) {
683 for (int type = 0; type < mTypeLists.length; type++) {
684 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
685 for (NetworkAgentInfo nai : mTypeLists[type]) {
686 pw.println(type + " " + naiToString(nai));
687 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900688 }
689 }
690 pw.decreaseIndent();
691 pw.decreaseIndent();
692 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700693 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700694 }
695 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
696
Jeff Sharkey899223b2012-08-04 15:24:58 -0700697 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700698 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900699 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
700 }
701
702 @VisibleForTesting
703 protected ConnectivityService(Context context, INetworkManagementService netManager,
704 INetworkStatsService statsService, INetworkPolicyManager policyManager,
705 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800706 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800707
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900708 mSystemProperties = getSystemProperties();
709
Hugo Benichif9fdf872016-07-28 17:53:06 +0900710 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900711 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900712 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900713 mNetworkRequests.put(mDefaultRequest, defaultNRI);
714 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900715
716 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900717 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700718
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900719 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900720 mHandlerThread.start();
721 mHandler = new InternalHandler(mHandlerThread.getLooper());
722 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700723
Jeremy Joslin79294842014-12-03 17:15:28 -0800724 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
725 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
726
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900727 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900728
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700729 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700730 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800731 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700732 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700733 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700734 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700735
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700736 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600737 mPolicyManager.setConnectivityListener(mPolicyListener);
738 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700739 } catch (RemoteException e) {
740 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700741 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700742 }
743
744 final PowerManager powerManager = (PowerManager) context.getSystemService(
745 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700746 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
747 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
748 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800749 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700750
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700751 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700752
Wink Saville51f456f2013-04-23 14:26:51 -0700753 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900754 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700755 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700756 String[] naStrings = context.getResources().getStringArray(
757 com.android.internal.R.array.networkAttributes);
758 for (String naString : naStrings) {
759 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700760 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700761 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700762 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800763 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700764 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700765 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700766 }
Wink Saville51f456f2013-04-23 14:26:51 -0700767 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
768 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
769 n.type);
770 continue;
771 }
Wink Saville975c8482011-04-07 14:23:45 -0700772 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800773 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700774 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700775 continue;
776 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700777 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700778
Wink Saville975c8482011-04-07 14:23:45 -0700779 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700780 mNetworksDefined++;
781 } catch(Exception e) {
782 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700783 }
784 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700785
786 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
787 if (mNetConfigs[TYPE_VPN] == null) {
788 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
789 // don't need to add TYPE_VPN to mNetConfigs.
790 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
791 mNetworksDefined++; // used only in the log() statement below.
792 }
793
Wink Saville5e56bc52013-07-29 15:00:57 -0700794 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700795
Robert Greenwalt50393202011-06-21 17:26:14 -0700796 mProtectedNetworks = new ArrayList<Integer>();
797 int[] protectedNetworks = context.getResources().getIntArray(
798 com.android.internal.R.array.config_protectedNetworks);
799 for (int p : protectedNetworks) {
800 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
801 mProtectedNetworks.add(p);
802 } else {
803 if (DBG) loge("Ignoring protectedNetwork " + p);
804 }
805 }
806
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900807 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
808 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700809
Erik Kline5a7c8a02017-04-30 19:36:15 +0900810 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800811
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700812 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
813
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700814 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700815 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100816 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700817 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700818 intentFilter.addAction(Intent.ACTION_USER_ADDED);
819 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000820 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700821 mContext.registerReceiverAsUser(
822 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000823 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
824 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900825
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700826 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700827 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700828 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700829 } catch (RemoteException e) {
830 loge("Error registering observer :" + e);
831 }
832
Erik Klineda4bfa82015-04-30 12:58:40 +0900833 mSettingsObserver = new SettingsObserver(mContext, mHandler);
834 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800835
John Spurlockbf991a82013-06-24 14:20:23 -0400836 mDataConnectionStats = new DataConnectionStats(mContext);
837 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400838
Jason Monkdecd2952013-10-10 14:02:51 -0400839 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700840
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400841 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900842
843 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900844 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
845 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900846
847 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
848 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
849 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
850 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
851 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
852 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
853 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900854
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900855 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900856 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900857 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700859
Erik Kline5a7c8a02017-04-30 19:36:15 +0900860 private Tethering makeTethering() {
861 // TODO: Move other elements into @Overridden getters.
862 final TetheringDependencies deps = new TetheringDependencies();
863 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
864 IoThread.get().getLooper(), new MockableSystemProperties(),
865 deps);
866 }
867
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900868 private NetworkRequest createInternetRequestForTransport(
869 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900870 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900871 netCap.addCapability(NET_CAPABILITY_INTERNET);
872 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900873 if (transportType > -1) {
874 netCap.addTransportType(transportType);
875 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900876 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900877 }
878
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900879 // Used only for testing.
880 // TODO: Delete this and either:
881 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
882 // changing ContentResolver to make registerContentObserver non-final).
883 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
884 // by subclassing SettingsObserver.
885 @VisibleForTesting
886 void updateMobileDataAlwaysOn() {
887 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
888 }
889
Erik Klineda4bfa82015-04-30 12:58:40 +0900890 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900891 final boolean enable = toBool(Settings.Global.getInt(
892 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900893 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
894 if (enable == isEnabled) {
895 return; // Nothing to do.
896 }
897
898 if (enable) {
899 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900900 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900901 } else {
902 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
903 }
904 }
905
906 private void registerSettingsCallbacks() {
907 // Watch for global HTTP proxy changes.
908 mSettingsObserver.observe(
909 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
910 EVENT_APPLY_GLOBAL_HTTP_PROXY);
911
912 // Watch for whether or not to keep mobile data always on.
913 mSettingsObserver.observe(
914 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
915 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
916 }
917
Robert Greenwalt34524f02014-05-18 16:22:10 -0700918 private synchronized int nextNetworkRequestId() {
919 return mNextNetworkRequestId++;
920 }
921
Paul Jensen67b0b072015-06-10 11:22:17 -0400922 @VisibleForTesting
923 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400924 synchronized (mNetworkForNetId) {
925 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
926 int netId = mNextNetId;
927 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
928 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500929 if (!mNetIdInUse.get(netId)) {
930 mNetIdInUse.put(netId, true);
931 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400932 }
933 }
934 }
935 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700936 }
937
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600938 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600940 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
941 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800942 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600943 state = nai.getNetworkState();
944 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800945 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600946 final NetworkInfo info = new NetworkInfo(networkType, 0,
947 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800948 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
949 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600950 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
951 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800952 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600953 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600954 return state;
955 } else {
956 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800957 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400958 }
959
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800960 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
961 if (network == null) {
962 return null;
963 }
964 synchronized (mNetworkForNetId) {
965 return mNetworkForNetId.get(network.netId);
966 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600967 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800968
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900969 private Network[] getVpnUnderlyingNetworks(int uid) {
970 if (!mLockdownEnabled) {
971 int user = UserHandle.getUserId(uid);
972 synchronized (mVpns) {
973 Vpn vpn = mVpns.get(user);
974 if (vpn != null && vpn.appliesToUid(uid)) {
975 return vpn.getUnderlyingNetworks();
976 }
977 }
978 }
979 return null;
980 }
981
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800982 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400983 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800984
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900985 final Network[] networks = getVpnUnderlyingNetworks(uid);
986 if (networks != null) {
987 // getUnderlyingNetworks() returns:
988 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
989 // empty array => the VPN explicitly said "no default network".
990 // non-empty array => the VPN specified one or more default networks; we use the
991 // first one.
992 if (networks.length > 0) {
993 nai = getNetworkAgentInfoForNetwork(networks[0]);
994 } else {
995 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800996 }
997 }
998
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800999 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001000 return nai.getNetworkState();
1001 } else {
1002 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001003 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001004 }
1005
1006 /**
1007 * Check if UID should be blocked from using the network with the given LinkProperties.
1008 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001009 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1010 boolean ignoreBlocked) {
1011 // Networks aren't blocked when ignoring blocked status
1012 if (ignoreBlocked) return false;
1013 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001014 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001015
1016 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001017 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001018
Robin Lee17e61832016-05-09 13:46:28 +01001019 synchronized (mVpns) {
1020 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1021 if (vpn != null && vpn.isBlockingUid(uid)) {
1022 return true;
1023 }
1024 }
1025
Robert Greenwalt12e67352014-05-13 21:41:06 -07001026 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001027 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001028 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001029 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001030 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001031
Felipe Lemed31a97f2016-05-06 14:53:50 -07001032 boolean allowed = true;
1033 // Check Data Saver Mode first...
1034 if (networkMetered) {
1035 if ((uidRules & RULE_REJECT_METERED) != 0) {
1036 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1037 // Explicitly blacklisted.
1038 allowed = false;
1039 } else {
1040 allowed = !mRestrictBackground
1041 || (uidRules & RULE_ALLOW_METERED) != 0
1042 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1043 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1044 + " mRestrictBackground=" + mRestrictBackground
1045 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1046 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1047 + ": " + allowed);
1048 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001049 }
Felipe Leme781ba142016-05-09 16:24:48 -07001050 // ...then power restrictions.
1051 if (allowed) {
1052 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001053 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001054 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001055 }
1056 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001057 }
1058
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001059 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001060 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1061 return;
1062 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001063 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001064 synchronized (mBlockedAppUids) {
1065 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001066 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001067 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001068 blocked = false;
1069 } else {
1070 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001071 }
1072 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001073 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1074 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1075 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001076 }
1077
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001078 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001079 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1080 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1081 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1082 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001083 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001084 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001085 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1086
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001087 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001088 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001089 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001090 if (mLockdownTracker != null) {
1091 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001092 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001093
1094 // TODO: apply metered state closer to NetworkAgentInfo
1095 final long token = Binder.clearCallingIdentity();
1096 try {
1097 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1098 } catch (RemoteException e) {
1099 } finally {
1100 Binder.restoreCallingIdentity(token);
1101 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001102 }
1103
1104 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 * Return NetworkInfo for the active (i.e., connected) network interface.
1106 * It is assumed that at most one network is active at a time. If more
1107 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001108 * @return the info for the active network, or {@code null} if none is
1109 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001111 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001113 enforceAccessPermission();
1114 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001115 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001116 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001117 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1118 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 }
1120
Paul Jensen31a94f42015-02-13 14:18:39 -05001121 @Override
1122 public Network getActiveNetwork() {
1123 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001124 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001125 }
1126
1127 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001128 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001129 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001130 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001131 }
1132
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001133 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001134 final int user = UserHandle.getUserId(uid);
1135 int vpnNetId = NETID_UNSET;
1136 synchronized (mVpns) {
1137 final Vpn vpn = mVpns.get(user);
1138 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1139 }
1140 NetworkAgentInfo nai;
1141 if (vpnNetId != NETID_UNSET) {
1142 synchronized (mNetworkForNetId) {
1143 nai = mNetworkForNetId.get(vpnNetId);
1144 }
1145 if (nai != null) return nai.network;
1146 }
1147 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001148 if (nai != null
1149 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1150 nai = null;
1151 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001152 return nai != null ? nai.network : null;
1153 }
1154
Lorenzo Colitti18660282016-07-04 12:55:44 +09001155 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001156 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1157 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001158 final int uid = Binder.getCallingUid();
1159 NetworkState state = getUnfilteredActiveNetworkState(uid);
1160 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001161 }
1162
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001163 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001164 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001165 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001166 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001167 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001168 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001169 }
1170
1171 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 public NetworkInfo getNetworkInfo(int networkType) {
1173 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001174 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001175 if (getVpnUnderlyingNetworks(uid) != null) {
1176 // A VPN is active, so we may need to return one of its underlying networks. This
1177 // information is not available in LegacyTypeTracker, so we have to get it from
1178 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001179 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001180 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001181 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001182 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001183 }
1184 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001185 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001186 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 }
1188
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001189 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001190 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001191 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001192 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001193 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001194 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001195 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001196 return state.networkInfo;
1197 } else {
1198 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001199 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001200 }
1201
1202 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 public NetworkInfo[] getAllNetworkInfo() {
1204 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001205 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001206 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1207 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001208 NetworkInfo info = getNetworkInfo(networkType);
1209 if (info != null) {
1210 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001213 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 }
1215
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001216 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001217 public Network getNetworkForType(int networkType) {
1218 enforceAccessPermission();
1219 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001220 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1221 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001222 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001223 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001224 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001225 }
1226
1227 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001228 public Network[] getAllNetworks() {
1229 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001230 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001231 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001232 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001233 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001234 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001235 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001236 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001237 }
1238
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001239 @Override
1240 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1241 // The basic principle is: if an app's traffic could possibly go over a
1242 // network, without the app doing anything multinetwork-specific,
1243 // (hence, by "default"), then include that network's capabilities in
1244 // the array.
1245 //
1246 // In the normal case, app traffic only goes over the system's default
1247 // network connection, so that's the only network returned.
1248 //
1249 // With a VPN in force, some app traffic may go into the VPN, and thus
1250 // over whatever underlying networks the VPN specifies, while other app
1251 // traffic may go over the system default network (e.g.: a split-tunnel
1252 // VPN, or an app disallowed by the VPN), so the set of networks
1253 // returned includes the VPN's underlying networks and the system
1254 // default.
1255 enforceAccessPermission();
1256
1257 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1258
1259 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001260 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001261 if (nc != null) {
1262 result.put(nai.network, nc);
1263 }
1264
1265 if (!mLockdownEnabled) {
1266 synchronized (mVpns) {
1267 Vpn vpn = mVpns.get(userId);
1268 if (vpn != null) {
1269 Network[] networks = vpn.getUnderlyingNetworks();
1270 if (networks != null) {
1271 for (Network network : networks) {
1272 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001273 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001274 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001275 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001276 }
1277 }
1278 }
1279 }
1280 }
1281 }
1282
1283 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1284 out = result.values().toArray(out);
1285 return out;
1286 }
1287
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001288 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001289 public boolean isNetworkSupported(int networkType) {
1290 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001291 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001292 }
1293
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001294 /**
1295 * Return LinkProperties for the active (i.e., connected) default
1296 * network interface. It is assumed that at most one default network
1297 * is active at a time. If more than one is active, it is indeterminate
1298 * which will be returned.
1299 * @return the ip properties for the active network, or {@code null} if
1300 * none is active
1301 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001302 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001303 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001304 enforceAccessPermission();
1305 final int uid = Binder.getCallingUid();
1306 NetworkState state = getUnfilteredActiveNetworkState(uid);
1307 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001308 }
1309
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001310 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001311 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001312 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001313 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1314 if (nai != null) {
1315 synchronized (nai) {
1316 return new LinkProperties(nai.linkProperties);
1317 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001318 }
1319 return null;
1320 }
1321
Robert Greenwalt12e67352014-05-13 21:41:06 -07001322 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001323 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001324 public LinkProperties getLinkProperties(Network network) {
1325 enforceAccessPermission();
Hugo Benichi29551722017-04-06 16:01:44 +09001326 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1327 }
1328
1329 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1330 if (nai == null) {
1331 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001332 }
Hugo Benichi29551722017-04-06 16:01:44 +09001333 synchronized (nai) {
1334 return new LinkProperties(nai.linkProperties);
1335 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001336 }
1337
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001338 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001339 if (nai != null) {
1340 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001341 if (nai.networkCapabilities != null) {
1342 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001343 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001344 }
1345 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001346 return null;
1347 }
1348
1349 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001350 public NetworkCapabilities getNetworkCapabilities(Network network) {
1351 enforceAccessPermission();
1352 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1353 }
1354
1355 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001356 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001357 // Require internal since we're handing out IMSI details
1358 enforceConnectivityInternalPermission();
1359
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001360 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001361 for (Network network : getAllNetworks()) {
1362 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1363 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001364 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001365 }
1366 }
1367 return result.toArray(new NetworkState[result.size()]);
1368 }
1369
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001370 @Override
1371 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1372 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001373 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001374 final long token = Binder.clearCallingIdentity();
1375 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001376 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1377 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001378 try {
1379 return mPolicyManager.getNetworkQuotaInfo(state);
1380 } catch (RemoteException e) {
1381 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001382 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001383 return null;
1384 } finally {
1385 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001386 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001387 }
1388
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001389 @Override
1390 public boolean isActiveNetworkMetered() {
1391 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001392
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001393 final NetworkInfo info = getActiveNetworkInfo();
1394 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001395 }
1396
Jeff Sharkey216c1812012-08-05 14:29:23 -07001397 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1398 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001399 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001400 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001401 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001402 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001403 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001404
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001405 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 * Ensure that a network route exists to deliver traffic to the specified
1407 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001408 * @param networkType the type of the network over which traffic to the
1409 * specified host is to be routed
1410 * @param hostAddress the IP address of the host to which the route is
1411 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 * @return {@code true} on success, {@code false} on failure
1413 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001414 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001415 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001417 if (mProtectedNetworks.contains(networkType)) {
1418 enforceConnectivityInternalPermission();
1419 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001420
Chad Brubakerc0234532014-02-14 13:24:29 -08001421 InetAddress addr;
1422 try {
1423 addr = InetAddress.getByAddress(hostAddress);
1424 } catch (UnknownHostException e) {
1425 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1426 return false;
1427 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001430 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 return false;
1432 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001433
1434 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1435 if (nai == null) {
1436 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1437 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1438 } else {
1439 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1440 }
1441 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001442 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001443
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001444 DetailedState netState;
1445 synchronized (nai) {
1446 netState = nai.networkInfo.getDetailedState();
1447 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001448
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001449 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001450 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001451 log("requestRouteToHostAddress on down network "
1452 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001453 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001454 }
1455 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001457
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001458 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001459 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001460 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001461 LinkProperties lp;
1462 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001463 synchronized (nai) {
1464 lp = nai.linkProperties;
1465 netId = nai.network.netId;
1466 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001467 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001468 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1469 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001470 } finally {
1471 Binder.restoreCallingIdentity(token);
1472 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001473 }
1474
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001475 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001476 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001477 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001478 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001479 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001480 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001481 if (bestRoute.getGateway().equals(addr)) {
1482 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001483 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001484 } else {
1485 // if we will connect to this through another route, add a direct route
1486 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001487 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001488 }
1489 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001490 if (DBG) log("Adding legacy route " + bestRoute +
1491 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001492 try {
1493 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1494 } catch (Exception e) {
1495 // never crash - catch them all
1496 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001497 return false;
1498 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001499 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 }
1501
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001502 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1503 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001504 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001505 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001506 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001507 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001508 }
1509
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001510 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001511 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001512 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001513 if (oldRules == uidRules) return;
1514
Felipe Leme781ba142016-05-09 16:24:48 -07001515 if (uidRules == RULE_NONE) {
1516 mUidRules.delete(uid);
1517 } else {
1518 mUidRules.put(uid, uidRules);
1519 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001520 }
1521
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001522 // TODO: notify UID when it has requested targeted updates
1523 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001524
1525 @Override
1526 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001527 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001528 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001529 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001530 }
1531
1532 synchronized (mRulesLock) {
1533 mMeteredIfaces.clear();
1534 for (String iface : meteredIfaces) {
1535 mMeteredIfaces.add(iface);
1536 }
1537 }
1538 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001539
1540 @Override
1541 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1542 // caller is NPMS, since we only register with them
1543 if (LOGD_RULES) {
1544 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1545 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001546
1547 synchronized (mRulesLock) {
1548 mRestrictBackground = restrictBackground;
1549 }
1550
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001551 if (restrictBackground) {
1552 log("onRestrictBackgroundChanged(true): disabling tethering");
1553 mTethering.untetherAll();
1554 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001555 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001556
1557 @Override
1558 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1559 if (LOGD_RULES) {
1560 // caller is NPMS, since we only register with them
1561 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1562 + whitelisted + ")");
1563 }
1564 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001565 @Override
1566 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1567 if (LOGD_RULES) {
1568 // caller is NPMS, since we only register with them
1569 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1570 + blacklisted + ")");
1571 }
1572 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001573 };
1574
Robin Lee3b3dd942015-05-12 18:14:58 +01001575 /**
1576 * Require that the caller is either in the same user or has appropriate permission to interact
1577 * across users.
1578 *
1579 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1580 */
1581 private void enforceCrossUserPermission(int userId) {
1582 if (userId == UserHandle.getCallingUserId()) {
1583 // Not a cross-user call.
1584 return;
1585 }
1586 mContext.enforceCallingOrSelfPermission(
1587 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1588 "ConnectivityService");
1589 }
1590
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001591 private void enforceInternetPermission() {
1592 mContext.enforceCallingOrSelfPermission(
1593 android.Manifest.permission.INTERNET,
1594 "ConnectivityService");
1595 }
1596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001598 mContext.enforceCallingOrSelfPermission(
1599 android.Manifest.permission.ACCESS_NETWORK_STATE,
1600 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 }
1602
1603 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001604 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001607 private void enforceTetherAccessPermission() {
1608 mContext.enforceCallingOrSelfPermission(
1609 android.Manifest.permission.ACCESS_NETWORK_STATE,
1610 "ConnectivityService");
1611 }
1612
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001613 private void enforceConnectivityInternalPermission() {
1614 mContext.enforceCallingOrSelfPermission(
1615 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1616 "ConnectivityService");
1617 }
1618
Hugo Benichi514da602016-07-19 15:59:27 +09001619 private void enforceConnectivityRestrictedNetworksPermission() {
1620 try {
1621 mContext.enforceCallingOrSelfPermission(
1622 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1623 "ConnectivityService");
1624 return;
1625 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1626 enforceConnectivityInternalPermission();
1627 }
1628
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001629 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001630 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001631 }
1632
Lorenzo Colitti18660282016-07-04 12:55:44 +09001633 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001634 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001635 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001636 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001637 }
1638
1639 private void sendInetConditionBroadcast(NetworkInfo info) {
1640 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1641 }
1642
Wink Saville628b0852011-08-04 15:01:58 -07001643 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001644 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001645 info = new NetworkInfo(info);
1646 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001647 }
1648
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001649 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001650 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001651 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 if (info.isFailover()) {
1653 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1654 info.setFailover(false);
1655 }
1656 if (info.getReason() != null) {
1657 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1658 }
1659 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001660 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1661 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001663 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001664 return intent;
1665 }
1666
1667 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1668 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1669 }
1670
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001671 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001672 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1673 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1674 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001675 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001676 final long ident = Binder.clearCallingIdentity();
1677 try {
1678 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1679 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1680 } finally {
1681 Binder.restoreCallingIdentity(ident);
1682 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001683 }
1684
Mike Lockwood0f79b542009-08-14 14:18:49 -04001685 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001686 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001687 if (!mSystemReady) {
1688 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001689 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001690 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001691 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001692 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001693 }
1694
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001695 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001696 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001697 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001698 final NetworkInfo ni = intent.getParcelableExtra(
1699 ConnectivityManager.EXTRA_NETWORK_INFO);
1700 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1701 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1702 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001703 } else {
1704 BroadcastOptions opts = BroadcastOptions.makeBasic();
1705 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1706 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001707 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001708 final IBatteryStats bs = BatteryStatsService.getService();
1709 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001710 bs.noteConnectivityChanged(intent.getIntExtra(
1711 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1712 ni != null ? ni.getState().toString() : "?");
1713 } catch (RemoteException e) {
1714 }
1715 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001716 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001717 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001718 } finally {
1719 Binder.restoreCallingIdentity(ident);
1720 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001721 }
1722 }
1723
1724 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001725 loadGlobalProxy();
1726
Hugo Benichi20035e02017-04-26 14:53:28 +09001727 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001728 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001729 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001730 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001731 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001732 }
1733 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001734 // load the global proxy at startup
1735 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001736
Robin Lee244ce8e2016-01-05 18:03:46 +00001737 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1738 // for user to unlock device too.
1739 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001740
Erik Klineda4bfa82015-04-30 12:58:40 +09001741 // Configure whether mobile data is always on.
1742 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1743
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001744 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001745
1746 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
1748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001750 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001751 *
1752 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001753 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001754 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001755 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1756 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001757
1758 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001759 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001760
Robert Greenwalt7b816022014-04-18 15:25:25 -07001761 if (networkAgent.networkCapabilities.hasTransport(
1762 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001763 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1764 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001765 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001766 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001767 } else if (networkAgent.networkCapabilities.hasTransport(
1768 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001769 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1770 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001771 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001772 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001773 } else {
1774 // do not track any other networks
1775 timeout = 0;
1776 }
1777
Robert Greenwalt7b816022014-04-18 15:25:25 -07001778 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001779 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001780 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001781 } catch (Exception e) {
1782 // You shall not crash!
1783 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001784 }
1785 }
1786 }
1787
1788 /**
1789 * Remove data activity tracking when network disconnects.
1790 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001791 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1792 final String iface = networkAgent.linkProperties.getInterfaceName();
1793 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001794
Robert Greenwalt7b816022014-04-18 15:25:25 -07001795 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1796 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001797 try {
1798 // the call fails silently if no idletimer setup for this interface
1799 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001800 } catch (Exception e) {
1801 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001802 }
1803 }
1804 }
1805
1806 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001807 * Reads the network specific MTU size from reources.
1808 * and set it on it's iface.
1809 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001810 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1811 final String iface = newLp.getInterfaceName();
1812 final int mtu = newLp.getMtu();
Pierre Imaiaccd5fc2016-02-08 16:01:40 +09001813 if (oldLp == null && mtu == 0) {
1814 // Silently ignore unset MTU value.
1815 return;
1816 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001817 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1818 if (VDBG) log("identical MTU - not setting");
1819 return;
1820 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001821 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001822 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001823 return;
1824 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001825
w1997615afd812014-08-05 15:18:11 -07001826 // Cannot set MTU without interface name
1827 if (TextUtils.isEmpty(iface)) {
1828 loge("Setting MTU size with null iface.");
1829 return;
1830 }
1831
Robert Greenwalt7b816022014-04-18 15:25:25 -07001832 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001833 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001834 mNetd.setMtu(iface, mtu);
1835 } catch (Exception e) {
1836 Slog.e(TAG, "exception in setMtu()" + e);
1837 }
1838 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001839
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001840 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001841 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1842
1843 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001844 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001845 protected MockableSystemProperties getSystemProperties() {
1846 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001847 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001848
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001849 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1850 if (isDefaultNetwork(nai) == false) {
1851 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001852 }
1853
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001854 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1855 String[] values = null;
1856 if (tcpBufferSizes != null) {
1857 values = tcpBufferSizes.split(",");
1858 }
1859
1860 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001861 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001862 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1863 values = tcpBufferSizes.split(",");
1864 }
1865
1866 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1867
1868 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001869 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001870
1871 final String prefix = "/sys/kernel/ipv4/tcp_";
1872 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1873 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1874 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1875 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1876 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1877 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1878 mCurrentTcpBufferSizes = tcpBufferSizes;
1879 } catch (IOException e) {
1880 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001881 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001882
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001883 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001884 Settings.Global.TCP_DEFAULT_INIT_RWND,
1885 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001886 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1887 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001888 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001889 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001890 }
1891
Mattias Falk8b47b362011-08-23 14:15:13 +02001892 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001893 /*
1894 * Tell the VMs to toss their DNS caches
1895 */
1896 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1897 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001898 /*
1899 * Connectivity events can happen before boot has completed ...
1900 */
1901 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001902 final long ident = Binder.clearCallingIdentity();
1903 try {
1904 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1905 } finally {
1906 Binder.restoreCallingIdentity(ident);
1907 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001908 }
1909
Robert Greenwalt562cc542014-05-15 18:07:26 -07001910 @Override
1911 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001912 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001913 NETWORK_RESTORE_DELAY_PROP_NAME);
1914 if(restoreDefaultNetworkDelayStr != null &&
1915 restoreDefaultNetworkDelayStr.length() != 0) {
1916 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001917 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001918 } catch (NumberFormatException e) {
1919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001921 // if the system property isn't set, use the value for the apn type
1922 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1923
1924 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1925 (mNetConfigs[networkType] != null)) {
1926 ret = mNetConfigs[networkType].restoreTime;
1927 }
1928 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 }
1930
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001931 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001932 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001933 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001934 }
1935 return false;
1936 }
1937
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001938 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1939 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1940 final long DIAG_TIME_MS = 5000;
1941 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1942 // Start gathering diagnostic information.
1943 netDiags.add(new NetworkDiagnostics(
1944 nai.network,
1945 new LinkProperties(nai.linkProperties), // Must be a copy.
1946 DIAG_TIME_MS));
1947 }
1948
1949 for (NetworkDiagnostics netDiag : netDiags) {
1950 pw.println();
1951 netDiag.waitForMeasurements();
1952 netDiag.dump(pw);
1953 }
1954 }
1955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001957 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1958 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001959 if (mContext.checkCallingOrSelfPermission(
1960 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001962 pw.println("Permission Denial: can't dump ConnectivityService " +
1963 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1964 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 return;
1966 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001967
Erik Kline7747fd42017-05-12 16:52:48 +09001968 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001969 dumpNetworkDiagnostics(pw);
1970 return;
Erik Klineee363c42017-05-29 09:11:03 +09001971 } else if (argsContain(args, TETHERING_ARG)) {
1972 mTethering.dump(fd, pw, args);
1973 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001974 }
Erik Kline379747a2015-06-05 17:47:34 +09001975
Lorenzo Colittie3805462015-06-03 11:18:24 +09001976 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001977 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001978 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001979 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001980 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001981 pw.println();
1982
Paul Jensen85cf78e2015-06-25 13:25:07 -04001983 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001984 pw.print("Active default network: ");
1985 if (defaultNai == null) {
1986 pw.println("none");
1987 } else {
1988 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001990 pw.println();
1991
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001992 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001993 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001994 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1995 pw.println(nai.toString());
1996 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001997 pw.println(String.format(
1998 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1999 nai.numForegroundNetworkRequests(),
2000 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2001 nai.numBackgroundNetworkRequests(),
2002 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002003 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002004 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2005 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002006 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002007 pw.decreaseIndent();
2008 pw.println("Lingered:");
2009 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002010 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002011 pw.decreaseIndent();
2012 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002013 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002014 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002015 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002016
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002017 pw.println("Metered Interfaces:");
2018 pw.increaseIndent();
2019 for (String value : mMeteredIfaces) {
2020 pw.println(value);
2021 }
2022 pw.decreaseIndent();
2023 pw.println();
2024
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002025 pw.print("Restrict background: ");
2026 pw.println(mRestrictBackground);
2027 pw.println();
2028
Felipe Leme46c4fc32016-05-04 09:21:43 -07002029 pw.println("Status for known UIDs:");
2030 pw.increaseIndent();
2031 final int size = mUidRules.size();
2032 for (int i = 0; i < size; i++) {
2033 final int uid = mUidRules.keyAt(i);
2034 pw.print("UID=");
2035 pw.print(uid);
2036 final int uidRules = mUidRules.get(uid, RULE_NONE);
2037 pw.print(" rules=");
2038 pw.print(uidRulesToString(uidRules));
2039 pw.println();
2040 }
2041 pw.println();
2042 pw.decreaseIndent();
2043
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002044 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002045 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002046 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2047 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002048 }
2049 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002050 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002051
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002052 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002053
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002054 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002055 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002056
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002057 pw.println();
2058 mKeepaliveTracker.dump(pw);
2059
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002060 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002061 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002062
Erik Kline7747fd42017-05-12 16:52:48 +09002063 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002064 pw.println();
2065 synchronized (mValidationLogs) {
2066 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002067 for (ValidationLog p : mValidationLogs) {
2068 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002069 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002070 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002071 pw.decreaseIndent();
2072 }
2073 }
Erik Kline7523eb32015-07-09 18:24:03 +09002074
2075 pw.println();
2076 pw.println("mNetworkRequestInfoLogs (most recent first):");
2077 pw.increaseIndent();
2078 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2079 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002080
2081 pw.println();
2082 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2083 pw.increaseIndent();
2084 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2085 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002086
2087 pw.println();
2088 pw.println("NetTransition WakeLock activity (most recent first):");
2089 pw.increaseIndent();
2090 mWakelockLogs.reverseDump(fd, pw, args);
2091 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 }
2094
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002095 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002096 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002097 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002098 if (officialNai != null && officialNai.equals(nai)) return true;
2099 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002100 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002101 " - " + nai);
2102 }
2103 return false;
2104 }
2105
Robert Greenwalt42acef32009-08-12 16:08:25 -07002106 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002107 private class NetworkStateTrackerHandler extends Handler {
2108 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002109 super(looper);
2110 }
2111
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002112 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002114 default:
2115 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002116 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002117 handleAsyncChannelHalfConnect(msg);
2118 break;
2119 }
2120 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2121 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2122 if (nai != null) nai.asyncChannel.disconnect();
2123 break;
2124 }
2125 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2126 handleAsyncChannelDisconnected(msg);
2127 break;
2128 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002129 }
2130 return true;
2131 }
2132
2133 private void maybeHandleNetworkAgentMessage(Message msg) {
2134 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2135 if (nai == null) {
2136 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002137 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002138 }
2139 return;
2140 }
2141
2142 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002144 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2145 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002146 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2147 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002148 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002149 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002150 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002151 break;
2152 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002153 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002154 if (VDBG) {
2155 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002156 "; created=" + nai.created +
2157 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002158 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002159 LinkProperties oldLp = nai.linkProperties;
2160 synchronized (nai) {
2161 nai.linkProperties = (LinkProperties)msg.obj;
2162 }
Robin Lee585e2482016-05-01 23:00:00 +01002163 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002164 break;
2165 }
2166 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002167 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002168 updateNetworkInfo(nai, info);
2169 break;
2170 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002171 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002172 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002173 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002174 break;
2175 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002176 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002177 try {
2178 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002179 } catch (Exception e) {
2180 // Never crash!
2181 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002182 }
2183 break;
2184 }
2185 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002186 try {
2187 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002188 } catch (Exception e) {
2189 // Never crash!
2190 loge("Exception in removeVpnUidRanges: " + e);
2191 }
2192 break;
2193 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002194 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002195 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2196 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002197 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002198 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002199 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002200 break;
2201 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002202 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002203 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2204 break;
2205 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002206 }
2207 }
2208
2209 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2210 switch (msg.what) {
2211 default:
2212 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002213 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002214 final NetworkAgentInfo nai;
2215 synchronized (mNetworkForNetId) {
2216 nai = mNetworkForNetId.get(msg.arg2);
2217 }
2218 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002219 final boolean valid =
2220 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002221 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002222 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2223 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002224 if (valid != nai.lastValidated) {
2225 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002226 nai.lastValidated = valid;
2227 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002228 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002229 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2230 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002231 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002232 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002233 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002234 Bundle redirectUrlBundle = new Bundle();
2235 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002236 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002237 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002238 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002239 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002240 if (wasValidated && !nai.lastValidated) {
2241 handleNetworkUnvalidated(nai);
2242 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002243 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002244 break;
2245 }
Paul Jensen869868be2014-05-15 10:33:05 -04002246 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002247 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002248 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002249 final NetworkAgentInfo nai;
2250 synchronized (mNetworkForNetId) {
2251 nai = mNetworkForNetId.get(netId);
2252 }
Calvin On1f64f3f2016-10-11 15:10:46 -07002253 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002254 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002255 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002256 nai.lastCaptivePortalDetected = visible;
2257 nai.everCaptivePortalDetected |= visible;
Calvin On1f64f3f2016-10-11 15:10:46 -07002258 if (nai.lastCaptivePortalDetected &&
2259 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2260 if (DBG) log("Avoiding captive portal network: " + nai.name());
2261 nai.asyncChannel.sendMessage(
2262 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2263 teardownUnneededNetwork(nai);
2264 break;
2265 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002266 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002267 }
2268 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002269 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002270 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002271 if (nai == null) {
2272 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2273 break;
2274 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002275 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002276 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002277 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002278 }
Paul Jensen869868be2014-05-15 10:33:05 -04002279 }
Paul Jensen869868be2014-05-15 10:33:05 -04002280 break;
2281 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002282 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002283 return true;
2284 }
2285
Calvin On1f64f3f2016-10-11 15:10:46 -07002286 private int getCaptivePortalMode() {
2287 return Settings.Global.getInt(mContext.getContentResolver(),
2288 Settings.Global.CAPTIVE_PORTAL_MODE,
2289 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2290 }
2291
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002292 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2293 switch (msg.what) {
2294 default:
2295 return false;
2296 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2297 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2298 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2299 handleLingerComplete(nai);
2300 }
2301 break;
2302 }
2303 }
2304 return true;
2305 }
2306
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002307 @Override
2308 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002309 if (!maybeHandleAsyncChannelMessage(msg) &&
2310 !maybeHandleNetworkMonitorMessage(msg) &&
2311 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002312 maybeHandleNetworkAgentMessage(msg);
2313 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002314 }
2315 }
2316
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002317 private void updateLingerState(NetworkAgentInfo nai, long now) {
2318 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2319 // 2. If the network was lingering and there are now requests, unlinger it.
2320 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2321 // one lingered request, start lingering.
2322 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002323 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002324 if (DBG) log("Unlingering " + nai.name());
2325 nai.unlinger();
2326 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002327 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002328 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002329 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002330 nai.linger();
2331 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2332 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2333 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002334 }
2335
Robert Greenwalt7b816022014-04-18 15:25:25 -07002336 private void handleAsyncChannelHalfConnect(Message msg) {
2337 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002338 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002339 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2340 if (VDBG) log("NetworkFactory connected");
2341 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002342 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002343 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002344 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002345 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002346 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002347 }
2348 } else {
2349 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002350 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002351 }
2352 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2353 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2354 if (VDBG) log("NetworkAgent connected");
2355 // A network agent has requested a connection. Establish the connection.
2356 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2357 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2358 } else {
2359 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002360 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002361 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002362 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002363 synchronized (mNetworkForNetId) {
2364 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002365 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002366 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002367 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002368 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002369 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002370 }
2371 }
2372 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002373
Robert Greenwalt7b816022014-04-18 15:25:25 -07002374 private void handleAsyncChannelDisconnected(Message msg) {
2375 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2376 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002377 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002378 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002379 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002380 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002381 // TODO - if we move the logic to the network agent (have them disconnect
2382 // because they lost all their requests or because their score isn't good)
2383 // then they would disconnect organically, report their new state and then
2384 // disconnect the channel.
2385 if (nai.networkInfo.isConnected()) {
2386 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2387 null, null);
2388 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002389 final boolean wasDefault = isDefaultNetwork(nai);
2390 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002391 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002392 // Log default network disconnection before required book-keeping.
2393 // Let rematchAllNetworksAndRequests() below record a new default network event
2394 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2395 // whose timestamps tell how long it takes to recover a default network.
2396 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002397 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002398 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002399 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2400 // by other networks that are already connected. Perhaps that can be done by
2401 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2402 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002403 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002404 mKeepaliveTracker.handleStopAllKeepalives(nai,
2405 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002406 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2407 // Disable wakeup packet monitoring for each interface.
2408 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2409 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002410 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002411 mNetworkAgentInfos.remove(msg.replyTo);
2412 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002413 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002414 // Remove the NetworkAgent, but don't mark the netId as
2415 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002416 mNetworkForNetId.remove(nai.network.netId);
2417 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002418 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002419 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2420 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002421 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2422 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2423 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002424 sendUpdatedScoreToFactories(request, 0);
2425 }
2426 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002427 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002428 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002429 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002430 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002431 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002432 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002433 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002434 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002435 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002436 if (nai.created) {
2437 // Tell netd to clean up the configuration for this network
2438 // (routing rules, DNS, etc).
2439 // This may be slow as it requires a lot of netd shelling out to ip and
2440 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2441 // after we've rematched networks with requests which should make a potential
2442 // fallback network the default or requested a new network from the
2443 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2444 // long time.
2445 try {
2446 mNetd.removeNetwork(nai.network.netId);
2447 } catch (Exception e) {
2448 loge("Exception removing network: " + e);
2449 }
2450 }
2451 synchronized (mNetworkForNetId) {
2452 mNetIdInUse.delete(nai.network.netId);
2453 }
2454 } else {
2455 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2456 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002457 }
2458 }
2459
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002460 // If this method proves to be too slow then we can maintain a separate
2461 // pendingIntent => NetworkRequestInfo map.
2462 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2463 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2464 Intent intent = pendingIntent.getIntent();
2465 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2466 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2467 if (existingPendingIntent != null &&
2468 existingPendingIntent.getIntent().filterEquals(intent)) {
2469 return entry.getValue();
2470 }
2471 }
2472 return null;
2473 }
2474
2475 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2476 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2477
2478 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2479 if (existingRequest != null) { // remove the existing request.
2480 if (DBG) log("Replacing " + existingRequest.request + " with "
2481 + nri.request + " because their intents matched.");
2482 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2483 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002484 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002485 }
2486
Erik Klineda4bfa82015-04-30 12:58:40 +09002487 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002488 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002489 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002490 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002491 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002492 if (nri.request.networkCapabilities.hasSignalStrength() &&
2493 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2494 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002495 }
2496 }
2497 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002498 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002499 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002500 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002501 }
2502 }
2503
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002504 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2505 int callingUid) {
2506 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2507 if (nri != null) {
2508 handleReleaseNetworkRequest(nri.request, callingUid);
2509 }
2510 }
2511
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002512 // Determines whether the network is the best (or could become the best, if it validated), for
2513 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2514 // on the value of reason:
2515 //
2516 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2517 // then it should be torn down.
2518 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2519 // then it should be lingered.
2520 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2521 final int numRequests;
2522 switch (reason) {
2523 case TEARDOWN:
2524 numRequests = nai.numRequestNetworkRequests();
2525 break;
2526 case LINGER:
2527 numRequests = nai.numForegroundNetworkRequests();
2528 break;
2529 default:
2530 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2531 return true;
2532 }
2533
2534 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002535 return false;
2536 }
Paul Jensene0988542015-06-25 15:30:08 -04002537 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002538 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2539 // Background requests don't affect lingering.
2540 continue;
2541 }
2542
Paul Jensene0988542015-06-25 15:30:08 -04002543 // If this Network is already the highest scoring Network for a request, or if
2544 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002545 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002546 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002547 // Note that this catches two important cases:
2548 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2549 // is currently satisfying the request. This is desirable when
2550 // cellular ends up validating but WiFi does not.
2551 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002552 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002553 // WiFi ends up validating and out scoring cellular.
2554 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2555 nai.getCurrentScoreAsValidated())) {
2556 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002557 }
2558 }
Paul Jensene0988542015-06-25 15:30:08 -04002559 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002560 }
2561
Erik Klineacdd6392016-07-07 16:50:58 +09002562 private NetworkRequestInfo getNriForAppRequest(
2563 NetworkRequest request, int callingUid, String requestedOperation) {
2564 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2565
Robert Greenwalt9258c642014-03-26 16:47:06 -07002566 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002567 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002568 log(String.format("UID %d attempted to %s for unowned request %s",
2569 callingUid, requestedOperation, nri));
2570 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002571 }
Erik Klineacdd6392016-07-07 16:50:58 +09002572 }
2573
2574 return nri;
2575 }
2576
Erik Kline3841a482015-11-25 12:49:38 +09002577 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002578 if (mNetworkRequests.get(nri.request) == null) {
2579 return;
Erik Kline3841a482015-11-25 12:49:38 +09002580 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002581 if (mNetworkForRequestId.get(nri.request.requestId) != null) {
2582 return;
2583 }
2584 if (VDBG || (DBG && nri.request.isRequest())) {
2585 log("releasing " + nri.request + " (timeout)");
2586 }
2587 handleRemoveNetworkRequest(nri);
2588 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline3841a482015-11-25 12:49:38 +09002589 }
2590
Erik Klineacdd6392016-07-07 16:50:58 +09002591 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002592 final NetworkRequestInfo nri =
2593 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2594 if (nri == null) {
2595 return;
Erik Kline3841a482015-11-25 12:49:38 +09002596 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002597 if (VDBG || (DBG && nri.request.isRequest())) {
2598 log("releasing " + nri.request + " (release request)");
2599 }
2600 handleRemoveNetworkRequest(nri);
Erik Kline3841a482015-11-25 12:49:38 +09002601 }
Erik Klineacdd6392016-07-07 16:50:58 +09002602
Hugo Benichidba33db2017-03-23 22:40:44 +09002603 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002604 nri.unlinkDeathRecipient();
Erik Kline3841a482015-11-25 12:49:38 +09002605 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002606 synchronized (mUidToNetworkRequestCount) {
2607 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2608 if (requests < 1) {
2609 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2610 nri.mUid);
2611 } else if (requests == 1) {
2612 mUidToNetworkRequestCount.removeAt(
2613 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2614 } else {
2615 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2616 }
2617 }
2618 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2619 if (nri.request.isRequest()) {
2620 boolean wasKept = false;
2621 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2622 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002623 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002624 nai.removeRequest(nri.request.requestId);
2625 if (VDBG) {
2626 log(" Removing from current network " + nai.name() +
2627 ", leaving " + nai.numNetworkRequests() + " requests.");
2628 }
2629 // If there are still lingered requests on this network, don't tear it down,
2630 // but resume lingering instead.
2631 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002632 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002633 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2634 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002635 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002636 wasKept = true;
2637 }
2638 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002639 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2640 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002641 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002642 }
Erik Klineacdd6392016-07-07 16:50:58 +09002643 }
2644
2645 // TODO: remove this code once we know that the Slog.wtf is never hit.
2646 //
2647 // Find all networks that are satisfying this request and remove the request
2648 // from their request lists.
2649 // TODO - it's my understanding that for a request there is only a single
2650 // network satisfying it, so this loop is wasteful
2651 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2652 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2653 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2654 otherNai.name() + ", but mNetworkAgentInfos says " +
2655 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002656 }
2657 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002658
Erik Klineacdd6392016-07-07 16:50:58 +09002659 // Maintain the illusion. When this request arrived, we might have pretended
2660 // that a network connected to serve it, even though the network was already
2661 // connected. Now that this request has gone away, we might have to pretend
2662 // that the network disconnected. LegacyTypeTracker will generate that
2663 // phantom disconnect for this type.
2664 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2665 boolean doRemove = true;
2666 if (wasKept) {
2667 // check if any of the remaining requests for this network are for the
2668 // same legacy type - if so, don't remove the nai
2669 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2670 NetworkRequest otherRequest = nai.requestAt(i);
2671 if (otherRequest.legacyType == nri.request.legacyType &&
2672 otherRequest.isRequest()) {
2673 if (DBG) log(" still have other legacy request - leaving");
2674 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002675 }
2676 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002677 }
2678
Erik Klineacdd6392016-07-07 16:50:58 +09002679 if (doRemove) {
2680 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002681 }
2682 }
Erik Klineacdd6392016-07-07 16:50:58 +09002683
2684 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2685 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2686 nri.request);
2687 }
2688 } else {
2689 // listens don't have a singular affectedNetwork. Check all networks to see
2690 // if this listen request applies and remove it.
2691 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2692 nai.removeRequest(nri.request.requestId);
2693 if (nri.request.networkCapabilities.hasSignalStrength() &&
2694 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2695 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2696 }
2697 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002698 }
2699 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002700
Lorenzo Colitti18660282016-07-04 12:55:44 +09002701 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002702 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2703 enforceConnectivityInternalPermission();
2704 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002705 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002706 }
2707
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002708 @Override
2709 public void setAvoidUnvalidated(Network network) {
2710 enforceConnectivityInternalPermission();
2711 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2712 }
2713
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002714 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2715 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2716 " accept=" + accept + " always=" + always);
2717
2718 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2719 if (nai == null) {
2720 // Nothing to do.
2721 return;
2722 }
2723
2724 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002725 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002726 return;
2727 }
2728
2729 if (!nai.networkMisc.explicitlySelected) {
2730 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2731 }
2732
2733 if (accept != nai.networkMisc.acceptUnvalidated) {
2734 int oldScore = nai.getCurrentScore();
2735 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002736 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002737 sendUpdatedScoreToFactories(nai);
2738 }
2739
2740 if (always) {
2741 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002742 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002743 }
2744
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002745 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002746 // Tell the NetworkAgent to not automatically reconnect to the network.
2747 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2748 // Teardown the nework.
2749 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002750 }
2751
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002752 }
2753
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002754 private void handleSetAvoidUnvalidated(Network network) {
2755 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2756 if (nai == null || nai.lastValidated) {
2757 // Nothing to do. The network either disconnected or revalidated.
2758 return;
2759 }
2760 if (!nai.avoidUnvalidated) {
2761 int oldScore = nai.getCurrentScore();
2762 nai.avoidUnvalidated = true;
2763 rematchAllNetworksAndRequests(nai, oldScore);
2764 sendUpdatedScoreToFactories(nai);
2765 }
2766 }
2767
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002768 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002769 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002770 mHandler.sendMessageDelayed(
2771 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2772 PROMPT_UNVALIDATED_DELAY_MS);
2773 }
2774
Lorenzo Colitti2965d332017-04-27 14:30:21 +09002775 @Override
2776 public void startCaptivePortalApp(Network network) {
2777 enforceConnectivityInternalPermission();
2778 mHandler.post(() -> {
2779 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2780 if (nai == null) return;
2781 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2782 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2783 });
2784 }
2785
Hugo Benichic8e9e122016-09-14 23:23:08 +00002786 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002787 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002788 }
2789
Erik Kline065ab6e2016-10-02 18:02:14 +09002790 private void rematchForAvoidBadWifiUpdate() {
2791 rematchAllNetworksAndRequests(null, 0);
2792 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2793 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2794 sendUpdatedScoreToFactories(nai);
2795 }
2796 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002797 }
2798
Erik Kline065ab6e2016-10-02 18:02:14 +09002799 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002800 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002801 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002802 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002803 if (!configRestrict) {
2804 pw.println("Bad Wi-Fi avoidance: unrestricted");
2805 return;
2806 }
2807
2808 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2809 pw.increaseIndent();
2810 pw.println("Config restrict: " + configRestrict);
2811
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002812 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002813 String description;
2814 // Can't use a switch statement because strings are legal case labels, but null is not.
2815 if ("0".equals(value)) {
2816 description = "get stuck";
2817 } else if (value == null) {
2818 description = "prompt";
2819 } else if ("1".equals(value)) {
2820 description = "avoid";
2821 } else {
2822 description = value + " (?)";
2823 }
2824 pw.println("User setting: " + description);
2825 pw.println("Network overrides:");
2826 pw.increaseIndent();
2827 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2828 if (nai.avoidUnvalidated) {
2829 pw.println(nai.name());
2830 }
2831 }
2832 pw.decreaseIndent();
2833 pw.decreaseIndent();
2834 }
2835
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002836 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2837 final String action;
2838 switch (type) {
2839 case NO_INTERNET:
2840 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2841 break;
2842 case LOST_INTERNET:
2843 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2844 break;
2845 default:
2846 Slog.wtf(TAG, "Unknown notification type " + type);
2847 return;
2848 }
2849
2850 Intent intent = new Intent(action);
2851 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2852 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2853 intent.setClassName("com.android.settings",
2854 "com.android.settings.wifi.WifiNoInternetDialog");
2855
2856 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2857 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2858 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2859 }
2860
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002861 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002862 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002863 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2864
2865 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2866 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002867 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002868 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002869 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2870 return;
2871 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002872 showValidationNotification(nai, NotificationType.NO_INTERNET);
2873 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002874
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002875 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2876 NetworkCapabilities nc = nai.networkCapabilities;
2877 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002878
Erik Kline065ab6e2016-10-02 18:02:14 +09002879 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002880 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002881 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2882 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002883 }
2884
Lorenzo Colitti46aa9c02017-01-24 18:08:41 +09002885 @Override
2886 public int getMultipathPreference(Network network) {
2887 enforceAccessPermission();
2888
2889 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2890 if (nai != null && !nai.networkInfo.isMetered()) {
2891 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2892 }
2893
2894 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2895 }
2896
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002897 private class InternalHandler extends Handler {
2898 public InternalHandler(Looper looper) {
2899 super(looper);
2900 }
2901
2902 @Override
2903 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002904 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002905 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002906 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002907 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002908 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002909 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002910 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002911 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002912 break;
2913 }
Jason Monkdecd2952013-10-10 14:02:51 -04002914 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002915 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002916 break;
2917 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002918 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002919 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2920 break;
2921 }
2922 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2923 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002924 break;
2925 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002926 case EVENT_REGISTER_NETWORK_AGENT: {
2927 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2928 break;
2929 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002930 case EVENT_REGISTER_NETWORK_REQUEST:
2931 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002932 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002933 break;
2934 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002935 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2936 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002937 handleRegisterNetworkRequestWithIntent(msg);
2938 break;
2939 }
Erik Kline3841a482015-11-25 12:49:38 +09002940 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2941 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2942 handleTimedOutNetworkRequest(nri);
2943 break;
2944 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002945 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2946 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2947 break;
2948 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002949 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002950 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002951 break;
2952 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002953 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002954 Network network = (Network) msg.obj;
2955 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002956 break;
2957 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002958 case EVENT_SET_AVOID_UNVALIDATED: {
2959 handleSetAvoidUnvalidated((Network) msg.obj);
2960 break;
2961 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002962 case EVENT_PROMPT_UNVALIDATED: {
2963 handlePromptUnvalidated((Network) msg.obj);
2964 break;
2965 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002966 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2967 handleMobileDataAlwaysOn();
2968 break;
2969 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002970 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2971 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2972 mKeepaliveTracker.handleStartKeepalive(msg);
2973 break;
2974 }
2975 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2976 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2977 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2978 int slot = msg.arg1;
2979 int reason = msg.arg2;
2980 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2981 break;
2982 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002983 case EVENT_SYSTEM_READY: {
2984 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2985 nai.networkMonitor.systemReady = true;
2986 }
2987 break;
2988 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002989 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002990 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002991 break;
2992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 }
2994 }
2995 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002996
2997 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002998 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002999 public int tether(String iface, String callerPkg) {
3000 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003001 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003002 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003003 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003004 } else {
3005 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3006 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003007 }
3008
3009 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003010 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003011 public int untether(String iface, String callerPkg) {
3012 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003013
3014 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003015 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003016 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003017 } else {
3018 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3019 }
3020 }
3021
3022 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003023 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003024 public int getLastTetherError(String iface) {
3025 enforceTetherAccessPermission();
3026
3027 if (isTetheringSupported()) {
3028 return mTethering.getLastTetherError(iface);
3029 } else {
3030 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3031 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003032 }
3033
3034 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003035 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003036 public String[] getTetherableUsbRegexs() {
3037 enforceTetherAccessPermission();
3038 if (isTetheringSupported()) {
3039 return mTethering.getTetherableUsbRegexs();
3040 } else {
3041 return new String[0];
3042 }
3043 }
3044
Lorenzo Colitti18660282016-07-04 12:55:44 +09003045 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003046 public String[] getTetherableWifiRegexs() {
3047 enforceTetherAccessPermission();
3048 if (isTetheringSupported()) {
3049 return mTethering.getTetherableWifiRegexs();
3050 } else {
3051 return new String[0];
3052 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003053 }
3054
Lorenzo Colitti18660282016-07-04 12:55:44 +09003055 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003056 public String[] getTetherableBluetoothRegexs() {
3057 enforceTetherAccessPermission();
3058 if (isTetheringSupported()) {
3059 return mTethering.getTetherableBluetoothRegexs();
3060 } else {
3061 return new String[0];
3062 }
3063 }
3064
Lorenzo Colitti18660282016-07-04 12:55:44 +09003065 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003066 public int setUsbTethering(boolean enable, String callerPkg) {
3067 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003068 if (isTetheringSupported()) {
3069 return mTethering.setUsbTethering(enable);
3070 } else {
3071 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3072 }
3073 }
3074
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003075 // TODO - move iface listing, queries, etc to new module
3076 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003077 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003078 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003079 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003080 return mTethering.getTetherableIfaces();
3081 }
3082
Lorenzo Colitti18660282016-07-04 12:55:44 +09003083 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003084 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003085 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003086 return mTethering.getTetheredIfaces();
3087 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003088
Lorenzo Colitti18660282016-07-04 12:55:44 +09003089 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003090 public String[] getTetheringErroredIfaces() {
3091 enforceTetherAccessPermission();
3092 return mTethering.getErroredIfaces();
3093 }
3094
Lorenzo Colitti18660282016-07-04 12:55:44 +09003095 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003096 public String[] getTetheredDhcpRanges() {
3097 enforceConnectivityInternalPermission();
3098 return mTethering.getTetheredDhcpRanges();
3099 }
3100
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003101 // if ro.tether.denied = true we default to no tethering
3102 // gservices could set the secure setting to 1 though to enable it on a build where it
3103 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003104 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003105 public boolean isTetheringSupported() {
3106 enforceTetherAccessPermission();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003107 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3108 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3109 Settings.Global.TETHER_SUPPORTED, defaultVal));
3110 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003111 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003112
3113 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3114 boolean adminUser = false;
3115 final long token = Binder.clearCallingIdentity();
3116 try {
3117 adminUser = mUserManager.isAdminUser();
3118 } finally {
3119 Binder.restoreCallingIdentity(token);
3120 }
3121
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003122 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003123 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003124
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003125 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003126 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3127 String callerPkg) {
3128 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003129 if (!isTetheringSupported()) {
3130 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3131 return;
3132 }
3133 mTethering.startTethering(type, receiver, showProvisioningUi);
3134 }
3135
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003136 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003137 public void stopTethering(int type, String callerPkg) {
3138 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003139 mTethering.stopTethering(type);
3140 }
3141
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003142 // Called when we lose the default network and have no replacement yet.
3143 // This will automatically be cleared after X seconds or a new default network
3144 // becomes CONNECTED, whichever happens first. The timer is started by the
3145 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003146 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003147 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003148 if (mNetTransitionWakeLock.isHeld()) {
3149 return;
3150 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003151 mNetTransitionWakeLock.acquire();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003152 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003153 mWakelockLogs.log("ACQUIRE for " + forWhom);
3154 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3155 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003156 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003157
Hugo Benichi4c31b342017-03-30 23:18:10 +09003158 // Called when we gain a new default network to release the network transition wakelock in a
3159 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3160 // message is cancelled.
3161 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003162 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003163 if (!mNetTransitionWakeLock.isHeld()) {
3164 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003165 }
3166 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003167 // Cancel self timeout on wakelock hold.
3168 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3169 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3170 mHandler.sendMessageDelayed(msg, 1000);
3171 }
3172
3173 // Called when either message of ensureNetworkTransitionWakelock or
3174 // scheduleReleaseNetworkTransitionWakelock is processed.
3175 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3176 String event = eventName(eventId);
3177 synchronized (this) {
3178 if (!mNetTransitionWakeLock.isHeld()) {
3179 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3180 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3181 return;
3182 }
3183 mNetTransitionWakeLock.release();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003184 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003185 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003186 }
3187
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003188 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003189 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003190 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003191 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003192 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003193 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003194 }
3195
Lorenzo Colitti18660282016-07-04 12:55:44 +09003196 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003197 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003198 enforceAccessPermission();
3199 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003200 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003201 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003202 mHandler.sendMessage(
3203 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3204 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003205
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003206 private void handleReportNetworkConnectivity(
3207 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi29551722017-04-06 16:01:44 +09003208 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003209 if (network == null) {
3210 nai = getDefaultNetwork();
3211 } else {
3212 nai = getNetworkAgentInfoForNetwork(network);
3213 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003214 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3215 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3216 return;
3217 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003218 // Revalidate if the app report does not match our current validated state.
Hugo Benichi29551722017-04-06 16:01:44 +09003219 if (hasConnectivity == nai.lastValidated) {
3220 return;
3221 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003222 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003223 int netid = nai.network.netId;
3224 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003225 }
Hugo Benichi29551722017-04-06 16:01:44 +09003226 // Validating a network that has not yet connected could result in a call to
3227 // rematchNetworkAndRequests() which is not meant to work on such networks.
3228 if (!nai.everConnected) {
3229 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003230 }
Hugo Benichi29551722017-04-06 16:01:44 +09003231 LinkProperties lp = getLinkProperties(nai);
3232 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3233 return;
3234 }
3235 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003236 }
3237
Paul Jensencee9b512015-05-06 07:32:40 -04003238 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003239 // this information is already available as a world read/writable jvm property
3240 // so this API change wouldn't have a benifit. It also breaks the passing
3241 // of proxy info to all the JVMs.
3242 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003243 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003244 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003245 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3246 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003247 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003248 }
3249
Lorenzo Colitti18660282016-07-04 12:55:44 +09003250 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003251 public ProxyInfo getProxyForNetwork(Network network) {
3252 if (network == null) return getDefaultProxy();
3253 final ProxyInfo globalProxy = getGlobalProxy();
3254 if (globalProxy != null) return globalProxy;
3255 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3256 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3257 // caller may not have.
3258 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3259 if (nai == null) return null;
3260 synchronized (nai) {
3261 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3262 if (proxyInfo == null) return null;
3263 return new ProxyInfo(proxyInfo);
3264 }
3265 }
3266
Paul Jensene0bef712014-12-10 15:12:18 -05003267 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3268 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3269 // proxy is null then there is no proxy in place).
3270 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3271 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3272 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3273 proxy = null;
3274 }
3275 return proxy;
3276 }
3277
3278 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3279 // better for determining if a new proxy broadcast is necessary:
3280 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3281 // avoid unnecessary broadcasts.
3282 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3283 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3284 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3285 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3286 // all set.
3287 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3288 a = canonicalizeProxyInfo(a);
3289 b = canonicalizeProxyInfo(b);
3290 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3291 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3292 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3293 }
3294
Jason Monk207900c2014-04-25 15:00:09 -04003295 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003296 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003297
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003298 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003299 if (proxyProperties == mGlobalProxy) return;
3300 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3301 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3302
3303 String host = "";
3304 int port = 0;
3305 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003306 String pacFileUrl = "";
3307 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003308 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003309 if (!proxyProperties.isValid()) {
3310 if (DBG)
3311 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3312 return;
3313 }
Jason Monk207900c2014-04-25 15:00:09 -04003314 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003315 host = mGlobalProxy.getHost();
3316 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003317 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003318 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003319 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003320 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003321 } else {
3322 mGlobalProxy = null;
3323 }
3324 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003325 final long token = Binder.clearCallingIdentity();
3326 try {
3327 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3328 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3329 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3330 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003331 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003332 } finally {
3333 Binder.restoreCallingIdentity(token);
3334 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003335
Jason Monkcf0f97a2014-10-02 15:39:38 -04003336 if (mGlobalProxy == null) {
3337 proxyProperties = mDefaultProxy;
3338 }
3339 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003340 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003341 }
3342
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003343 private void loadGlobalProxy() {
3344 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003345 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3346 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3347 String exclList = Settings.Global.getString(res,
3348 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003349 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3350 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003351 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003352 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003353 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003354 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003355 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003356 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003357 if (!proxyProperties.isValid()) {
3358 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3359 return;
3360 }
3361
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003362 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003363 mGlobalProxy = proxyProperties;
3364 }
3365 }
3366 }
3367
Jason Monk207900c2014-04-25 15:00:09 -04003368 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003369 // this information is already available as a world read/writable jvm property
3370 // so this API change wouldn't have a benifit. It also breaks the passing
3371 // of proxy info to all the JVMs.
3372 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003373 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003374 return mGlobalProxy;
3375 }
3376 }
3377
Jason Monk207900c2014-04-25 15:00:09 -04003378 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003379 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003380 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003381 proxy = null;
3382 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003383 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003384 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003385 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003386 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003387 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3388 return;
3389 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003390
3391 // This call could be coming from the PacManager, containing the port of the local
3392 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3393 // global (to get the correct local port), and send a broadcast.
3394 // TODO: Switch PacManager to have its own message to send back rather than
3395 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003396 if ((mGlobalProxy != null) && (proxy != null)
3397 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003398 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3399 mGlobalProxy = proxy;
3400 sendProxyBroadcast(mGlobalProxy);
3401 return;
3402 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003403 mDefaultProxy = proxy;
3404
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003405 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003406 if (!mDefaultProxyDisabled) {
3407 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003408 }
3409 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003410 }
3411
Paul Jensene0bef712014-12-10 15:12:18 -05003412 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3413 // This method gets called when any network changes proxy, but the broadcast only ever contains
3414 // the default proxy (even if it hasn't changed).
3415 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3416 // world where an app might be bound to a non-default network.
3417 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3418 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3419 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3420
3421 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3422 sendProxyBroadcast(getDefaultProxy());
3423 }
3424 }
3425
Robert Greenwalt434203a2010-10-11 16:00:27 -07003426 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003427 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3428 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003429 if (!TextUtils.isEmpty(proxy)) {
3430 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003431 if (data.length == 0) {
3432 return;
3433 }
3434
Robert Greenwalt434203a2010-10-11 16:00:27 -07003435 String proxyHost = data[0];
3436 int proxyPort = 8080;
3437 if (data.length > 1) {
3438 try {
3439 proxyPort = Integer.parseInt(data[1]);
3440 } catch (NumberFormatException e) {
3441 return;
3442 }
3443 }
Jason Monk207900c2014-04-25 15:00:09 -04003444 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003445 setGlobalProxy(p);
3446 }
3447 }
3448
Jason Monk207900c2014-04-25 15:00:09 -04003449 private void sendProxyBroadcast(ProxyInfo proxy) {
3450 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003451 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003452 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003453 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003454 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3455 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003456 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003457 final long ident = Binder.clearCallingIdentity();
3458 try {
3459 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3460 } finally {
3461 Binder.restoreCallingIdentity(ident);
3462 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003463 }
3464
3465 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003466 final private HashMap<Uri, Integer> mUriEventMap;
3467 final private Context mContext;
3468 final private Handler mHandler;
3469
3470 SettingsObserver(Context context, Handler handler) {
3471 super(null);
3472 mUriEventMap = new HashMap<Uri, Integer>();
3473 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003474 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003475 }
3476
Erik Klineda4bfa82015-04-30 12:58:40 +09003477 void observe(Uri uri, int what) {
3478 mUriEventMap.put(uri, what);
3479 final ContentResolver resolver = mContext.getContentResolver();
3480 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003481 }
3482
3483 @Override
3484 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003485 Slog.wtf(TAG, "Should never be reached.");
3486 }
3487
3488 @Override
3489 public void onChange(boolean selfChange, Uri uri) {
3490 final Integer what = mUriEventMap.get(uri);
3491 if (what != null) {
3492 mHandler.obtainMessage(what.intValue()).sendToTarget();
3493 } else {
3494 loge("No matching event to send for URI=" + uri);
3495 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003496 }
3497 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003498
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003499 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003500 Slog.d(TAG, s);
3501 }
3502
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003503 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003504 Slog.e(TAG, s);
3505 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003506
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003507 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003508 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003509 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3510 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3511 *
3512 * @param oldPackage Package name of the application which currently controls VPN, which will
3513 * be replaced. If there is no such application, this should should either be
3514 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3515 * @param newPackage Package name of the application which should gain control of VPN, or
3516 * {@code null} to disable.
3517 * @param userId User for whom to prepare the new VPN.
3518 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003519 * @hide
3520 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003521 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003522 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3523 int userId) {
3524 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003525 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003526
Hugo Benichi20035e02017-04-26 14:53:28 +09003527 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003528 Vpn vpn = mVpns.get(userId);
3529 if (vpn != null) {
3530 return vpn.prepare(oldPackage, newPackage);
3531 } else {
3532 return false;
3533 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003534 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003535 }
3536
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003537 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003538 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3539 * This method is used by system-privileged apps.
3540 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3541 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3542 *
3543 * @param packageName The package for which authorization state should change.
3544 * @param userId User for whom {@code packageName} is installed.
3545 * @param authorized {@code true} if this app should be able to start a VPN connection without
3546 * explicit user approval, {@code false} if not.
3547 *
Jeff Davidson05542602014-08-11 14:07:27 -07003548 * @hide
3549 */
3550 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003551 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3552 enforceCrossUserPermission(userId);
3553
Hugo Benichi20035e02017-04-26 14:53:28 +09003554 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003555 Vpn vpn = mVpns.get(userId);
3556 if (vpn != null) {
3557 vpn.setPackageAuthorization(packageName, authorized);
3558 }
Jeff Davidson05542602014-08-11 14:07:27 -07003559 }
3560 }
3561
3562 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003563 * Configure a TUN interface and return its file descriptor. Parameters
3564 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003565 * and not available in ConnectivityManager. Permissions are checked in
3566 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003567 * @hide
3568 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003569 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003570 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003571 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003572 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003573 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003574 return mVpns.get(user).establish(config);
3575 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003576 }
3577
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003578 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003579 * Start legacy VPN, controlling native daemons as needed. Creates a
3580 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003581 */
3582 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003583 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003584 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003585 final LinkProperties egress = getActiveLinkProperties();
3586 if (egress == null) {
3587 throw new IllegalStateException("Missing active network connection");
3588 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003589 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003590 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003591 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3592 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003593 }
3594
3595 /**
3596 * Return the information of the ongoing legacy VPN. This method is used
3597 * by VpnSettings and not available in ConnectivityManager. Permissions
3598 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003599 */
3600 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003601 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3602 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003603
Hugo Benichi20035e02017-04-26 14:53:28 +09003604 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003605 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003606 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003607 }
3608
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003609 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003610 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3611 * and not available in ConnectivityManager.
3612 */
3613 @Override
3614 public VpnInfo[] getAllVpnInfo() {
3615 enforceConnectivityInternalPermission();
3616 if (mLockdownEnabled) {
3617 return new VpnInfo[0];
3618 }
3619
Hugo Benichi20035e02017-04-26 14:53:28 +09003620 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003621 List<VpnInfo> infoList = new ArrayList<>();
3622 for (int i = 0; i < mVpns.size(); i++) {
3623 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3624 if (info != null) {
3625 infoList.add(info);
3626 }
3627 }
3628 return infoList.toArray(new VpnInfo[infoList.size()]);
3629 }
3630 }
3631
3632 /**
3633 * @return VPN information for accounting, or null if we can't retrieve all required
3634 * information, e.g primary underlying iface.
3635 */
3636 @Nullable
3637 private VpnInfo createVpnInfo(Vpn vpn) {
3638 VpnInfo info = vpn.getVpnInfo();
3639 if (info == null) {
3640 return null;
3641 }
3642 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3643 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3644 // the underlyingNetworks list.
3645 if (underlyingNetworks == null) {
3646 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3647 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3648 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3649 }
3650 } else if (underlyingNetworks.length > 0) {
3651 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3652 if (linkProperties != null) {
3653 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3654 }
3655 }
3656 return info.primaryUnderlyingIface == null ? null : info;
3657 }
3658
3659 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003660 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3661 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003662 * Permissions are checked in Vpn class.
3663 * @hide
3664 */
3665 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003666 public VpnConfig getVpnConfig(int userId) {
3667 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003668 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003669 Vpn vpn = mVpns.get(userId);
3670 if (vpn != null) {
3671 return vpn.getVpnConfig();
3672 } else {
3673 return null;
3674 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003675 }
3676 }
3677
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003678 @Override
3679 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003680 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3681 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3682 return false;
3683 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003684
3685 // Tear down existing lockdown if profile was removed
3686 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3687 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003688 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3689 if (profileTag == null) {
3690 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3691 return false;
3692 }
3693 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003694 final VpnProfile profile = VpnProfile.decode(
3695 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003696 if (profile == null) {
3697 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3698 setLockdownTracker(null);
3699 return true;
3700 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003701 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003702 synchronized (mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003703 Vpn vpn = mVpns.get(user);
3704 if (vpn == null) {
3705 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3706 return false;
3707 }
3708 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003709 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003710 } else {
3711 setLockdownTracker(null);
3712 }
3713
3714 return true;
3715 }
3716
3717 /**
3718 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3719 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3720 */
3721 private void setLockdownTracker(LockdownVpnTracker tracker) {
3722 // Shutdown any existing tracker
3723 final LockdownVpnTracker existing = mLockdownTracker;
3724 mLockdownTracker = null;
3725 if (existing != null) {
3726 existing.shutdown();
3727 }
3728
Robin Leec3736bc2017-03-10 16:19:54 +00003729 if (tracker != null) {
3730 mLockdownTracker = tracker;
3731 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003732 }
3733 }
3734
3735 private void throwIfLockdownEnabled() {
3736 if (mLockdownEnabled) {
3737 throw new IllegalStateException("Unavailable in lockdown mode");
3738 }
3739 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003740
Robin Lee244ce8e2016-01-05 18:03:46 +00003741 /**
Robin Lee17e61832016-05-09 13:46:28 +01003742 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3743 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003744 *
Robin Lee17e61832016-05-09 13:46:28 +01003745 * @return {@code true} if the service was started, the service was already connected, or there
3746 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003747 */
Robin Lee17e61832016-05-09 13:46:28 +01003748 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003749 synchronized (mVpns) {
3750 Vpn vpn = mVpns.get(userId);
3751 if (vpn == null) {
3752 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3753 // exists already.
3754 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3755 return false;
3756 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003757
Robin Lee812800c2016-05-13 15:38:08 +01003758 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003759 }
3760 }
3761
3762 @Override
Robin Leedc679712016-05-03 13:23:03 +01003763 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003764 enforceConnectivityInternalPermission();
3765 enforceCrossUserPermission(userId);
3766
3767 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3768 if (LockdownVpnTracker.isEnabled()) {
3769 return false;
3770 }
3771
Robin Lee244ce8e2016-01-05 18:03:46 +00003772 synchronized (mVpns) {
3773 Vpn vpn = mVpns.get(userId);
3774 if (vpn == null) {
3775 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3776 return false;
3777 }
Robin Lee17e61832016-05-09 13:46:28 +01003778 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003779 return false;
3780 }
Robin Lee17e61832016-05-09 13:46:28 +01003781 if (!startAlwaysOnVpn(userId)) {
3782 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003783 return false;
3784 }
3785 }
3786 return true;
3787 }
3788
3789 @Override
3790 public String getAlwaysOnVpnPackage(int userId) {
3791 enforceConnectivityInternalPermission();
3792 enforceCrossUserPermission(userId);
3793
3794 synchronized (mVpns) {
3795 Vpn vpn = mVpns.get(userId);
3796 if (vpn == null) {
3797 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3798 return null;
3799 }
3800 return vpn.getAlwaysOnPackage();
3801 }
3802 }
3803
Wink Savilleab9321d2013-06-29 21:10:57 -07003804 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003805 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003806 // TODO: Remove? Any reason to trigger a provisioning check?
3807 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003808 }
3809
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003810 /** Location to an updatable file listing carrier provisioning urls.
3811 * An example:
3812 *
3813 * <?xml version="1.0" encoding="utf-8"?>
3814 * <provisioningUrls>
3815 * <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 -07003816 * </provisioningUrls>
3817 */
3818 private static final String PROVISIONING_URL_PATH =
3819 "/data/misc/radio/provisioning_urls.xml";
3820 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003821
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003822 /** XML tag for root element. */
3823 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3824 /** XML tag for individual url */
3825 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003826 /** XML attribute for mcc */
3827 private static final String ATTR_MCC = "mcc";
3828 /** XML attribute for mnc */
3829 private static final String ATTR_MNC = "mnc";
3830
Paul Jensen434dde82015-06-11 09:43:30 -04003831 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003832 FileReader fileReader = null;
3833 XmlPullParser parser = null;
3834 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003835
3836 try {
3837 fileReader = new FileReader(mProvisioningUrlFile);
3838 parser = Xml.newPullParser();
3839 parser.setInput(fileReader);
3840 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3841
3842 while (true) {
3843 XmlUtils.nextElement(parser);
3844
3845 String element = parser.getName();
3846 if (element == null) break;
3847
Paul Jensen434dde82015-06-11 09:43:30 -04003848 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003849 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3850 try {
3851 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3852 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3853 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3854 parser.next();
3855 if (parser.getEventType() == XmlPullParser.TEXT) {
3856 return parser.getText();
3857 }
3858 }
3859 }
3860 } catch (NumberFormatException e) {
3861 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3862 }
3863 }
3864 }
3865 return null;
3866 } catch (FileNotFoundException e) {
3867 loge("Carrier Provisioning Urls file not found");
3868 } catch (XmlPullParserException e) {
3869 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3870 } catch (IOException e) {
3871 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3872 } finally {
3873 if (fileReader != null) {
3874 try {
3875 fileReader.close();
3876 } catch (IOException e) {}
3877 }
3878 }
3879 return null;
3880 }
3881
Wink Saville42d4f082013-07-20 20:31:59 -07003882 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003883 public String getMobileProvisioningUrl() {
3884 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003885 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003886 if (TextUtils.isEmpty(url)) {
3887 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003888 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003889 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003890 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003891 }
Wink Saville8cf35602013-07-10 23:00:07 -07003892 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003893 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003894 String phoneNumber = mTelephonyManager.getLine1Number();
3895 if (TextUtils.isEmpty(phoneNumber)) {
3896 phoneNumber = "0000000000";
3897 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003898 url = String.format(url,
3899 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3900 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003901 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003902 }
3903
Wink Savilleab9321d2013-06-29 21:10:57 -07003904 return url;
3905 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003906
Wink Saville948282b2013-08-29 08:55:16 -07003907 @Override
3908 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003909 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003910 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003911 final long ident = Binder.clearCallingIdentity();
3912 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003913 // Concatenate the range of types onto the range of NetIDs.
3914 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3915 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003916 } finally {
3917 Binder.restoreCallingIdentity(ident);
3918 }
Wink Saville948282b2013-08-29 08:55:16 -07003919 }
Wink Saville7788c612013-08-29 14:57:08 -07003920
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003921 @Override
3922 public void setAirplaneMode(boolean enable) {
3923 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003924 final long ident = Binder.clearCallingIdentity();
3925 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003926 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003927 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003928 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3929 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003930 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003931 } finally {
3932 Binder.restoreCallingIdentity(ident);
3933 }
3934 }
3935
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003936 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003937 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003938 Vpn userVpn = mVpns.get(userId);
3939 if (userVpn != null) {
3940 loge("Starting user already has a VPN");
3941 return;
3942 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003943 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003944 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003945 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003946 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3947 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003948 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003949 }
3950
3951 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003952 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003953 Vpn userVpn = mVpns.get(userId);
3954 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003955 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003956 return;
3957 }
Robin Lee17e61832016-05-09 13:46:28 +01003958 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003959 mVpns.delete(userId);
3960 }
3961 }
3962
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003963 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003964 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003965 final int vpnsSize = mVpns.size();
3966 for (int i = 0; i < vpnsSize; i++) {
3967 Vpn vpn = mVpns.valueAt(i);
3968 vpn.onUserAdded(userId);
3969 }
3970 }
3971 }
3972
3973 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003974 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003975 final int vpnsSize = mVpns.size();
3976 for (int i = 0; i < vpnsSize; i++) {
3977 Vpn vpn = mVpns.valueAt(i);
3978 vpn.onUserRemoved(userId);
3979 }
3980 }
3981 }
3982
Robin Lee89e7a692016-02-29 14:38:17 +00003983 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003984 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3985 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3986 updateLockdownVpn();
3987 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003988 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003989 }
3990 }
3991
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003992 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3993 @Override
3994 public void onReceive(Context context, Intent intent) {
3995 final String action = intent.getAction();
3996 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3997 if (userId == UserHandle.USER_NULL) return;
3998
Robin Lee323f29d2016-05-04 16:38:06 +01003999 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004000 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004001 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004002 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004003 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4004 onUserAdded(userId);
4005 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4006 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004007 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4008 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004009 }
4010 }
4011 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004012
Robin Lee95204e02017-01-27 11:59:22 +00004013 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4014 @Override
4015 public void onReceive(Context context, Intent intent) {
4016 // Try creating lockdown tracker, since user present usually means
4017 // unlocked keystore.
4018 updateLockdownVpn();
4019 mContext.unregisterReceiver(this);
4020 }
4021 };
4022
Robert Greenwalta67be032014-05-16 15:49:14 -07004023 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4024 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004025 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4026 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004027
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004028 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4029 // Map from UID to number of NetworkRequests that UID has filed.
4030 @GuardedBy("mUidToNetworkRequestCount")
4031 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4032
Robert Greenwalta67be032014-05-16 15:49:14 -07004033 private static class NetworkFactoryInfo {
4034 public final String name;
4035 public final Messenger messenger;
4036 public final AsyncChannel asyncChannel;
4037
4038 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4039 this.name = name;
4040 this.messenger = messenger;
4041 this.asyncChannel = asyncChannel;
4042 }
4043 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004044
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004045 private void ensureNetworkRequestHasType(NetworkRequest request) {
4046 if (request.type == NetworkRequest.Type.NONE) {
4047 throw new IllegalArgumentException(
4048 "All NetworkRequests in ConnectivityService must have a type");
4049 }
4050 }
4051
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004052 /**
4053 * Tracks info about the requester.
4054 * Also used to notice when the calling process dies so we can self-expire
4055 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004056 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004057 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004058 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004059 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004060 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004061 final int mPid;
4062 final int mUid;
4063 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004064
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004065 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004066 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004067 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004068 mPendingIntent = pi;
4069 messenger = null;
4070 mBinder = null;
4071 mPid = getCallingPid();
4072 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004073 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004074 }
4075
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004076 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004077 super();
4078 messenger = m;
4079 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004080 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004081 mBinder = binder;
4082 mPid = getCallingPid();
4083 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004084 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004085 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004086
4087 try {
4088 mBinder.linkToDeath(this, 0);
4089 } catch (RemoteException e) {
4090 binderDied();
4091 }
4092 }
4093
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004094 private void enforceRequestCountLimit() {
4095 synchronized (mUidToNetworkRequestCount) {
4096 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4097 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004098 throw new ServiceSpecificException(
4099 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004100 }
4101 mUidToNetworkRequestCount.put(mUid, networkRequests);
4102 }
4103 }
4104
Robert Greenwalt9258c642014-03-26 16:47:06 -07004105 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004106 if (mBinder != null) {
4107 mBinder.unlinkToDeath(this, 0);
4108 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004109 }
4110
4111 public void binderDied() {
4112 log("ConnectivityService NetworkRequestInfo binderDied(" +
4113 request + ", " + mBinder + ")");
4114 releaseNetworkRequest(request);
4115 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004116
4117 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004118 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004119 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004120 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004121 }
4122
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004123 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4124 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4125 if (badCapability != null) {
4126 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004127 }
4128 }
4129
Erik Kline9d598e12015-07-13 16:37:51 +09004130 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004131 final SortedSet<Integer> thresholds = new TreeSet();
4132 synchronized (nai) {
4133 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4134 if (nri.request.networkCapabilities.hasSignalStrength() &&
4135 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4136 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4137 }
4138 }
4139 }
Erik Kline9d598e12015-07-13 16:37:51 +09004140 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004141 }
4142
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004143 private void updateSignalStrengthThresholds(
4144 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4145 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004146 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004147 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4148
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004149 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004150 String detail;
4151 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4152 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4153 } else {
4154 detail = reason;
4155 }
4156 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4157 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4158 }
4159
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004160 nai.asyncChannel.sendMessage(
4161 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004162 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004163 }
4164
Etan Cohen859748f2017-04-03 17:42:34 -07004165 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4166 if (nc == null) {
4167 return;
4168 }
4169 NetworkSpecifier ns = nc.getNetworkSpecifier();
4170 if (ns == null) {
4171 return;
4172 }
4173 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4174 ns.assertValidFromUid(Binder.getCallingUid());
4175 }
4176
Robert Greenwalt9258c642014-03-26 16:47:06 -07004177 @Override
4178 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004179 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004180 final NetworkRequest.Type type = (networkCapabilities == null)
4181 ? NetworkRequest.Type.TRACK_DEFAULT
4182 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004183 // If the requested networkCapabilities is null, take them instead from
4184 // the default network request. This allows callers to keep track of
4185 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004186 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004187 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4188 enforceAccessPermission();
4189 } else {
4190 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4191 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004192 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4193 // of the app when the request is filed, but we never change the request if the app
4194 // changes network state. http://b/29964605
4195 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004196 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004197 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004198
Etan Cohenba07c8c2017-02-05 10:42:27 -08004199 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004200 throw new IllegalArgumentException("Bad timeout specified");
4201 }
Etan Cohen859748f2017-04-03 17:42:34 -07004202 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004203
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004204 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004205 nextNetworkRequestId(), type);
4206 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004207 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004208
4209 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004210 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004211 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004212 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004213 }
4214 return networkRequest;
4215 }
4216
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004217 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004218 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004219 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004220 } else {
4221 enforceChangePermission();
4222 }
4223 }
4224
fenglub15e72b2015-03-20 11:29:56 -07004225 @Override
fengludb571472015-04-21 17:12:05 -07004226 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004227 enforceAccessPermission();
4228 NetworkAgentInfo nai = null;
4229 if (network == null) {
4230 return false;
4231 }
4232 synchronized (mNetworkForNetId) {
4233 nai = mNetworkForNetId.get(network.netId);
4234 }
4235 if (nai != null) {
4236 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4237 return true;
4238 }
4239 return false;
4240 }
4241
Felipe Lemeee27cab2016-06-20 16:36:29 -07004242 private boolean isSystem(int uid) {
4243 return uid < Process.FIRST_APPLICATION_UID;
4244 }
fenglub15e72b2015-03-20 11:29:56 -07004245
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004246 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004247 final int uid = Binder.getCallingUid();
4248 if (isSystem(uid)) {
4249 return;
4250 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004251 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004252 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004253 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004254 synchronized(mRulesLock) {
4255 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4256 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004257 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4258 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004259 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004260 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004261 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004262 }
4263 }
4264 }
4265
Robert Greenwalt9258c642014-03-26 16:47:06 -07004266 @Override
4267 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4268 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004269 checkNotNull(operation, "PendingIntent cannot be null.");
4270 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4271 enforceNetworkRequestPermissions(networkCapabilities);
4272 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004273 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004274 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004275
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004276 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004277 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4278 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004279 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004280 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4281 nri));
4282 return networkRequest;
4283 }
4284
Jeremy Joslin79294842014-12-03 17:15:28 -08004285 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4286 mHandler.sendMessageDelayed(
4287 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4288 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4289 }
4290
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004291 @Override
4292 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004293 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004294 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4295 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004296 }
4297
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004298 // In order to implement the compatibility measure for pre-M apps that call
4299 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4300 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4301 // This ensures it has permission to do so.
4302 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4303 if (nc == null) {
4304 return false;
4305 }
4306 int[] transportTypes = nc.getTransportTypes();
4307 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4308 return false;
4309 }
4310 try {
4311 mContext.enforceCallingOrSelfPermission(
4312 android.Manifest.permission.ACCESS_WIFI_STATE,
4313 "ConnectivityService");
4314 } catch (SecurityException e) {
4315 return false;
4316 }
4317 return true;
4318 }
4319
Robert Greenwalt9258c642014-03-26 16:47:06 -07004320 @Override
4321 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4322 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004323 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4324 enforceAccessPermission();
4325 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004326
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004327 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4328 if (!ConnectivityManager.checkChangePermission(mContext)) {
4329 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4330 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4331 // onLost and onAvailable callbacks when networks move in and out of the background.
4332 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4333 // can't request networks.
4334 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4335 }
Etan Cohen859748f2017-04-03 17:42:34 -07004336 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004337
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004338 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004339 NetworkRequest.Type.LISTEN);
4340 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004341 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004342
4343 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4344 return networkRequest;
4345 }
4346
4347 @Override
4348 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4349 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004350 checkNotNull(operation, "PendingIntent cannot be null.");
4351 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4352 enforceAccessPermission();
4353 }
Etan Cohen859748f2017-04-03 17:42:34 -07004354 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004355
Erik Kline7523eb32015-07-09 18:24:03 +09004356 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004357 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4358 NetworkRequest.Type.LISTEN);
4359 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004360 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004361
4362 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004363 }
4364
Erik Klineacdd6392016-07-07 16:50:58 +09004365 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004366 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004367 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004368 mHandler.sendMessage(mHandler.obtainMessage(
4369 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004370 }
4371
4372 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004373 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004374 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004375 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4376 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004377 }
4378
Robert Greenwalta67be032014-05-16 15:49:14 -07004379 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004380 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004381 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4382 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4383 }
4384
4385 @Override
4386 public void unregisterNetworkFactory(Messenger messenger) {
4387 enforceConnectivityInternalPermission();
4388 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4389 }
4390
4391 private void handleUnregisterNetworkFactory(Messenger messenger) {
4392 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4393 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004394 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004395 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004396 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004397 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004398 }
4399
Robert Greenwalt7b816022014-04-18 15:25:25 -07004400 /**
4401 * NetworkAgentInfo supporting a request by requestId.
4402 * These have already been vetted (their Capabilities satisfy the request)
4403 * and the are the highest scored network available.
4404 * the are keyed off the Requests requestId.
4405 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004406 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004407 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4408 new SparseArray<NetworkAgentInfo>();
4409
Paul Jensen31a94f42015-02-13 14:18:39 -05004410 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4411 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004412 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4413 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004414 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4415 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4416 // there may not be a strict 1:1 correlation between the two.
4417 @GuardedBy("mNetworkForNetId")
4418 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004419
Robert Greenwalt7b816022014-04-18 15:25:25 -07004420 // NetworkAgentInfo keyed off its connecting messenger
4421 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004422 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004423 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4424 new HashMap<Messenger, NetworkAgentInfo>();
4425
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004426 @GuardedBy("mBlockedAppUids")
4427 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4428
Paul Jensen2c311d62014-11-17 12:34:51 -05004429 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004430 private final NetworkRequest mDefaultRequest;
4431
Erik Klineda4bfa82015-04-30 12:58:40 +09004432 // Request used to optionally keep mobile data active even when higher
4433 // priority networks like Wi-Fi are active.
4434 private final NetworkRequest mDefaultMobileDataRequest;
4435
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004436 private NetworkAgentInfo getDefaultNetwork() {
4437 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4438 }
4439
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004440 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004441 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004442 }
4443
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004444 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4445 return nri.request.requestId == mDefaultRequest.requestId;
4446 }
4447
Paul Jensen31a94f42015-02-13 14:18:39 -05004448 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004449 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004450 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004451 enforceConnectivityInternalPermission();
4452
Paul Jensen2c311d62014-11-17 12:34:51 -05004453 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4454 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004455 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004456 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4457 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004458 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004459 synchronized (this) {
4460 nai.networkMonitor.systemReady = mSystemReady;
4461 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004462 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4463 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004464 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004465 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004466 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004467 }
4468
4469 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4470 if (VDBG) log("Got NetworkAgent Messenger");
4471 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004472 synchronized (mNetworkForNetId) {
4473 mNetworkForNetId.put(na.network.netId, na);
4474 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004475 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4476 NetworkInfo networkInfo = na.networkInfo;
4477 na.networkInfo = null;
4478 updateNetworkInfo(na, networkInfo);
4479 }
4480
4481 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4482 LinkProperties newLp = networkAgent.linkProperties;
4483 int netId = networkAgent.network.netId;
4484
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004485 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4486 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004487 if (networkAgent.clatd != null) {
4488 networkAgent.clatd.fixupLinkProperties(oldLp);
4489 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004490
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004491 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004492 updateMtu(newLp, oldLp);
4493 // TODO - figure out what to do for clat
4494// for (LinkProperties lp : newLp.getStackedLinks()) {
4495// updateMtu(lp, null);
4496// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004497 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004498
Erik Kline94887872016-04-05 13:30:49 +09004499 updateRoutes(newLp, oldLp, netId);
4500 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004501
Paul Jensen3b759822014-05-13 11:44:01 -04004502 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004503 if (isDefaultNetwork(networkAgent)) {
4504 handleApplyDefaultProxy(newLp.getHttpProxy());
4505 } else {
4506 updateProxy(newLp, oldLp, networkAgent);
4507 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004508 // TODO - move this check to cover the whole function
4509 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004510 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004511 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4512 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004513
4514 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004515 }
4516
Lorenzo Colitti95439462014-10-09 13:44:48 +09004517 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4518 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4519 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004520
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004521 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004522 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4523 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004524 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004525 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004526 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004527 }
Paul Jensen992f2522014-04-28 10:33:11 -04004528
Joel Scherpelz668370b2017-06-08 15:35:21 +09004529 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004530 // Marks are only available on WiFi interaces. Checking for
4531 // marks on unsupported interfaces is harmless.
4532 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4533 return;
4534 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004535
Joel Scherpelz668370b2017-06-08 15:35:21 +09004536 int mark = mContext.getResources().getInteger(
4537 com.android.internal.R.integer.config_networkWakeupPacketMark);
4538 int mask = mContext.getResources().getInteger(
4539 com.android.internal.R.integer.config_networkWakeupPacketMask);
4540
4541 // Mask/mark of zero will not detect anything interesting.
4542 // Don't install rules unless both values are nonzero.
4543 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004544 return;
4545 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004546
4547 final String prefix = "iface:" + iface;
4548 try {
4549 if (add) {
4550 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4551 } else {
4552 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4553 }
4554 } catch (Exception e) {
4555 loge("Exception modifying wakeup packet monitoring: " + e);
4556 }
4557
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004558 }
4559
4560 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4561 NetworkCapabilities caps) {
Paul Jensen992f2522014-04-28 10:33:11 -04004562 CompareResult<String> interfaceDiff = new CompareResult<String>();
4563 if (oldLp != null) {
4564 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4565 } else if (newLp != null) {
4566 interfaceDiff.added = newLp.getAllInterfaceNames();
4567 }
4568 for (String iface : interfaceDiff.added) {
4569 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004570 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004571 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004572 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004573 } catch (Exception e) {
4574 loge("Exception adding interface: " + e);
4575 }
4576 }
4577 for (String iface : interfaceDiff.removed) {
4578 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004579 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004580 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004581 mNetd.removeInterfaceFromNetwork(iface, netId);
4582 } catch (Exception e) {
4583 loge("Exception removing interface: " + e);
4584 }
4585 }
4586 }
4587
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004588 /**
4589 * Have netd update routes from oldLp to newLp.
4590 * @return true if routes changed between oldLp and newLp
4591 */
4592 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004593 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4594 if (oldLp != null) {
4595 routeDiff = oldLp.compareAllRoutes(newLp);
4596 } else if (newLp != null) {
4597 routeDiff.added = newLp.getAllRoutes();
4598 }
4599
4600 // add routes before removing old in case it helps with continuous connectivity
4601
4602 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4603 for (RouteInfo route : routeDiff.added) {
4604 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004605 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004606 try {
4607 mNetd.addRoute(netId, route);
4608 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004609 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4610 loge("Exception in addRoute for non-gateway: " + e);
4611 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004612 }
4613 }
4614 for (RouteInfo route : routeDiff.added) {
4615 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004616 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004617 try {
4618 mNetd.addRoute(netId, route);
4619 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004620 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4621 loge("Exception in addRoute for gateway: " + e);
4622 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004623 }
4624 }
4625
4626 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004627 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004628 try {
4629 mNetd.removeRoute(netId, route);
4630 } catch (Exception e) {
4631 loge("Exception in removeRoute: " + e);
4632 }
4633 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004634 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004635 }
Erik Kline41368502015-06-17 13:19:54 +09004636
Erik Kline94887872016-04-05 13:30:49 +09004637 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4638 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4639 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004640 }
Erik Kline94887872016-04-05 13:30:49 +09004641
4642 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004643 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004644 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004645 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004646 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4647 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004648 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004649 }
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004650 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4651 if (defaultNai != null && defaultNai.network.netId == netId) {
4652 setDefaultDnsSystemProperties(dnses);
4653 }
Erik Kline94887872016-04-05 13:30:49 +09004654 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004655 }
4656
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004657 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4658 int last = 0;
4659 for (InetAddress dns : dnses) {
4660 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004661 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004662 }
4663 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004664 setNetDnsProperty(i, "");
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004665 }
4666 mNumDnsEntries = last;
4667 }
4668
Erik Kline4edba012017-04-07 15:29:29 +09004669 private void setNetDnsProperty(int which, String value) {
4670 final String key = "net.dns" + which;
4671 // Log and forget errors setting unsupported properties.
4672 try {
4673 mSystemProperties.set(key, value);
4674 } catch (Exception e) {
4675 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4676 }
4677 }
4678
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004679 private String getNetworkPermission(NetworkCapabilities nc) {
4680 // TODO: make these permission strings AIDL constants instead.
4681 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4682 return NetworkManagementService.PERMISSION_SYSTEM;
4683 }
4684 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4685 return NetworkManagementService.PERMISSION_NETWORK;
4686 }
4687 return null;
4688 }
4689
Paul Jensen3d194ea2015-06-16 14:27:36 -04004690 /**
4691 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4692 * augmented with any stateful capabilities implied from {@code networkAgent}
4693 * (e.g., validated status and captive portal status).
4694 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004695 * @param oldScore score of the network before any of the changes that prompted us
4696 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004697 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004698 * @param networkCapabilities the new network capabilities.
4699 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004700 private void updateCapabilities(
4701 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004702 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4703 networkCapabilities)) {
4704 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4705 + nai.networkCapabilities + " -> " + networkCapabilities);
4706 }
4707
Paul Jensen3d194ea2015-06-16 14:27:36 -04004708 // Don't modify caller's NetworkCapabilities.
4709 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004710 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004711 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4712 } else {
4713 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4714 }
Paul Jensene0988542015-06-25 15:30:08 -04004715 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004716 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4717 } else {
4718 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4719 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004720 if (nai.isBackgroundNetwork()) {
4721 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4722 } else {
4723 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4724 }
4725
4726 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4727
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004728 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4729 final String newPermission = getNetworkPermission(networkCapabilities);
4730 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004731 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004732 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004733 } catch (RemoteException e) {
4734 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004735 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004736 }
4737
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004738 final NetworkCapabilities prevNc = nai.networkCapabilities;
4739 synchronized (nai) {
4740 nai.networkCapabilities = networkCapabilities;
4741 }
4742 if (nai.getCurrentScore() == oldScore &&
4743 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4744 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4745 // the change we're processing can't affect any requests, it can only affect the listens
4746 // on this network. We might have been called by rematchNetworkAndRequests when a
4747 // network changed foreground state.
4748 processListenRequests(nai, true);
4749 } else {
4750 // If the requestable capabilities have changed or the score changed, we can't have been
4751 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004752 rematchAllNetworksAndRequests(nai, oldScore);
4753 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004754 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004755 }
4756
Paul Jensenc8b9a742014-09-30 15:37:41 -04004757 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004758 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4759 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004760 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004761 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004762 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4763 }
4764 }
4765
Robert Greenwalt7b816022014-04-18 15:25:25 -07004766 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4767 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004768 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004769 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4770 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004771 }
4772 }
4773
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004774 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4775 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004776 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004777 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004778 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4779 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004780 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004781 sendIntent(nri.mPendingIntent, intent);
4782 }
4783 // else not handled
4784 }
4785
4786 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4787 mPendingIntentWakeLock.acquire();
4788 try {
4789 if (DBG) log("Sending " + pendingIntent);
4790 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4791 } catch (PendingIntent.CanceledException e) {
4792 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4793 mPendingIntentWakeLock.release();
4794 releasePendingNetworkRequest(pendingIntent);
4795 }
4796 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4797 }
4798
4799 @Override
4800 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4801 String resultData, Bundle resultExtras) {
4802 if (DBG) log("Finished sending " + pendingIntent);
4803 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004804 // Release with a delay so the receiving client has an opportunity to put in its
4805 // own request.
4806 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004807 }
4808
Hugo Benichidba33db2017-03-23 22:40:44 +09004809 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004810 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004811 if (nri.messenger == null) {
4812 return; // Default request has no msgr
4813 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004814 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004815 // TODO: check if defensive copies of data is needed.
4816 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004817 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004818 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4819 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004820 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004821 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004822 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004823 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004824 break;
4825 }
4826 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004827 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004828 break;
4829 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004830 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004831 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004832 break;
4833 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004834 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004835 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004836 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004837 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004838 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004839 String notification = ConnectivityManager.getCallbackName(notificationType);
4840 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004841 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004842 nri.messenger.send(msg);
4843 } catch (RemoteException e) {
4844 // may occur naturally in the race of binder death.
4845 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4846 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004847 }
4848
Hugo Benichidba33db2017-03-23 22:40:44 +09004849 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4850 bundle.putParcelable(t.getClass().getSimpleName(), t);
4851 }
4852
Paul Jensenc8b9a742014-09-30 15:37:41 -04004853 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004854 if (nai.numRequestNetworkRequests() != 0) {
4855 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4856 NetworkRequest nr = nai.requestAt(i);
4857 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004858 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004859 loge("Dead network still had at least " + nr);
4860 break;
4861 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004862 }
4863 nai.asyncChannel.disconnect();
4864 }
4865
Robert Greenwalt7b816022014-04-18 15:25:25 -07004866 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4867 if (oldNetwork == null) {
4868 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4869 return;
4870 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004871 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004872
4873 // If we get here it means that the last linger timeout for this network expired. So there
4874 // must be no other active linger timers, and we must stop lingering.
4875 oldNetwork.clearLingerState();
4876
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004877 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004878 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004879 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004880 } else {
4881 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004882 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4883 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004884 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004885 }
4886
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004887 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004888 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004889 setupDataActivityTracking(newNetwork);
4890 try {
4891 mNetd.setDefaultNetId(newNetwork.network.netId);
4892 } catch (Exception e) {
4893 loge("Exception setting default network :" + e);
4894 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004895 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004896 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004897 updateTcpBufferSizes(newNetwork);
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004898 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004899 }
4900
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004901 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004902 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4903 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4904 NetworkRequest nr = nri.request;
4905 if (!nr.isListen()) continue;
4906 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4907 nai.removeRequest(nri.request.requestId);
4908 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4909 }
4910 }
4911
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004912 if (capabilitiesChanged) {
4913 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4914 }
4915
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004916 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4917 NetworkRequest nr = nri.request;
4918 if (!nr.isListen()) continue;
4919 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4920 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004921 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004922 }
4923 }
4924 }
4925
Paul Jensen2161a8e2014-09-11 11:00:39 -04004926 // Handles a network appearing or improving its score.
4927 //
4928 // - Evaluates all current NetworkRequests that can be
4929 // satisfied by newNetwork, and reassigns to newNetwork
4930 // any such requests for which newNetwork is the best.
4931 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004932 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004933 // needed. A network is needed if it is the best network for
4934 // one or more NetworkRequests, or if it is a VPN.
4935 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004936 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004937 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004938 //
4939 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4940 // networks that have no chance (i.e. even if validated)
4941 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004942 //
4943 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4944 // it does not remove NetworkRequests that other Networks could better satisfy.
4945 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4946 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4947 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004948 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004949 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004950 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4951 // performed to tear down unvalidated networks that have no chance (i.e. even if
4952 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004953 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004954 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004955 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004956 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004957 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004958 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004959
4960 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4961 final int score = newNetwork.getCurrentScore();
4962
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004963 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004964
Paul Jensen2161a8e2014-09-11 11:00:39 -04004965 // Find and migrate to this Network any NetworkRequests for
4966 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004967 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004968 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004969 NetworkCapabilities nc = newNetwork.networkCapabilities;
4970 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004971 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004972 // Process requests in the first pass and listens in the second pass. This allows us to
4973 // change a network's capabilities depending on which requests it has. This is only
4974 // correct if the change in capabilities doesn't affect whether the network satisfies
4975 // requests or not, and doesn't affect the network's score.
4976 if (nri.request.isListen()) continue;
4977
Paul Jensencf4c2c62015-07-01 14:16:32 -04004978 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4979 final boolean satisfies = newNetwork.satisfies(nri.request);
4980 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004981 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004982 log("Network " + newNetwork.name() + " was already satisfying" +
4983 " request " + nri.request.requestId + ". No change.");
4984 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004985 keep = true;
4986 continue;
4987 }
4988
4989 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004990 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004991 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004992 // next check if it's better than any current network we're using for
4993 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004994 if (VDBG) {
4995 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004996 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004997 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004998 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004999 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005000 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005001 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005002 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005003 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005004 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005005 affectedNetworks.add(currentNetwork);
5006 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005007 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005008 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005009 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005010 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005011 if (!newNetwork.addRequest(nri.request)) {
5012 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5013 }
5014 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005015 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005016 // Tell NetworkFactories about the new score, so they can stop
5017 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005018 // TODO - this could get expensive if we have alot of requests for this
5019 // network. Think about if there is a way to reduce this. Push
5020 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005021 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005022 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005023 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005024 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005025 if (currentNetwork != null) {
5026 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5027 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005028 }
5029 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005030 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005031 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5032 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005033 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005034 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5035 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5036 // This means this code doesn't have to handle the case where "currentNetwork" no
5037 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5038 if (DBG) {
5039 log("Network " + newNetwork.name() + " stopped satisfying" +
5040 " request " + nri.request.requestId);
5041 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005042 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005043 if (currentNetwork == newNetwork) {
5044 mNetworkForRequestId.remove(nri.request.requestId);
5045 sendUpdatedScoreToFactories(nri.request, 0);
5046 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005047 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5048 newNetwork.name() +
5049 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005050 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005051 // TODO: Technically, sending CALLBACK_LOST here is
5052 // incorrect if there is a replacement network currently
5053 // connected that can satisfy nri, which is a request
5054 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005055 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5056 // so this code is only incorrect for a network that loses
5057 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005058 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005059 }
5060 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005061 if (isNewDefault) {
5062 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005063 makeDefault(newNetwork);
5064 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
5065 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005066 // Have a new default network, release the transition wakelock in
5067 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005068 }
5069
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005070 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5071 Slog.wtf(TAG, String.format(
5072 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
5073 nc, newNetwork.networkCapabilities));
5074 }
5075 if (newNetwork.getCurrentScore() != score) {
5076 Slog.wtf(TAG, String.format(
5077 "BUG: %s changed score during rematch: %d -> %d",
5078 score, newNetwork.getCurrentScore()));
5079 }
5080
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005081 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005082 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5083 // If the network went from background to foreground or vice versa, we need to update
5084 // its foreground state. It is safe to do this after rematching the requests because
5085 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5086 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005087 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005088 } else {
5089 processListenRequests(newNetwork, false);
5090 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005091
Paul Jensencf4c2c62015-07-01 14:16:32 -04005092 // do this after the default net is switched, but
5093 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005094 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005095
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005096 // Linger any networks that are no longer needed. This should be done after sending the
5097 // available callback for newNetwork.
5098 for (NetworkAgentInfo nai : affectedNetworks) {
5099 updateLingerState(nai, now);
5100 }
5101 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5102 // does not need to be done in any particular order.
5103 updateLingerState(newNetwork, now);
5104
Paul Jensencf4c2c62015-07-01 14:16:32 -04005105 if (isNewDefault) {
5106 // Maintain the illusion: since the legacy API only
5107 // understands one network at a time, we must pretend
5108 // that the current default network disconnected before
5109 // the new one connected.
5110 if (oldDefaultNetwork != null) {
5111 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5112 oldDefaultNetwork, true);
5113 }
5114 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5115 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5116 notifyLockdownVpn(newNetwork);
5117 }
5118
Robert Greenwalt7b816022014-04-18 15:25:25 -07005119 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005120 // Notify battery stats service about this network, both the normal
5121 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005122 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005123 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005124 final IBatteryStats bs = BatteryStatsService.getService();
5125 final int type = newNetwork.networkInfo.getType();
5126
5127 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5128 bs.noteNetworkInterfaceType(baseIface, type);
5129 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5130 final String stackedIface = stacked.getInterfaceName();
5131 bs.noteNetworkInterfaceType(stackedIface, type);
5132 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5133 }
5134 } catch (RemoteException ignored) {
5135 }
5136
Robert Greenwalt152ed372014-12-17 17:19:53 -08005137 // This has to happen after the notifyNetworkCallbacks as that tickles each
5138 // ConnectivityManager instance so that legacy requests correctly bind dns
5139 // requests to this network. The legacy users are listening for this bcast
5140 // and will generally do a dns request so they can ensureRouteToHost and if
5141 // they do that before the callbacks happen they'll use the default network.
5142 //
5143 // TODO: Is there still a race here? We send the broadcast
5144 // after sending the callback, but if the app can receive the
5145 // broadcast before the callback, it might still break.
5146 //
5147 // This *does* introduce a race where if the user uses the new api
5148 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5149 // they may get old info. Reverse this after the old startUsing api is removed.
5150 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005151 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5152 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005153 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005154 // legacy type tracker filters out repeat adds
5155 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5156 }
5157 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005158
5159 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5160 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5161 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5162 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5163 if (newNetwork.isVPN()) {
5164 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5165 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005166 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005167 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5168 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005169 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005170 if (nai.getLingerExpiry() > 0) {
5171 // This network has active linger timers and no requests, but is not
5172 // lingering. Linger it.
5173 //
5174 // One way (the only way?) this can happen if this network is unvalidated
5175 // and became unneeded due to another network improving its score to the
5176 // point where this network will no longer be able to satisfy any requests
5177 // even if it validates.
5178 updateLingerState(nai, now);
5179 } else {
5180 if (DBG) log("Reaping " + nai.name());
5181 teardownUnneededNetwork(nai);
5182 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005183 }
5184 }
5185 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005186 }
5187
Paul Jensen1c7ba022015-06-16 14:27:36 -04005188 /**
5189 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5190 * being disconnected.
5191 * @param changed If only one Network's score or capabilities have been modified since the last
5192 * time this function was called, pass this Network in this argument, otherwise pass
5193 * null.
5194 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5195 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5196 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5197 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5198 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005199 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005200 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005201 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5202 // to avoid the slowness. It is not simply enough to process just "changed", for
5203 // example in the case where "changed"'s score decreases and another network should begin
5204 // satifying a NetworkRequest that "changed" currently satisfies.
5205
5206 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5207 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5208 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005209 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005210 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005211 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005212 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005213 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5214 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5215 // Rematch higher scoring networks first to prevent requests first matching a lower
5216 // scoring network and then a higher scoring network, which could produce multiple
5217 // callbacks and inadvertently unlinger networks.
5218 Arrays.sort(nais);
5219 for (NetworkAgentInfo nai : nais) {
5220 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005221 // Only reap the last time through the loop. Reaping before all rematching
5222 // is complete could incorrectly teardown a network that hasn't yet been
5223 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005224 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005225 : ReapUnvalidatedNetworks.REAP,
5226 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005227 }
5228 }
5229 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005230
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005231 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005232 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005233 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005234 // For now only update icons for default connection.
5235 // TODO: Update WiFi and cellular icons separately. b/17237507
5236 if (!isDefaultNetwork(nai)) return;
5237
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005238 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005239 // Don't repeat publish.
5240 if (newInetCondition == mDefaultInetConditionPublished) return;
5241
5242 mDefaultInetConditionPublished = newInetCondition;
5243 sendInetConditionBroadcast(nai.networkInfo);
5244 }
5245
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005246 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5247 if (mLockdownTracker != null) {
5248 if (nai != null && nai.isVPN()) {
5249 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5250 } else {
5251 mLockdownTracker.onNetworkInfoChanged();
5252 }
5253 }
5254 }
5255
Robert Greenwalt7b816022014-04-18 15:25:25 -07005256 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005257 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005258 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005259 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005260 synchronized (networkAgent) {
5261 oldInfo = networkAgent.networkInfo;
5262 networkAgent.networkInfo = newInfo;
5263 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005264 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005265
5266 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005267 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5268 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5269 notifyIfacesChangedForNetworkStats();
5270 } else if (VDBG) log("ignoring duplicate network state non-change");
5271 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005272 return;
5273 }
5274 if (DBG) {
5275 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5276 (oldInfo == null ? "null" : oldInfo.getState()) +
5277 " to " + state);
5278 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005279
Robin Lee585e2482016-05-01 23:00:00 +01005280 if (!networkAgent.created
5281 && (state == NetworkInfo.State.CONNECTED
5282 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005283
5284 // A network that has just connected has zero requests and is thus a foreground network.
5285 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5286
Robert Greenwalt7b816022014-04-18 15:25:25 -07005287 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005288 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005289 if (networkAgent.isVPN()) {
5290 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005291 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5292 (networkAgent.networkMisc == null ||
5293 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005294 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005295 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005296 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005297 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005298 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005299 loge("Error creating network " + networkAgent.network.netId + ": "
5300 + e.getMessage());
5301 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005302 }
Paul Jenseneec75412014-08-04 12:21:19 -04005303 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005304 }
5305
5306 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5307 networkAgent.everConnected = true;
5308
Robert Greenwalt7b816022014-04-18 15:25:25 -07005309 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005310 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005311
Paul Jensenca8f16a2014-05-09 12:47:55 -04005312 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005313 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005314
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005315 if (networkAgent.isVPN()) {
5316 // Temporarily disable the default proxy (not global).
5317 synchronized (mProxyLock) {
5318 if (!mDefaultProxyDisabled) {
5319 mDefaultProxyDisabled = true;
5320 if (mGlobalProxy == null && mDefaultProxy != null) {
5321 sendProxyBroadcast(null);
5322 }
5323 }
5324 }
5325 // TODO: support proxy per network.
5326 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005327
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005328 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5329 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5330 // capabilities, so it only needs to be done once on initial connect, not every time the
5331 // network's capabilities change. Note that we do this before rematching the network,
5332 // so we could decide to tear it down immediately afterwards. That's fine though - on
5333 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5334 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005335 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005336
Paul Jensen2161a8e2014-09-11 11:00:39 -04005337 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005338 final long now = SystemClock.elapsedRealtime();
5339 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005340
5341 // This has to happen after matching the requests, because callbacks are just requests.
5342 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005343 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005344 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005345 if (networkAgent.isVPN()) {
5346 synchronized (mProxyLock) {
5347 if (mDefaultProxyDisabled) {
5348 mDefaultProxyDisabled = false;
5349 if (mGlobalProxy == null && mDefaultProxy != null) {
5350 sendProxyBroadcast(mDefaultProxy);
5351 }
5352 }
5353 }
5354 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005355 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5356 state == NetworkInfo.State.SUSPENDED) {
5357 // going into or coming out of SUSPEND: rescore and notify
5358 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005359 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005360 }
5361 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5362 ConnectivityManager.CALLBACK_SUSPENDED :
5363 ConnectivityManager.CALLBACK_RESUMED));
5364 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005365 }
5366 }
5367
Robert Greenwaltac96c522014-06-03 16:43:57 -07005368 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005369 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005370 if (score < 0) {
5371 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5372 "). Bumping score to min of 0");
5373 score = 0;
5374 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005375
Paul Jensen2161a8e2014-09-11 11:00:39 -04005376 final int oldScore = nai.getCurrentScore();
5377 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005378
Paul Jensen85cf78e2015-06-25 13:25:07 -04005379 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005380
Paul Jensenc8b9a742014-09-30 15:37:41 -04005381 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005382 }
5383
Erik Klinec75d4fa2017-02-15 19:59:17 +09005384 // Notify only this one new request of the current state. Transfer all the
5385 // current state by calling NetworkCapabilities and LinkProperties callbacks
5386 // so that callers can be guaranteed to have as close to atomicity in state
5387 // transfer as can be supported by this current API.
5388 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohenbf3b1ba2016-10-27 15:05:50 -07005389 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005390 if (nri.mPendingIntent != null) {
5391 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5392 // Attempt no subsequent state pushes where intents are involved.
5393 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005394 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005395
5396 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5397 // Whether a network is currently suspended is also an important
5398 // element of state to be transferred (it would not otherwise be
5399 // delivered by any currently available mechanism).
5400 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5401 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5402 }
5403 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5404 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005405 }
5406
Robert Greenwalt8d482522015-06-24 13:23:42 -07005407 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005408 // The NetworkInfo we actually send out has no bearing on the real
5409 // state of affairs. For example, if the default connection is mobile,
5410 // and a request for HIPRI has just gone away, we need to pretend that
5411 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5412 // the state to DISCONNECTED, even though the network is of type MOBILE
5413 // and is still connected.
5414 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5415 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005416 if (state != DetailedState.DISCONNECTED) {
5417 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005418 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005419 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005420 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005421 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5422 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5423 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5424 if (info.isFailover()) {
5425 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5426 nai.networkInfo.setFailover(false);
5427 }
5428 if (info.getReason() != null) {
5429 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5430 }
5431 if (info.getExtraInfo() != null) {
5432 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5433 }
5434 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005435 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005436 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005437 if (newDefaultAgent != null) {
5438 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5439 newDefaultAgent.networkInfo);
5440 } else {
5441 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5442 }
5443 }
5444 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5445 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005446 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005447 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005448 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005449 }
5450 }
5451 }
5452
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005453 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005454 if (VDBG) {
5455 String notification = ConnectivityManager.getCallbackName(notifyType);
5456 log("notifyType " + notification + " for " + networkAgent.name());
5457 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005458 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5459 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005460 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5461 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005462 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5463 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005464 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005465 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005466 } else {
5467 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5468 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005469 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005470 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005471
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005472 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5473 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5474 }
5475
Jeff Sharkey69736342014-12-08 14:50:12 -08005476 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005477 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5478 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005479 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005480 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005481 try {
5482 mStatsService.forceUpdateIfaces();
5483 } catch (Exception ignored) {
5484 }
5485 }
5486
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005487 @Override
5488 public boolean addVpnAddress(String address, int prefixLength) {
5489 throwIfLockdownEnabled();
5490 int user = UserHandle.getUserId(Binder.getCallingUid());
5491 synchronized (mVpns) {
5492 return mVpns.get(user).addAddress(address, prefixLength);
5493 }
5494 }
5495
5496 @Override
5497 public boolean removeVpnAddress(String address, int prefixLength) {
5498 throwIfLockdownEnabled();
5499 int user = UserHandle.getUserId(Binder.getCallingUid());
5500 synchronized (mVpns) {
5501 return mVpns.get(user).removeAddress(address, prefixLength);
5502 }
5503 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005504
5505 @Override
5506 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5507 throwIfLockdownEnabled();
5508 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005509 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005510 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005511 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005512 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005513 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005514 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005515 }
5516 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005517 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005518
5519 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005520 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005521 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005522 }
5523
5524 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005525 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5526 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5527 enforceKeepalivePermission();
5528 mKeepaliveTracker.startNattKeepalive(
5529 getNetworkAgentInfoForNetwork(network),
5530 intervalSeconds, messenger, binder,
5531 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5532 }
5533
5534 @Override
5535 public void stopKeepalive(Network network, int slot) {
5536 mHandler.sendMessage(mHandler.obtainMessage(
5537 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5538 }
5539
5540 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005541 public void factoryReset() {
5542 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005543
5544 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5545 return;
5546 }
5547
Robin Lee3b3dd942015-05-12 18:14:58 +01005548 final int userId = UserHandle.getCallingUserId();
5549
Stuart Scottf1fb3972015-04-02 18:00:02 -07005550 // Turn airplane mode off
5551 setAirplaneMode(false);
5552
Stuart Scotte3e314d2015-04-20 14:07:45 -07005553 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5554 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005555 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005556 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005557 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005558 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005559 }
5560
Stuart Scotte3e314d2015-04-20 14:07:45 -07005561 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005562 // Remove always-on package
5563 synchronized (mVpns) {
5564 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5565 if (alwaysOnPackage != null) {
5566 setAlwaysOnVpnPackage(userId, null, false);
5567 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5568 }
5569 }
5570
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005571 // Turn Always-on VPN off
5572 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5573 final long ident = Binder.clearCallingIdentity();
5574 try {
5575 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5576 mLockdownEnabled = false;
5577 setLockdownTracker(null);
5578 } finally {
5579 Binder.restoreCallingIdentity(ident);
5580 }
5581 }
5582
Stuart Scotte3e314d2015-04-20 14:07:45 -07005583 // Turn VPN off
5584 VpnConfig vpnConfig = getVpnConfig(userId);
5585 if (vpnConfig != null) {
5586 if (vpnConfig.legacy) {
5587 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5588 } else {
5589 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5590 // in the future without user intervention.
5591 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005592
Victor Changb04a5ea2016-05-30 20:36:30 +01005593 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005594 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005595 }
5596 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005597
5598 Settings.Global.putString(mContext.getContentResolver(),
5599 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005600 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005601
5602 @VisibleForTesting
5603 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5604 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5605 return new NetworkMonitor(context, handler, nai, defaultRequest);
5606 }
Erik Kline48f12f22016-04-14 17:30:59 +09005607
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005608 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005609 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5610 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005611 }
5612
5613 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005614 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5615 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5616 }
5617
Hugo Benichicfddd682016-05-31 16:28:06 +09005618 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005619 int newNetid = NETID_UNSET;
5620 int prevNetid = NETID_UNSET;
5621 int[] transports = new int[0];
5622 boolean hadIPv4 = false;
5623 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005624
Hugo Benichi5f16f762016-04-20 12:09:33 +09005625 if (newNai != null) {
5626 newNetid = newNai.network.netId;
5627 transports = newNai.networkCapabilities.getTransportTypes();
5628 }
5629 if (prevNai != null) {
5630 prevNetid = prevNai.network.netId;
5631 final LinkProperties lp = prevNai.linkProperties;
5632 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5633 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5634 }
5635
Hugo Benichicfddd682016-05-31 16:28:06 +09005636 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5637 }
5638
5639 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5640 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005641 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005642
5643 private static boolean toBool(int encodedBoolean) {
5644 return encodedBoolean != 0; // Only 0 means false.
5645 }
5646
5647 private static int encodeBool(boolean b) {
5648 return b ? 1 : 0;
5649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650}