blob: 59c8840ebf179af23fae24ec7812281236dbf18b [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 Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060032import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070033import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070034import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060036import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070037import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060038
Wenchao Tongf5ea3402015-03-04 13:26:38 -080039import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080040import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090041import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070042import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.ContentResolver;
45import android.content.Context;
46import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070047import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070049import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090050import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070051import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090053import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070055import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070056import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070058import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080059import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070060import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070061import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070062import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070063import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070064import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070066import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070067import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070068import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070069import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070070import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070071import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070072import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040073import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070074import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040075import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040076import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090077import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090078import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090079import android.net.metrics.NetworkEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080081import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070082import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040083import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070085import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070086import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070087import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.Looper;
89import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070090import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070091import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070092import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070093import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070094import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080095import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090096import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070098import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040099import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700101import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700102import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700103import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700104import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600105import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700106import android.util.LocalLog;
107import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600108import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700109import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800110import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700111import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500112import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700114import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Wink Savilleab9321d2013-06-29 21:10:57 -0700116import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400117import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400118import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700119import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700120import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700122import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800123import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700124import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700125import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700126import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900127import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900128import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700129import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700130import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400131import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900132import com.android.server.connectivity.KeepaliveTracker;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900133import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900134import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700135import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600136import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400137import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900138import com.android.server.connectivity.NetworkNotificationManager;
139import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400140import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700141import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800142import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700143import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700144import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700145import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600146
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700147import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700148
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700149import org.xmlpull.v1.XmlPullParser;
150import org.xmlpull.v1.XmlPullParserException;
151
152import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700154import java.io.FileNotFoundException;
155import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700156import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700158import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700159import java.net.InetAddress;
160import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700161import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700162import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700163import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700164import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700165import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700166import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700167import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700168import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700169import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600170import java.util.SortedSet;
171import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
173/**
174 * @hide
175 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800176public class ConnectivityService extends IConnectivityManager.Stub
177 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900178 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900180 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700181 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
Jake Hamby786e71a2014-02-06 14:43:50 -0800183 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900184 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700185
Jeff Sharkey899223b2012-08-04 15:24:58 -0700186 // TODO: create better separation between radio types and network types
187
Robert Greenwalt42acef32009-08-12 16:08:25 -0700188 // how long to wait before switching back to a radio's default network
189 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
190 // system property that can override the above value
191 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
192 "android.telephony.apn-restore";
193
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900194 // How long to wait before putting up a "This network doesn't have an Internet connection,
195 // connect anyway?" dialog after the user selects a network that doesn't validate.
196 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
197
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900198 // Default to 30s linger time-out. Modifiable only for testing.
199 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
200 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
201 @VisibleForTesting
202 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
203
Jeremy Joslin79294842014-12-03 17:15:28 -0800204 // How long to delay to removal of a pending intent based request.
205 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
206 private final int mReleasePendingIntentDelayMs;
207
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800208 private Tethering mTethering;
209
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700210 private final PermissionMonitor mPermissionMonitor;
211
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700212 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700213
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700214 @GuardedBy("mVpns")
215 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700216
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700217 private boolean mLockdownEnabled;
218 private LockdownVpnTracker mLockdownTracker;
219
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700220 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
221 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600223 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700224 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700225 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600226 @GuardedBy("mRulesLock")
227 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
228 /** Flag indicating if background data is restricted. */
229 @GuardedBy("mRulesLock")
230 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700231
Erik Klineda4bfa82015-04-30 12:58:40 +0900232 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700234 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700235 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800237 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
239 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700240 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700242 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800243 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700244 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700245
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700246 private String mCurrentTcpBufferSizes;
247
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700248 private static final int ENABLED = 1;
249 private static final int DISABLED = 0;
250
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900251 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900252 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
253 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900254
Paul Jensenb10e37f2014-11-25 12:33:08 -0500255 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400256 // Tear down networks that have no chance (e.g. even if validated) of becoming
257 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500258 // all networks have been rematched against all NetworkRequests.
259 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400260 // Don't reap networks. This should be passed when some networks have not yet been
261 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500262 DONT_REAP
263 };
264
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700265 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700266 * used internally to change our mobile data enabled flag
267 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700268 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700269
270 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700271 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700272 * from one net to another. Clear happens when we get a new
273 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
274 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700275 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700276 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700277
Robert Greenwalt434203a2010-10-11 16:00:27 -0700278 /**
279 * used internally to reload global proxy settings
280 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700281 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700282
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700283 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400284 * PAC manager has received new port.
285 */
286 private static final int EVENT_PROXY_HAS_CHANGED = 16;
287
Robert Greenwalte049c232014-04-11 15:53:27 -0700288 /**
289 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700290 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700291 */
292 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
293
Robert Greenwalt7b816022014-04-18 15:25:25 -0700294 /**
295 * used internally when registering NetworkAgents
296 * obj = Messenger
297 */
298 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
299
Robert Greenwalt9258c642014-03-26 16:47:06 -0700300 /**
301 * used to add a network request
302 * includes a NetworkRequestInfo
303 */
304 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
305
306 /**
307 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900308 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700309 * cancel it.
310 * includes a NetworkRequestInfo
311 */
312 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
313
314 /**
315 * used to add a network listener - no request
316 * includes a NetworkRequestInfo
317 */
318 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
319
320 /**
321 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400322 * arg1 = UID of caller
323 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700324 */
325 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
326
Robert Greenwalta67be032014-05-16 15:49:14 -0700327 /**
328 * used internally when registering NetworkFactories
329 * obj = Messenger
330 */
331 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
332
Robert Greenwalt27711812014-06-25 16:45:57 -0700333 /**
334 * used internally to expire a wakelock when transitioning
335 * from one net to another. Expire happens when we fail to find
336 * a new network (typically after 1 minute) -
337 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
338 * a replacement network.
339 */
340 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
341
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700342 /**
343 * Used internally to indicate the system is ready.
344 */
345 private static final int EVENT_SYSTEM_READY = 25;
346
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800347 /**
348 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400349 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800350 */
351 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
352
353 /**
354 * used to remove a pending intent and its associated network request.
355 * arg1 = UID of caller
356 * obj = PendingIntent
357 */
358 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
359
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900360 /**
361 * used to specify whether a network should be used even if unvalidated.
362 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
363 * arg2 = whether to remember this choice in the future (1 or 0)
364 * obj = network
365 */
366 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
367
368 /**
369 * used to ask the user to confirm a connection to an unvalidated network.
370 * obj = network
371 */
372 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700373
Erik Klineda4bfa82015-04-30 12:58:40 +0900374 /**
375 * used internally to (re)configure mobile data always-on settings.
376 */
377 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
378
Paul Jensen694f2b82015-06-17 14:15:39 -0400379 /**
380 * used to add a network listener with a pending intent
381 * obj = NetworkRequestInfo
382 */
383 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
384
Erik Klineacdd6392016-07-07 16:50:58 +0900385 /**
386 * Indicates a caller has requested to have its callback invoked with
387 * the latest LinkProperties or NetworkCapabilities.
388 *
389 * arg1 = UID of caller
390 * obj = NetworkRequest
391 */
392 private static final int EVENT_REQUEST_LINKPROPERTIES = 32;
393 private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
394
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900395 /**
396 * Used internally to (re)configure avoid bad wifi setting.
397 */
398 private static final int EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI = 34;
399
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900400 /** Handler thread used for both of the handlers below. */
401 @VisibleForTesting
402 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700403 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700404 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700405 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700406 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700407
Mike Lockwood0f79b542009-08-14 14:18:49 -0400408 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800409 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400410
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700411 private PowerManager.WakeLock mNetTransitionWakeLock;
412 private String mNetTransitionWakeLockCausedBy = "";
413 private int mNetTransitionWakeLockSerialNumber;
414 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800415 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700416
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700417 // used in DBG mode to track inet condition reports
418 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
419 private ArrayList mInetLog;
420
Robert Greenwalt434203a2010-10-11 16:00:27 -0700421 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400422 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700423 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700424 private boolean mDefaultProxyDisabled = false;
425
Robert Greenwalt434203a2010-10-11 16:00:27 -0700426 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400427 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700428
Jason Monk602b2322013-07-03 17:04:33 -0400429 private PacManager mPacManager = null;
430
Erik Klineda4bfa82015-04-30 12:58:40 +0900431 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700432
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400433 private UserManager mUserManager;
434
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700435 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700436 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700437
Robert Greenwalt50393202011-06-21 17:26:14 -0700438 // the set of network types that can only be enabled by system/sig apps
439 List mProtectedNetworks;
440
John Spurlockbf991a82013-06-24 14:20:23 -0400441 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700442
Wink Savilleab9321d2013-06-29 21:10:57 -0700443 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400444
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900445 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900446 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900447 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900448
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700449 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
450 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700451 private final static int MAX_NET_ID = 65535;
452 private int mNextNetId = MIN_NET_ID;
453
Robert Greenwalt34524f02014-05-18 16:22:10 -0700454 // sequence number of NetworkRequests
455 private int mNextNetworkRequestId = 1;
456
Erik Kline7523eb32015-07-09 18:24:03 +0900457 // NetworkRequest activity String log entries.
458 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
459 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
460
Hugo Benichic2ae2872016-07-11 11:05:12 +0900461 // NetworkInfo blocked and unblocked String log entries
462 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
463 private static final int MAX_NETWORK_INFO_LOGS = 100;
464 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
465
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700466 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
467 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400468 private static class ValidationLog {
469 final Network mNetwork;
470 final String mNetworkExtraInfo;
471 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700472
Paul Jensen0808eb82016-06-03 13:51:21 -0400473 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
474 mNetwork = network;
475 mNetworkExtraInfo = networkExtraInfo;
476 mLog = log;
477 }
478 }
479 private final ArrayDeque<ValidationLog> mValidationLogs =
480 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
481
482 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700483 synchronized(mValidationLogs) {
484 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
485 mValidationLogs.removeLast();
486 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400487 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700488 }
489 }
490
Hugo Benichif9fdf872016-07-28 17:53:06 +0900491 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900492
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700493 /**
494 * Implements support for the legacy "one network per network type" model.
495 *
496 * We used to have a static array of NetworkStateTrackers, one for each
497 * network type, but that doesn't work any more now that we can have,
498 * for example, more that one wifi network. This class stores all the
499 * NetworkAgentInfo objects that support a given type, but the legacy
500 * API will only see the first one.
501 *
502 * It serves two main purposes:
503 *
504 * 1. Provide information about "the network for a given type" (since this
505 * API only supports one).
506 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
507 * the first network for a given type changes, or if the default network
508 * changes.
509 */
510 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900511
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900512 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900514
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700515 /**
516 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
517 * Each list holds references to all NetworkAgentInfos that are used to
518 * satisfy requests for that network type.
519 *
520 * This array is built out at startup such that an unsupported network
521 * doesn't get an ArrayList instance, making this a tristate:
522 * unsupported, supported but not active and active.
523 *
524 * The actual lists are populated when we scan the network types that
525 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900526 *
527 * Threading model:
528 * - addSupportedType() is only called in the constructor
529 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
530 * They are therefore not thread-safe with respect to each other.
531 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
532 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
533 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700534 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900535 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700536
537 public LegacyTypeTracker() {
538 mTypeLists = (ArrayList<NetworkAgentInfo>[])
539 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
540 }
541
542 public void addSupportedType(int type) {
543 if (mTypeLists[type] != null) {
544 throw new IllegalStateException(
545 "legacy list for type " + type + "already initialized");
546 }
547 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
548 }
549
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700550 public boolean isTypeSupported(int type) {
551 return isNetworkTypeValid(type) && mTypeLists[type] != null;
552 }
553
554 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900555 synchronized (mTypeLists) {
556 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
557 return mTypeLists[type].get(0);
558 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900560 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
562
Robert Greenwalt8d482522015-06-24 13:23:42 -0700563 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900564 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900565 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700566 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900567 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900568 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900569 }
570 }
571
572 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700573 public void add(int type, NetworkAgentInfo nai) {
574 if (!isTypeSupported(type)) {
575 return; // Invalid network type.
576 }
577 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
578
579 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
580 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700581 return;
582 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900583 synchronized (mTypeLists) {
584 list.add(nai);
585 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900586
587 // 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 +0900588 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900589 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700590 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
591 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700592 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700593 }
594
Lorenzo Colittia793a672014-07-31 23:20:17 +0900595 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900596 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900597 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
598 if (list == null || list.isEmpty()) {
599 return;
600 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900601 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900602
Hugo Benichi78caa2582016-06-21 09:48:07 +0900603 synchronized (mTypeLists) {
604 if (!list.remove(nai)) {
605 return;
606 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900607 }
608
Robert Greenwalt8d482522015-06-24 13:23:42 -0700609 final DetailedState state = DetailedState.DISCONNECTED;
610
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900611 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700612 maybeLogBroadcast(nai, state, type, wasDefault);
613 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900614 }
615
616 if (!list.isEmpty() && wasFirstNetwork) {
617 if (DBG) log("Other network available for type " + type +
618 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900619 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700620 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
621 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900622 }
623 }
624
625 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900626 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
627 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700628 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900629 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 }
631 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700632
Robert Greenwalt8d482522015-06-24 13:23:42 -0700633 // send out another legacy broadcast - currently only used for suspend/unsuspend
634 // toggle
635 public void update(NetworkAgentInfo nai) {
636 final boolean isDefault = isDefaultNetwork(nai);
637 final DetailedState state = nai.networkInfo.getDetailedState();
638 for (int type = 0; type < mTypeLists.length; type++) {
639 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700640 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900641 final boolean isFirst = contains && (nai == list.get(0));
642 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700643 maybeLogBroadcast(nai, state, type, isDefault);
644 sendLegacyNetworkBroadcast(nai, state, type);
645 }
646 }
647 }
648
Lorenzo Colittia793a672014-07-31 23:20:17 +0900649 private String naiToString(NetworkAgentInfo nai) {
650 String name = (nai != null) ? nai.name() : "null";
651 String state = (nai.networkInfo != null) ?
652 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
653 "???/???";
654 return name + " " + state;
655 }
656
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700657 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900658 pw.println("mLegacyTypeTracker:");
659 pw.increaseIndent();
660 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700661 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900662 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700663 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900664 pw.println();
665 pw.println("Current state:");
666 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900667 synchronized (mTypeLists) {
668 for (int type = 0; type < mTypeLists.length; type++) {
669 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
670 for (NetworkAgentInfo nai : mTypeLists[type]) {
671 pw.println(type + " " + naiToString(nai));
672 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900673 }
674 }
675 pw.decreaseIndent();
676 pw.decreaseIndent();
677 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700678 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700679 }
680 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
681
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900682 @VisibleForTesting
683 protected HandlerThread createHandlerThread() {
684 return new HandlerThread("ConnectivityServiceThread");
685 }
686
Jeff Sharkey899223b2012-08-04 15:24:58 -0700687 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700688 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900689 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
690 }
691
692 @VisibleForTesting
693 protected ConnectivityService(Context context, INetworkManagementService netManager,
694 INetworkStatsService statsService, INetworkPolicyManager policyManager,
695 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800696 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800697
Hugo Benichif9fdf872016-07-28 17:53:06 +0900698 mMetricsLog = logger;
Erik Klineda4bfa82015-04-30 12:58:40 +0900699 mDefaultRequest = createInternetRequestForTransport(-1);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900700 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900701 mNetworkRequests.put(mDefaultRequest, defaultNRI);
702 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900703
704 mDefaultMobileDataRequest = createInternetRequestForTransport(
705 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700706
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900707 mHandlerThread = createHandlerThread();
708 mHandlerThread.start();
709 mHandler = new InternalHandler(mHandlerThread.getLooper());
710 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700711
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800712 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800713 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
714 String id = Settings.Secure.getString(context.getContentResolver(),
715 Settings.Secure.ANDROID_ID);
716 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700717 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800718 SystemProperties.set("net.hostname", name);
719 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800720 }
721
Jeremy Joslin79294842014-12-03 17:15:28 -0800722 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
723 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
724
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900725 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
726
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700727 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700728 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800729 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700730 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700731 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700732 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700733
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700734 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600735 mPolicyManager.setConnectivityListener(mPolicyListener);
736 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700737 } catch (RemoteException e) {
738 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700739 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700740 }
741
742 final PowerManager powerManager = (PowerManager) context.getSystemService(
743 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700744 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
745 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
746 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800747 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700748
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700749 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700750
Wink Saville51f456f2013-04-23 14:26:51 -0700751 // TODO: What is the "correct" way to do determine if this is a wifi only device?
752 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
753 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700754 String[] naStrings = context.getResources().getStringArray(
755 com.android.internal.R.array.networkAttributes);
756 for (String naString : naStrings) {
757 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700758 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700759 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700760 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800761 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700762 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700763 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700764 }
Wink Saville51f456f2013-04-23 14:26:51 -0700765 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
766 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
767 n.type);
768 continue;
769 }
Wink Saville975c8482011-04-07 14:23:45 -0700770 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800771 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700772 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700773 continue;
774 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700775 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700776
Wink Saville975c8482011-04-07 14:23:45 -0700777 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700778 mNetworksDefined++;
779 } catch(Exception e) {
780 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700781 }
782 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700783
784 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
785 if (mNetConfigs[TYPE_VPN] == null) {
786 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
787 // don't need to add TYPE_VPN to mNetConfigs.
788 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
789 mNetworksDefined++; // used only in the log() statement below.
790 }
791
Wink Saville5e56bc52013-07-29 15:00:57 -0700792 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700793
Robert Greenwalt50393202011-06-21 17:26:14 -0700794 mProtectedNetworks = new ArrayList<Integer>();
795 int[] protectedNetworks = context.getResources().getIntArray(
796 com.android.internal.R.array.config_protectedNetworks);
797 for (int p : protectedNetworks) {
798 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
799 mProtectedNetworks.add(p);
800 } else {
801 if (DBG) loge("Ignoring protectedNetwork " + p);
802 }
803 }
804
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700805 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
806 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700807
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800808 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800809
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700810 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
811
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700812 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700813 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100814 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700815 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700816 intentFilter.addAction(Intent.ACTION_USER_ADDED);
817 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000818 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700819 mContext.registerReceiverAsUser(
820 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900821
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700822 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700823 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700824 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700825 } catch (RemoteException e) {
826 loge("Error registering observer :" + e);
827 }
828
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700829 if (DBG) {
830 mInetLog = new ArrayList();
831 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700832
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
855 intentFilter = new IntentFilter();
856 intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
857 mContext.registerReceiverAsUser(new BroadcastReceiver() {
858 public void onReceive(Context context, Intent intent) {
859 mHandler.sendEmptyMessage(EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
860 }
861 }, UserHandle.ALL, intentFilter, null, null);
862 updateAvoidBadWifi();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700864
Erik Klineda4bfa82015-04-30 12:58:40 +0900865 private NetworkRequest createInternetRequestForTransport(int transportType) {
866 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900867 netCap.addCapability(NET_CAPABILITY_INTERNET);
868 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900869 if (transportType > -1) {
870 netCap.addTransportType(transportType);
871 }
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900872 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(),
873 NetworkRequest.Type.REQUEST);
Erik Klineda4bfa82015-04-30 12:58:40 +0900874 }
875
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900876 // Used only for testing.
877 // TODO: Delete this and either:
878 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
879 // changing ContentResolver to make registerContentObserver non-final).
880 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
881 // by subclassing SettingsObserver.
882 @VisibleForTesting
883 void updateMobileDataAlwaysOn() {
884 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
885 }
886
Erik Klineda4bfa82015-04-30 12:58:40 +0900887 private void handleMobileDataAlwaysOn() {
888 final boolean enable = (Settings.Global.getInt(
889 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
890 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
891 if (enable == isEnabled) {
892 return; // Nothing to do.
893 }
894
895 if (enable) {
896 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900897 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900898 } else {
899 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
900 }
901 }
902
903 private void registerSettingsCallbacks() {
904 // Watch for global HTTP proxy changes.
905 mSettingsObserver.observe(
906 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
907 EVENT_APPLY_GLOBAL_HTTP_PROXY);
908
909 // Watch for whether or not to keep mobile data always on.
910 mSettingsObserver.observe(
911 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
912 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900913
914 // Watch for whether to automatically switch away from wifi networks that lose Internet
915 // access.
916 mSettingsObserver.observe(
917 Settings.Global.getUriFor(Settings.Global.NETWORK_AVOID_BAD_WIFI),
918 EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900919 }
920
Robert Greenwalt34524f02014-05-18 16:22:10 -0700921 private synchronized int nextNetworkRequestId() {
922 return mNextNetworkRequestId++;
923 }
924
Paul Jensen67b0b072015-06-10 11:22:17 -0400925 @VisibleForTesting
926 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400927 synchronized (mNetworkForNetId) {
928 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
929 int netId = mNextNetId;
930 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
931 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500932 if (!mNetIdInUse.get(netId)) {
933 mNetIdInUse.put(netId, true);
934 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400935 }
936 }
937 }
938 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700939 }
940
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600941 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800942 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600943 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
944 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800945 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600946 state = nai.getNetworkState();
947 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800948 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600949 final NetworkInfo info = new NetworkInfo(networkType, 0,
950 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800951 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
952 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600953 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
954 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800955 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600956 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600957 return state;
958 } else {
959 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800960 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400961 }
962
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800963 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
964 if (network == null) {
965 return null;
966 }
967 synchronized (mNetworkForNetId) {
968 return mNetworkForNetId.get(network.netId);
969 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600970 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800971
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900972 private Network[] getVpnUnderlyingNetworks(int uid) {
973 if (!mLockdownEnabled) {
974 int user = UserHandle.getUserId(uid);
975 synchronized (mVpns) {
976 Vpn vpn = mVpns.get(user);
977 if (vpn != null && vpn.appliesToUid(uid)) {
978 return vpn.getUnderlyingNetworks();
979 }
980 }
981 }
982 return null;
983 }
984
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800985 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400986 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800987
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900988 final Network[] networks = getVpnUnderlyingNetworks(uid);
989 if (networks != null) {
990 // getUnderlyingNetworks() returns:
991 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
992 // empty array => the VPN explicitly said "no default network".
993 // non-empty array => the VPN specified one or more default networks; we use the
994 // first one.
995 if (networks.length > 0) {
996 nai = getNetworkAgentInfoForNetwork(networks[0]);
997 } else {
998 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800999 }
1000 }
1001
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001002 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001003 return nai.getNetworkState();
1004 } else {
1005 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001006 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001007 }
1008
1009 /**
1010 * Check if UID should be blocked from using the network with the given LinkProperties.
1011 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001012 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1013 boolean ignoreBlocked) {
1014 // Networks aren't blocked when ignoring blocked status
1015 if (ignoreBlocked) return false;
1016 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001017 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001018
1019 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001020 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001021
Robin Lee17e61832016-05-09 13:46:28 +01001022 synchronized (mVpns) {
1023 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1024 if (vpn != null && vpn.isBlockingUid(uid)) {
1025 return true;
1026 }
1027 }
1028
Robert Greenwalt12e67352014-05-13 21:41:06 -07001029 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001030 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001031 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001032 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001033 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001034
Felipe Lemed31a97f2016-05-06 14:53:50 -07001035 boolean allowed = true;
1036 // Check Data Saver Mode first...
1037 if (networkMetered) {
1038 if ((uidRules & RULE_REJECT_METERED) != 0) {
1039 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1040 // Explicitly blacklisted.
1041 allowed = false;
1042 } else {
1043 allowed = !mRestrictBackground
1044 || (uidRules & RULE_ALLOW_METERED) != 0
1045 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1046 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1047 + " mRestrictBackground=" + mRestrictBackground
1048 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1049 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1050 + ": " + allowed);
1051 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001052 }
Felipe Leme781ba142016-05-09 16:24:48 -07001053 // ...then power restrictions.
1054 if (allowed) {
1055 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001056 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001057 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001058 }
1059 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001060 }
1061
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001062 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001063 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1064 return;
1065 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001066 boolean removed = false;
1067 boolean added = false;
1068 synchronized (mBlockedAppUids) {
1069 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1070 added = true;
1071 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1072 removed = true;
1073 }
1074 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001075 if (added) {
1076 log("Returning blocked NetworkInfo to uid=" + uid);
1077 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1078 } else if (removed) {
1079 log("Returning unblocked NetworkInfo to uid=" + uid);
1080 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1081 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001082 }
1083
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001084 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001085 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1086 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1087 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1088 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001089 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001090 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001091 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1092
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001093 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001094 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001095 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001096 if (mLockdownTracker != null) {
1097 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001098 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001099
1100 // TODO: apply metered state closer to NetworkAgentInfo
1101 final long token = Binder.clearCallingIdentity();
1102 try {
1103 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1104 } catch (RemoteException e) {
1105 } finally {
1106 Binder.restoreCallingIdentity(token);
1107 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001108 }
1109
1110 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 * Return NetworkInfo for the active (i.e., connected) network interface.
1112 * It is assumed that at most one network is active at a time. If more
1113 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001114 * @return the info for the active network, or {@code null} if none is
1115 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001117 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001119 enforceAccessPermission();
1120 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001121 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001123 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1124 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 }
1126
Paul Jensen31a94f42015-02-13 14:18:39 -05001127 @Override
1128 public Network getActiveNetwork() {
1129 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001130 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001131 }
1132
1133 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001134 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001135 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001136 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001137 }
1138
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001139 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001140 final int user = UserHandle.getUserId(uid);
1141 int vpnNetId = NETID_UNSET;
1142 synchronized (mVpns) {
1143 final Vpn vpn = mVpns.get(user);
1144 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1145 }
1146 NetworkAgentInfo nai;
1147 if (vpnNetId != NETID_UNSET) {
1148 synchronized (mNetworkForNetId) {
1149 nai = mNetworkForNetId.get(vpnNetId);
1150 }
1151 if (nai != null) return nai.network;
1152 }
1153 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001154 if (nai != null
1155 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1156 nai = null;
1157 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001158 return nai != null ? nai.network : null;
1159 }
1160
Lorenzo Colitti18660282016-07-04 12:55:44 +09001161 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001162 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1163 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001164 final int uid = Binder.getCallingUid();
1165 NetworkState state = getUnfilteredActiveNetworkState(uid);
1166 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001167 }
1168
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001169 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001170 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001171 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001172 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001173 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001174 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001175 }
1176
1177 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 public NetworkInfo getNetworkInfo(int networkType) {
1179 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001180 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001181 if (getVpnUnderlyingNetworks(uid) != null) {
1182 // A VPN is active, so we may need to return one of its underlying networks. This
1183 // information is not available in LegacyTypeTracker, so we have to get it from
1184 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001185 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001186 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001187 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001188 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001189 }
1190 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001191 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001192 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 }
1194
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001195 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001196 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001197 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001198 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001199 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001200 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001201 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001202 return state.networkInfo;
1203 } else {
1204 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001205 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001206 }
1207
1208 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 public NetworkInfo[] getAllNetworkInfo() {
1210 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001211 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001212 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1213 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001214 NetworkInfo info = getNetworkInfo(networkType);
1215 if (info != null) {
1216 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001219 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
1221
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001222 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001223 public Network getNetworkForType(int networkType) {
1224 enforceAccessPermission();
1225 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001226 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1227 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001228 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001229 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001230 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001231 }
1232
1233 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001234 public Network[] getAllNetworks() {
1235 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001236 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001237 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001238 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001239 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001240 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001241 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001242 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001243 }
1244
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001245 @Override
1246 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1247 // The basic principle is: if an app's traffic could possibly go over a
1248 // network, without the app doing anything multinetwork-specific,
1249 // (hence, by "default"), then include that network's capabilities in
1250 // the array.
1251 //
1252 // In the normal case, app traffic only goes over the system's default
1253 // network connection, so that's the only network returned.
1254 //
1255 // With a VPN in force, some app traffic may go into the VPN, and thus
1256 // over whatever underlying networks the VPN specifies, while other app
1257 // traffic may go over the system default network (e.g.: a split-tunnel
1258 // VPN, or an app disallowed by the VPN), so the set of networks
1259 // returned includes the VPN's underlying networks and the system
1260 // default.
1261 enforceAccessPermission();
1262
1263 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1264
1265 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001266 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001267 if (nc != null) {
1268 result.put(nai.network, nc);
1269 }
1270
1271 if (!mLockdownEnabled) {
1272 synchronized (mVpns) {
1273 Vpn vpn = mVpns.get(userId);
1274 if (vpn != null) {
1275 Network[] networks = vpn.getUnderlyingNetworks();
1276 if (networks != null) {
1277 for (Network network : networks) {
1278 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001279 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001280 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001281 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001282 }
1283 }
1284 }
1285 }
1286 }
1287 }
1288
1289 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1290 out = result.values().toArray(out);
1291 return out;
1292 }
1293
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001294 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001295 public boolean isNetworkSupported(int networkType) {
1296 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001297 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001298 }
1299
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001300 /**
1301 * Return LinkProperties for the active (i.e., connected) default
1302 * network interface. It is assumed that at most one default network
1303 * is active at a time. If more than one is active, it is indeterminate
1304 * which will be returned.
1305 * @return the ip properties for the active network, or {@code null} if
1306 * none is active
1307 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001308 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001309 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001310 enforceAccessPermission();
1311 final int uid = Binder.getCallingUid();
1312 NetworkState state = getUnfilteredActiveNetworkState(uid);
1313 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001314 }
1315
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001316 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001317 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001318 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001319 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1320 if (nai != null) {
1321 synchronized (nai) {
1322 return new LinkProperties(nai.linkProperties);
1323 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001324 }
1325 return null;
1326 }
1327
Robert Greenwalt12e67352014-05-13 21:41:06 -07001328 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001329 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001330 public LinkProperties getLinkProperties(Network network) {
1331 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001332 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001333 if (nai != null) {
1334 synchronized (nai) {
1335 return new LinkProperties(nai.linkProperties);
1336 }
1337 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001338 return null;
1339 }
1340
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001341 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001342 if (nai != null) {
1343 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001344 if (nai.networkCapabilities != null) {
1345 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001346 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001347 }
1348 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001349 return null;
1350 }
1351
1352 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001353 public NetworkCapabilities getNetworkCapabilities(Network network) {
1354 enforceAccessPermission();
1355 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1356 }
1357
1358 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001359 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001360 // Require internal since we're handing out IMSI details
1361 enforceConnectivityInternalPermission();
1362
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001363 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001364 for (Network network : getAllNetworks()) {
1365 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1366 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001367 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001368 }
1369 }
1370 return result.toArray(new NetworkState[result.size()]);
1371 }
1372
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001373 @Override
1374 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1375 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001376 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001377 final long token = Binder.clearCallingIdentity();
1378 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001379 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1380 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001381 try {
1382 return mPolicyManager.getNetworkQuotaInfo(state);
1383 } catch (RemoteException e) {
1384 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001385 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001386 return null;
1387 } finally {
1388 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001389 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001390 }
1391
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001392 @Override
1393 public boolean isActiveNetworkMetered() {
1394 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001395
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001396 final NetworkInfo info = getActiveNetworkInfo();
1397 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001398 }
1399
Jeff Sharkey216c1812012-08-05 14:29:23 -07001400 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1401 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001402 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001403 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001404 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001405 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001406 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001407
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001408 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 * Ensure that a network route exists to deliver traffic to the specified
1410 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001411 * @param networkType the type of the network over which traffic to the
1412 * specified host is to be routed
1413 * @param hostAddress the IP address of the host to which the route is
1414 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 * @return {@code true} on success, {@code false} on failure
1416 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001417 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001418 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001420 if (mProtectedNetworks.contains(networkType)) {
1421 enforceConnectivityInternalPermission();
1422 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001423
Chad Brubakerc0234532014-02-14 13:24:29 -08001424 InetAddress addr;
1425 try {
1426 addr = InetAddress.getByAddress(hostAddress);
1427 } catch (UnknownHostException e) {
1428 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1429 return false;
1430 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001433 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 return false;
1435 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001436
1437 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1438 if (nai == null) {
1439 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1440 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1441 } else {
1442 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1443 }
1444 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001445 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001446
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001447 DetailedState netState;
1448 synchronized (nai) {
1449 netState = nai.networkInfo.getDetailedState();
1450 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001451
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001452 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001453 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001454 log("requestRouteToHostAddress on down network "
1455 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001456 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001457 }
1458 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001460
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001461 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001462 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001463 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001464 LinkProperties lp;
1465 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001466 synchronized (nai) {
1467 lp = nai.linkProperties;
1468 netId = nai.network.netId;
1469 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001470 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001471 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1472 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001473 } finally {
1474 Binder.restoreCallingIdentity(token);
1475 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001476 }
1477
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001478 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001479 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001480 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001481 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001482 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001483 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001484 if (bestRoute.getGateway().equals(addr)) {
1485 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001486 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001487 } else {
1488 // if we will connect to this through another route, add a direct route
1489 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001490 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001491 }
1492 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001493 if (DBG) log("Adding legacy route " + bestRoute +
1494 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001495 try {
1496 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1497 } catch (Exception e) {
1498 // never crash - catch them all
1499 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001500 return false;
1501 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001502 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 }
1504
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001505 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1506 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001507 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001508 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001509 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001510 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001511 }
1512
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001513 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001514 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001515 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001516 if (oldRules == uidRules) return;
1517
Felipe Leme781ba142016-05-09 16:24:48 -07001518 if (uidRules == RULE_NONE) {
1519 mUidRules.delete(uid);
1520 } else {
1521 mUidRules.put(uid, uidRules);
1522 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001523 }
1524
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001525 // TODO: notify UID when it has requested targeted updates
1526 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001527
1528 @Override
1529 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001530 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001531 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001532 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001533 }
1534
1535 synchronized (mRulesLock) {
1536 mMeteredIfaces.clear();
1537 for (String iface : meteredIfaces) {
1538 mMeteredIfaces.add(iface);
1539 }
1540 }
1541 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001542
1543 @Override
1544 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1545 // caller is NPMS, since we only register with them
1546 if (LOGD_RULES) {
1547 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1548 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001549
1550 synchronized (mRulesLock) {
1551 mRestrictBackground = restrictBackground;
1552 }
1553
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001554 if (restrictBackground) {
1555 log("onRestrictBackgroundChanged(true): disabling tethering");
1556 mTethering.untetherAll();
1557 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001558 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001559
1560 @Override
1561 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1562 if (LOGD_RULES) {
1563 // caller is NPMS, since we only register with them
1564 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1565 + whitelisted + ")");
1566 }
1567 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001568 @Override
1569 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1570 if (LOGD_RULES) {
1571 // caller is NPMS, since we only register with them
1572 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1573 + blacklisted + ")");
1574 }
1575 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001576 };
1577
Robin Lee3b3dd942015-05-12 18:14:58 +01001578 /**
1579 * Require that the caller is either in the same user or has appropriate permission to interact
1580 * across users.
1581 *
1582 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1583 */
1584 private void enforceCrossUserPermission(int userId) {
1585 if (userId == UserHandle.getCallingUserId()) {
1586 // Not a cross-user call.
1587 return;
1588 }
1589 mContext.enforceCallingOrSelfPermission(
1590 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1591 "ConnectivityService");
1592 }
1593
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001594 private void enforceInternetPermission() {
1595 mContext.enforceCallingOrSelfPermission(
1596 android.Manifest.permission.INTERNET,
1597 "ConnectivityService");
1598 }
1599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001601 mContext.enforceCallingOrSelfPermission(
1602 android.Manifest.permission.ACCESS_NETWORK_STATE,
1603 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 }
1605
1606 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001607 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 }
1609
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001610 private void enforceTetherAccessPermission() {
1611 mContext.enforceCallingOrSelfPermission(
1612 android.Manifest.permission.ACCESS_NETWORK_STATE,
1613 "ConnectivityService");
1614 }
1615
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001616 private void enforceConnectivityInternalPermission() {
1617 mContext.enforceCallingOrSelfPermission(
1618 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1619 "ConnectivityService");
1620 }
1621
Hugo Benichi514da602016-07-19 15:59:27 +09001622 private void enforceConnectivityRestrictedNetworksPermission() {
1623 try {
1624 mContext.enforceCallingOrSelfPermission(
1625 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1626 "ConnectivityService");
1627 return;
1628 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1629 enforceConnectivityInternalPermission();
1630 }
1631
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001632 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001633 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001634 }
1635
Lorenzo Colitti18660282016-07-04 12:55:44 +09001636 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001637 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001638 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001639 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001640 }
1641
1642 private void sendInetConditionBroadcast(NetworkInfo info) {
1643 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1644 }
1645
Wink Saville628b0852011-08-04 15:01:58 -07001646 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001647 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001648 info = new NetworkInfo(info);
1649 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001650 }
1651
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001652 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001653 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001654 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 if (info.isFailover()) {
1656 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1657 info.setFailover(false);
1658 }
1659 if (info.getReason() != null) {
1660 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1661 }
1662 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001663 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1664 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001666 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001667 return intent;
1668 }
1669
1670 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1671 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1672 }
1673
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001674 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001675 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1676 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1677 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001678 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001679 final long ident = Binder.clearCallingIdentity();
1680 try {
1681 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1682 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1683 } finally {
1684 Binder.restoreCallingIdentity(ident);
1685 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001686 }
1687
Mike Lockwood0f79b542009-08-14 14:18:49 -04001688 private void sendStickyBroadcast(Intent intent) {
1689 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001690 if (!mSystemReady) {
1691 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001692 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001693 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001694 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001695 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001696 }
1697
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001698 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001699 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001700 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001701 final NetworkInfo ni = intent.getParcelableExtra(
1702 ConnectivityManager.EXTRA_NETWORK_INFO);
1703 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1704 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1705 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001706 } else {
1707 BroadcastOptions opts = BroadcastOptions.makeBasic();
1708 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1709 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001710 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001711 final IBatteryStats bs = BatteryStatsService.getService();
1712 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001713 bs.noteConnectivityChanged(intent.getIntExtra(
1714 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1715 ni != null ? ni.getState().toString() : "?");
1716 } catch (RemoteException e) {
1717 }
1718 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001719 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001720 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001721 } finally {
1722 Binder.restoreCallingIdentity(ident);
1723 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001724 }
1725 }
1726
1727 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001728 loadGlobalProxy();
1729
Mike Lockwood0f79b542009-08-14 14:18:49 -04001730 synchronized(this) {
1731 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001732 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001733 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001734 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001735 }
1736 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001737 // load the global proxy at startup
1738 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001739
Robin Lee244ce8e2016-01-05 18:03:46 +00001740 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1741 // for user to unlock device too.
1742 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001743
Erik Klineda4bfa82015-04-30 12:58:40 +09001744 // Configure whether mobile data is always on.
1745 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1746
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001747 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001748
1749 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
1751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001753 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001754 *
1755 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001756 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001757 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001758 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1759 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001760
1761 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001762 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001763
Robert Greenwalt7b816022014-04-18 15:25:25 -07001764 if (networkAgent.networkCapabilities.hasTransport(
1765 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001766 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1767 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001768 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001769 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001770 } else if (networkAgent.networkCapabilities.hasTransport(
1771 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001772 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1773 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001774 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001775 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001776 } else {
1777 // do not track any other networks
1778 timeout = 0;
1779 }
1780
Robert Greenwalt7b816022014-04-18 15:25:25 -07001781 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001782 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001783 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001784 } catch (Exception e) {
1785 // You shall not crash!
1786 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001787 }
1788 }
1789 }
1790
1791 /**
1792 * Remove data activity tracking when network disconnects.
1793 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001794 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1795 final String iface = networkAgent.linkProperties.getInterfaceName();
1796 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001797
Robert Greenwalt7b816022014-04-18 15:25:25 -07001798 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1799 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001800 try {
1801 // the call fails silently if no idletimer setup for this interface
1802 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001803 } catch (Exception e) {
1804 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001805 }
1806 }
1807 }
1808
1809 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001810 * Reads the network specific MTU size from reources.
1811 * and set it on it's iface.
1812 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001813 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1814 final String iface = newLp.getInterfaceName();
1815 final int mtu = newLp.getMtu();
1816 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1817 if (VDBG) log("identical MTU - not setting");
1818 return;
1819 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001820
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
Paul Jensend7b6ca92015-05-13 14:05:12 -04001845 protected int getDefaultTcpRwnd() {
1846 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1847 }
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(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001884 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001885 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1886 if (rwndValue != 0) {
1887 SystemProperties.set(sysctlKey, rwndValue.toString());
1888 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001889 }
1890
Mattias Falk8b47b362011-08-23 14:15:13 +02001891 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001892 /*
1893 * Tell the VMs to toss their DNS caches
1894 */
1895 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1896 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001897 /*
1898 * Connectivity events can happen before boot has completed ...
1899 */
1900 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001901 final long ident = Binder.clearCallingIdentity();
1902 try {
1903 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1904 } finally {
1905 Binder.restoreCallingIdentity(ident);
1906 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001907 }
1908
Robert Greenwalt562cc542014-05-15 18:07:26 -07001909 @Override
1910 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001911 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1912 NETWORK_RESTORE_DELAY_PROP_NAME);
1913 if(restoreDefaultNetworkDelayStr != null &&
1914 restoreDefaultNetworkDelayStr.length() != 0) {
1915 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001916 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001917 } catch (NumberFormatException e) {
1918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001920 // if the system property isn't set, use the value for the apn type
1921 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1922
1923 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1924 (mNetConfigs[networkType] != null)) {
1925 ret = mNetConfigs[networkType].restoreTime;
1926 }
1927 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
1929
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001930 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001931 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001932 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001933 }
1934 return false;
1935 }
1936
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001937 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1938 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1939 final long DIAG_TIME_MS = 5000;
1940 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1941 // Start gathering diagnostic information.
1942 netDiags.add(new NetworkDiagnostics(
1943 nai.network,
1944 new LinkProperties(nai.linkProperties), // Must be a copy.
1945 DIAG_TIME_MS));
1946 }
1947
1948 for (NetworkDiagnostics netDiag : netDiags) {
1949 pw.println();
1950 netDiag.waitForMeasurements();
1951 netDiag.dump(pw);
1952 }
1953 }
1954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001956 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1957 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001958 if (mContext.checkCallingOrSelfPermission(
1959 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001961 pw.println("Permission Denial: can't dump ConnectivityService " +
1962 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1963 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 return;
1965 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001966
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001967 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001968 dumpNetworkDiagnostics(pw);
1969 return;
1970 }
Erik Kline379747a2015-06-05 17:47:34 +09001971
Lorenzo Colittie3805462015-06-03 11:18:24 +09001972 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001973 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001974 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001975 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001976 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001977 pw.println();
1978
Paul Jensen85cf78e2015-06-25 13:25:07 -04001979 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001980 pw.print("Active default network: ");
1981 if (defaultNai == null) {
1982 pw.println("none");
1983 } else {
1984 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001986 pw.println();
1987
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001988 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001989 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001990 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1991 pw.println(nai.toString());
1992 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001993 pw.println(String.format("Requests: %d request/%d total",
1994 nai.numRequestNetworkRequests(), nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001995 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001996 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1997 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001998 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001999 pw.decreaseIndent();
2000 pw.println("Lingered:");
2001 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002002 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002003 pw.decreaseIndent();
2004 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002005 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002006 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002007 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002008
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002009 pw.println("Metered Interfaces:");
2010 pw.increaseIndent();
2011 for (String value : mMeteredIfaces) {
2012 pw.println(value);
2013 }
2014 pw.decreaseIndent();
2015 pw.println();
2016
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002017 pw.print("Restrict background: ");
2018 pw.println(mRestrictBackground);
2019 pw.println();
2020
Felipe Leme46c4fc32016-05-04 09:21:43 -07002021 pw.println("Status for known UIDs:");
2022 pw.increaseIndent();
2023 final int size = mUidRules.size();
2024 for (int i = 0; i < size; i++) {
2025 final int uid = mUidRules.keyAt(i);
2026 pw.print("UID=");
2027 pw.print(uid);
2028 final int uidRules = mUidRules.get(uid, RULE_NONE);
2029 pw.print(" rules=");
2030 pw.print(uidRulesToString(uidRules));
2031 pw.println();
2032 }
2033 pw.println();
2034 pw.decreaseIndent();
2035
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002036 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002037 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002038 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2039 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002040 }
2041 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002042 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002043
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002044 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002045
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002046 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002047 pw.print("mNetTransitionWakeLock: currently " +
2048 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2049 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2050 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2051 } else {
2052 pw.println(", last requested never");
2053 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002054 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002055
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002056 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002057 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002058
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002059 pw.println();
2060 mKeepaliveTracker.dump(pw);
2061
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002062 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002063
Lorenzo Colittie3805462015-06-03 11:18:24 +09002064 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002065 pw.println();
2066 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002067 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002068 for(int i = 0; i < mInetLog.size(); i++) {
2069 pw.println(mInetLog.get(i));
2070 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002071 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002072 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002073
2074 if (argsContain(args, "--short") == false) {
2075 pw.println();
2076 synchronized (mValidationLogs) {
2077 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002078 for (ValidationLog p : mValidationLogs) {
2079 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002080 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002081 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002082 pw.decreaseIndent();
2083 }
2084 }
Erik Kline7523eb32015-07-09 18:24:03 +09002085
2086 pw.println();
2087 pw.println("mNetworkRequestInfoLogs (most recent first):");
2088 pw.increaseIndent();
2089 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2090 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002091
2092 pw.println();
2093 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2094 pw.increaseIndent();
2095 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2096 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 }
2099
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002100 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002101 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002102 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002103 if (officialNai != null && officialNai.equals(nai)) return true;
2104 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002105 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002106 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002107 " - " + nai);
2108 }
2109 return false;
2110 }
2111
Robert Greenwalt42acef32009-08-12 16:08:25 -07002112 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002113 private class NetworkStateTrackerHandler extends Handler {
2114 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002115 super(looper);
2116 }
2117
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002118 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002120 default:
2121 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002122 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002123 handleAsyncChannelHalfConnect(msg);
2124 break;
2125 }
2126 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2127 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2128 if (nai != null) nai.asyncChannel.disconnect();
2129 break;
2130 }
2131 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2132 handleAsyncChannelDisconnected(msg);
2133 break;
2134 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002135 }
2136 return true;
2137 }
2138
2139 private void maybeHandleNetworkAgentMessage(Message msg) {
2140 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2141 if (nai == null) {
2142 if (VDBG) {
2143 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2144 log(String.format("%s from unknown NetworkAgent", what));
2145 }
2146 return;
2147 }
2148
2149 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002151 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2152 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2153 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2154 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002155 }
Robin Lee585e2482016-05-01 23:00:00 +01002156 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002157 networkCapabilities)) {
2158 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2159 + nai.networkCapabilities + " -> " + networkCapabilities);
2160 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002161 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002162 break;
2163 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002164 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002165 if (VDBG) {
2166 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002167 "; created=" + nai.created +
2168 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002169 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002170 LinkProperties oldLp = nai.linkProperties;
2171 synchronized (nai) {
2172 nai.linkProperties = (LinkProperties)msg.obj;
2173 }
Robin Lee585e2482016-05-01 23:00:00 +01002174 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002175 break;
2176 }
2177 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002178 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002179 updateNetworkInfo(nai, info);
2180 break;
2181 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002182 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002183 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002184 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002185 break;
2186 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002187 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002188 try {
2189 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002190 } catch (Exception e) {
2191 // Never crash!
2192 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002193 }
2194 break;
2195 }
2196 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002197 try {
2198 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002199 } catch (Exception e) {
2200 // Never crash!
2201 loge("Exception in removeVpnUidRanges: " + e);
2202 }
2203 break;
2204 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002205 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002206 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2207 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002208 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002209 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002210 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002211 break;
2212 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002213 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002214 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2215 break;
2216 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002217 }
2218 }
2219
2220 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2221 switch (msg.what) {
2222 default:
2223 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002224 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002225 final NetworkAgentInfo nai;
2226 synchronized (mNetworkForNetId) {
2227 nai = mNetworkForNetId.get(msg.arg2);
2228 }
2229 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002230 final boolean valid =
2231 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002232 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002233 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2234 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002235 if (valid != nai.lastValidated) {
2236 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002237 nai.lastValidated = valid;
2238 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002239 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002240 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2241 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002242 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002243 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002244 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002245 Bundle redirectUrlBundle = new Bundle();
2246 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002247 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002248 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002249 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002250 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002251 if (wasValidated && !nai.lastValidated) {
2252 handleNetworkUnvalidated(nai);
2253 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002254 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002255 break;
2256 }
Paul Jensen869868be2014-05-15 10:33:05 -04002257 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002258 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002259 final boolean visible = (msg.arg1 != 0);
2260 final NetworkAgentInfo nai;
2261 synchronized (mNetworkForNetId) {
2262 nai = mNetworkForNetId.get(netId);
2263 }
2264 // If captive portal status has changed, update capabilities.
2265 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002266 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002267 nai.lastCaptivePortalDetected = visible;
2268 nai.everCaptivePortalDetected |= visible;
Hugo Benichif15b2822016-09-15 18:18:48 +09002269 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002270 }
2271 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002272 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002273 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002274 if (nai == null) {
2275 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2276 break;
2277 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002278 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002279 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002280 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002281 }
Paul Jensen869868be2014-05-15 10:33:05 -04002282 }
Paul Jensen869868be2014-05-15 10:33:05 -04002283 break;
2284 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002285 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002286 return true;
2287 }
2288
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002289 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2290 switch (msg.what) {
2291 default:
2292 return false;
2293 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2294 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2295 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2296 handleLingerComplete(nai);
2297 }
2298 break;
2299 }
2300 }
2301 return true;
2302 }
2303
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002304 @Override
2305 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002306 if (!maybeHandleAsyncChannelMessage(msg) &&
2307 !maybeHandleNetworkMonitorMessage(msg) &&
2308 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002309 maybeHandleNetworkAgentMessage(msg);
2310 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002311 }
2312 }
2313
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002314 private void updateLingerState(NetworkAgentInfo nai, long now) {
2315 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2316 // 2. If the network was lingering and there are now requests, unlinger it.
2317 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2318 // one lingered request, start lingering.
2319 nai.updateLingerTimer();
2320 if (nai.isLingering() && nai.numRequestNetworkRequests() > 0) {
2321 if (DBG) log("Unlingering " + nai.name());
2322 nai.unlinger();
2323 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
2324 } else if (unneeded(nai) && nai.getLingerExpiry() > 0) { // unneeded() calls isLingering()
2325 int lingerTime = (int) (nai.getLingerExpiry() - now);
2326 if (DBG) {
2327 Log.d(TAG, "Lingering " + nai.name() + " for " + lingerTime + "ms");
2328 }
2329 nai.linger();
2330 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2331 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2332 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002333 }
2334
Robert Greenwalt7b816022014-04-18 15:25:25 -07002335 private void handleAsyncChannelHalfConnect(Message msg) {
2336 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002337 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002338 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2339 if (VDBG) log("NetworkFactory connected");
2340 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002341 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002342 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002343 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002344 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002345 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002346 }
2347 } else {
2348 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002349 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002350 }
2351 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2352 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2353 if (VDBG) log("NetworkAgent connected");
2354 // A network agent has requested a connection. Establish the connection.
2355 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2356 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2357 } else {
2358 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002359 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002360 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002361 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002362 synchronized (mNetworkForNetId) {
2363 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002364 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002365 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002366 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002367 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002368 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002369 }
2370 }
2371 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002372
Robert Greenwalt7b816022014-04-18 15:25:25 -07002373 private void handleAsyncChannelDisconnected(Message msg) {
2374 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2375 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002376 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002377 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002378 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002379 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002380 // TODO - if we move the logic to the network agent (have them disconnect
2381 // because they lost all their requests or because their score isn't good)
2382 // then they would disconnect organically, report their new state and then
2383 // disconnect the channel.
2384 if (nai.networkInfo.isConnected()) {
2385 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2386 null, null);
2387 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002388 final boolean wasDefault = isDefaultNetwork(nai);
2389 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002390 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002391 // Log default network disconnection before required book-keeping.
2392 // Let rematchAllNetworksAndRequests() below record a new default network event
2393 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2394 // whose timestamps tell how long it takes to recover a default network.
2395 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002396 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002397 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002398 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2399 // by other networks that are already connected. Perhaps that can be done by
2400 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2401 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002402 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002403 mKeepaliveTracker.handleStopAllKeepalives(nai,
2404 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002405 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002406 mNetworkAgentInfos.remove(msg.replyTo);
2407 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002408 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002409 // Remove the NetworkAgent, but don't mark the netId as
2410 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002411 mNetworkForNetId.remove(nai.network.netId);
2412 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002413 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002414 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2415 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002416 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2417 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2418 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002419 sendUpdatedScoreToFactories(request, 0);
2420 }
2421 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002422 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002423 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002424 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002425 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002426 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002427 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002428 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002429 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002430 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002431 if (nai.created) {
2432 // Tell netd to clean up the configuration for this network
2433 // (routing rules, DNS, etc).
2434 // This may be slow as it requires a lot of netd shelling out to ip and
2435 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2436 // after we've rematched networks with requests which should make a potential
2437 // fallback network the default or requested a new network from the
2438 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2439 // long time.
2440 try {
2441 mNetd.removeNetwork(nai.network.netId);
2442 } catch (Exception e) {
2443 loge("Exception removing network: " + e);
2444 }
2445 }
2446 synchronized (mNetworkForNetId) {
2447 mNetIdInUse.delete(nai.network.netId);
2448 }
2449 } else {
2450 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2451 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002452 }
2453 }
2454
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002455 // If this method proves to be too slow then we can maintain a separate
2456 // pendingIntent => NetworkRequestInfo map.
2457 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2458 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2459 Intent intent = pendingIntent.getIntent();
2460 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2461 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2462 if (existingPendingIntent != null &&
2463 existingPendingIntent.getIntent().filterEquals(intent)) {
2464 return entry.getValue();
2465 }
2466 }
2467 return null;
2468 }
2469
2470 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2471 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2472
2473 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2474 if (existingRequest != null) { // remove the existing request.
2475 if (DBG) log("Replacing " + existingRequest.request + " with "
2476 + nri.request + " because their intents matched.");
2477 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2478 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002479 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002480 }
2481
Erik Klineda4bfa82015-04-30 12:58:40 +09002482 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002483 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002484 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002485 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002486 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002487 if (nri.request.networkCapabilities.hasSignalStrength() &&
2488 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2489 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002490 }
2491 }
2492 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002493 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002494 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002495 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002496 }
2497 }
2498
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002499 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2500 int callingUid) {
2501 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2502 if (nri != null) {
2503 handleReleaseNetworkRequest(nri.request, callingUid);
2504 }
2505 }
2506
Paul Jensen99364842014-12-09 11:43:45 -05002507 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002508 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2509 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002510 private boolean unneeded(NetworkAgentInfo nai) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002511 if (!nai.everConnected || nai.isVPN() ||
2512 nai.isLingering() || nai.numRequestNetworkRequests() > 0) {
2513 return false;
2514 }
Paul Jensene0988542015-06-25 15:30:08 -04002515 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2516 // If this Network is already the highest scoring Network for a request, or if
2517 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002518 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002519 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002520 // Note that this catches two important cases:
2521 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2522 // is currently satisfying the request. This is desirable when
2523 // cellular ends up validating but WiFi does not.
2524 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002525 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002526 // WiFi ends up validating and out scoring cellular.
2527 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2528 nai.getCurrentScoreAsValidated())) {
2529 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002530 }
2531 }
Paul Jensene0988542015-06-25 15:30:08 -04002532 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002533 }
2534
Erik Klineacdd6392016-07-07 16:50:58 +09002535 private NetworkRequestInfo getNriForAppRequest(
2536 NetworkRequest request, int callingUid, String requestedOperation) {
2537 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2538
Robert Greenwalt9258c642014-03-26 16:47:06 -07002539 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002540 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002541 log(String.format("UID %d attempted to %s for unowned request %s",
2542 callingUid, requestedOperation, nri));
2543 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002544 }
Erik Klineacdd6392016-07-07 16:50:58 +09002545 }
2546
2547 return nri;
2548 }
2549
2550 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2551 String description, int callbackType) {
2552 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2553 if (nri == null) return;
2554
2555 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2556 // The network that is satisfying this request may have changed since
2557 // the application requested the update.
2558 //
2559 // - If the request is no longer satisfied, don't send any updates.
2560 // - If the request is satisfied by a different network, it is the
2561 // caller's responsibility to check that the Network object in the
2562 // callback matches the network that was returned in the last
2563 // onAvailable() callback for this request.
2564 if (nai == null) return;
2565 callCallbackForRequest(nri, nai, callbackType, 0);
2566 }
2567
2568 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2569 handleRequestCallbackUpdate(request, callingUid,
2570 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2571 }
2572
2573 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2574 handleRequestCallbackUpdate(request, callingUid,
2575 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2576 }
2577
2578 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2579 final NetworkRequestInfo nri = getNriForAppRequest(
2580 request, callingUid, "release NetworkRequest");
2581 if (nri == null) return;
2582
2583 if (VDBG || (DBG && nri.request.isRequest())) log("releasing " + request);
2584 nri.unlinkDeathRecipient();
2585 mNetworkRequests.remove(request);
2586 synchronized (mUidToNetworkRequestCount) {
2587 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2588 if (requests < 1) {
2589 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2590 nri.mUid);
2591 } else if (requests == 1) {
2592 mUidToNetworkRequestCount.removeAt(
2593 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2594 } else {
2595 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2596 }
2597 }
2598 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2599 if (nri.request.isRequest()) {
2600 boolean wasKept = false;
2601 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2602 if (nai != null) {
2603 nai.removeRequest(nri.request.requestId);
2604 if (VDBG) {
2605 log(" Removing from current network " + nai.name() +
2606 ", leaving " + nai.numNetworkRequests() + " requests.");
2607 }
2608 // If there are still lingered requests on this network, don't tear it down,
2609 // but resume lingering instead.
2610 updateLingerState(nai, SystemClock.elapsedRealtime());
2611 if (unneeded(nai)) {
2612 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2613 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002614 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002615 wasKept = true;
2616 }
2617 mNetworkForRequestId.remove(nri.request.requestId);
2618 }
2619
2620 // TODO: remove this code once we know that the Slog.wtf is never hit.
2621 //
2622 // Find all networks that are satisfying this request and remove the request
2623 // from their request lists.
2624 // TODO - it's my understanding that for a request there is only a single
2625 // network satisfying it, so this loop is wasteful
2626 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2627 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2628 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2629 otherNai.name() + ", but mNetworkAgentInfos says " +
2630 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002631 }
2632 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002633
Erik Klineacdd6392016-07-07 16:50:58 +09002634 // Maintain the illusion. When this request arrived, we might have pretended
2635 // that a network connected to serve it, even though the network was already
2636 // connected. Now that this request has gone away, we might have to pretend
2637 // that the network disconnected. LegacyTypeTracker will generate that
2638 // phantom disconnect for this type.
2639 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2640 boolean doRemove = true;
2641 if (wasKept) {
2642 // check if any of the remaining requests for this network are for the
2643 // same legacy type - if so, don't remove the nai
2644 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2645 NetworkRequest otherRequest = nai.requestAt(i);
2646 if (otherRequest.legacyType == nri.request.legacyType &&
2647 otherRequest.isRequest()) {
2648 if (DBG) log(" still have other legacy request - leaving");
2649 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002650 }
2651 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002652 }
2653
Erik Klineacdd6392016-07-07 16:50:58 +09002654 if (doRemove) {
2655 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002656 }
2657 }
Erik Klineacdd6392016-07-07 16:50:58 +09002658
2659 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2660 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2661 nri.request);
2662 }
2663 } else {
2664 // listens don't have a singular affectedNetwork. Check all networks to see
2665 // if this listen request applies and remove it.
2666 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2667 nai.removeRequest(nri.request.requestId);
2668 if (nri.request.networkCapabilities.hasSignalStrength() &&
2669 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2670 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2671 }
2672 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002673 }
Erik Klineacdd6392016-07-07 16:50:58 +09002674 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002675 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002676
Lorenzo Colitti18660282016-07-04 12:55:44 +09002677 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002678 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2679 enforceConnectivityInternalPermission();
2680 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2681 accept ? 1 : 0, always ? 1: 0, network));
2682 }
2683
2684 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2685 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2686 " accept=" + accept + " always=" + always);
2687
2688 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2689 if (nai == null) {
2690 // Nothing to do.
2691 return;
2692 }
2693
2694 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002695 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002696 return;
2697 }
2698
2699 if (!nai.networkMisc.explicitlySelected) {
2700 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2701 }
2702
2703 if (accept != nai.networkMisc.acceptUnvalidated) {
2704 int oldScore = nai.getCurrentScore();
2705 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002706 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002707 sendUpdatedScoreToFactories(nai);
2708 }
2709
2710 if (always) {
2711 nai.asyncChannel.sendMessage(
2712 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2713 }
2714
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002715 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002716 // Tell the NetworkAgent to not automatically reconnect to the network.
2717 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2718 // Teardown the nework.
2719 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002720 }
2721
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002722 }
2723
2724 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002725 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002726 mHandler.sendMessageDelayed(
2727 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2728 PROMPT_UNVALIDATED_DELAY_MS);
2729 }
2730
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002731 private boolean mAvoidBadWifi;
2732
Hugo Benichic8e9e122016-09-14 23:23:08 +00002733 public boolean avoidBadWifi() {
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002734 return mAvoidBadWifi;
2735 }
2736
2737 @VisibleForTesting
2738 public boolean updateAvoidBadWifi() {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002739 // There are two modes: either we always automatically avoid unvalidated wifi, or we show a
2740 // dialog and don't switch to it. The behaviour is controlled by the NETWORK_AVOID_BAD_WIFI
2741 // setting. If the setting has no value, then the value is taken from the config value,
2742 // which can be changed via OEM/carrier overlays.
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002743 //
2744 // The only valid values for NETWORK_AVOID_BAD_WIFI are null and unset. Currently, the unit
2745 // test uses 0 in order to avoid having to mock out fetching the carrier setting.
Hugo Benichic8e9e122016-09-14 23:23:08 +00002746 int defaultAvoidBadWifi =
2747 mContext.getResources().getInteger(R.integer.config_networkAvoidBadWifi);
2748 int avoid = Settings.Global.getInt(mContext.getContentResolver(),
2749 Settings.Global.NETWORK_AVOID_BAD_WIFI, defaultAvoidBadWifi);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002750
2751 boolean prev = mAvoidBadWifi;
2752 mAvoidBadWifi = (avoid == 1);
2753 return mAvoidBadWifi != prev;
Hugo Benichic8e9e122016-09-14 23:23:08 +00002754 }
2755
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002756 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2757 final String action;
2758 switch (type) {
2759 case NO_INTERNET:
2760 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2761 break;
2762 case LOST_INTERNET:
2763 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2764 break;
2765 default:
2766 Slog.wtf(TAG, "Unknown notification type " + type);
2767 return;
2768 }
2769
2770 Intent intent = new Intent(action);
2771 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2772 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2773 intent.setClassName("com.android.settings",
2774 "com.android.settings.wifi.WifiNoInternetDialog");
2775
2776 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2777 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2778 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2779 }
2780
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002781 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002782 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002783 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2784
2785 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2786 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002787 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002788 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002789 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2790 return;
2791 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002792 showValidationNotification(nai, NotificationType.NO_INTERNET);
2793 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002794
Lorenzo Colitti73b209382016-09-15 22:18:09 +09002795 // TODO: Delete this like updateMobileDataAlwaysOn above.
2796 @VisibleForTesting
2797 void updateNetworkAvoidBadWifi() {
2798 mHandler.sendEmptyMessage(EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
2799 }
2800
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002801 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2802 NetworkCapabilities nc = nai.networkCapabilities;
2803 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002804
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002805 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && !avoidBadWifi()) {
2806 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2807 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002808 }
2809
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002810 private class InternalHandler extends Handler {
2811 public InternalHandler(Looper looper) {
2812 super(looper);
2813 }
2814
2815 @Override
2816 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002817 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002818 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002819 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002820 String causedBy = null;
2821 synchronized (ConnectivityService.this) {
2822 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2823 mNetTransitionWakeLock.isHeld()) {
2824 mNetTransitionWakeLock.release();
2825 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002826 } else {
2827 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002828 }
2829 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002830 if (VDBG) {
2831 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2832 log("Failed to find a new network - expiring NetTransition Wakelock");
2833 } else {
2834 log("NetTransition Wakelock (" +
2835 (causedBy == null ? "unknown" : causedBy) +
2836 " cleared because we found a replacement network");
2837 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002838 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002839 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002840 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002841 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002842 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002843 break;
2844 }
Jason Monkdecd2952013-10-10 14:02:51 -04002845 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002846 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002847 break;
2848 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002849 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002850 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2851 break;
2852 }
2853 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2854 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002855 break;
2856 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002857 case EVENT_REGISTER_NETWORK_AGENT: {
2858 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2859 break;
2860 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002861 case EVENT_REGISTER_NETWORK_REQUEST:
2862 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002863 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002864 break;
2865 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002866 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2867 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002868 handleRegisterNetworkRequestWithIntent(msg);
2869 break;
2870 }
2871 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2872 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2873 break;
2874 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002875 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002876 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002877 break;
2878 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002879 case EVENT_SET_ACCEPT_UNVALIDATED: {
2880 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2881 break;
2882 }
2883 case EVENT_PROMPT_UNVALIDATED: {
2884 handlePromptUnvalidated((Network) msg.obj);
2885 break;
2886 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002887 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2888 handleMobileDataAlwaysOn();
2889 break;
2890 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002891 case EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI: {
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002892 if (updateAvoidBadWifi()) {
2893 rematchAllNetworksAndRequests(null, 0);
2894 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002895 break;
2896 }
Erik Klineacdd6392016-07-07 16:50:58 +09002897 case EVENT_REQUEST_LINKPROPERTIES:
2898 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2899 break;
2900 case EVENT_REQUEST_NETCAPABILITIES:
2901 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2902 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002903 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2904 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2905 mKeepaliveTracker.handleStartKeepalive(msg);
2906 break;
2907 }
2908 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2909 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2910 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2911 int slot = msg.arg1;
2912 int reason = msg.arg2;
2913 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2914 break;
2915 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002916 case EVENT_SYSTEM_READY: {
2917 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2918 nai.networkMonitor.systemReady = true;
2919 }
2920 break;
2921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 }
2923 }
2924 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002925
2926 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002927 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002928 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002929 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002930 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002931 final int status = mTethering.tether(iface);
2932 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2933 try {
2934 mPolicyManager.onTetheringChanged(iface, true);
2935 } catch (RemoteException e) {
2936 }
2937 }
2938 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002939 } else {
2940 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2941 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002942 }
2943
2944 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002945 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002946 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002947 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002948
2949 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002950 final int status = mTethering.untether(iface);
2951 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2952 try {
2953 mPolicyManager.onTetheringChanged(iface, false);
2954 } catch (RemoteException e) {
2955 }
2956 }
2957 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002958 } else {
2959 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2960 }
2961 }
2962
2963 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002964 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002965 public int getLastTetherError(String iface) {
2966 enforceTetherAccessPermission();
2967
2968 if (isTetheringSupported()) {
2969 return mTethering.getLastTetherError(iface);
2970 } else {
2971 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2972 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002973 }
2974
2975 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002976 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002977 public String[] getTetherableUsbRegexs() {
2978 enforceTetherAccessPermission();
2979 if (isTetheringSupported()) {
2980 return mTethering.getTetherableUsbRegexs();
2981 } else {
2982 return new String[0];
2983 }
2984 }
2985
Lorenzo Colitti18660282016-07-04 12:55:44 +09002986 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002987 public String[] getTetherableWifiRegexs() {
2988 enforceTetherAccessPermission();
2989 if (isTetheringSupported()) {
2990 return mTethering.getTetherableWifiRegexs();
2991 } else {
2992 return new String[0];
2993 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002994 }
2995
Lorenzo Colitti18660282016-07-04 12:55:44 +09002996 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002997 public String[] getTetherableBluetoothRegexs() {
2998 enforceTetherAccessPermission();
2999 if (isTetheringSupported()) {
3000 return mTethering.getTetherableBluetoothRegexs();
3001 } else {
3002 return new String[0];
3003 }
3004 }
3005
Lorenzo Colitti18660282016-07-04 12:55:44 +09003006 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003007 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003008 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003009 if (isTetheringSupported()) {
3010 return mTethering.setUsbTethering(enable);
3011 } else {
3012 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3013 }
3014 }
3015
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003016 // TODO - move iface listing, queries, etc to new module
3017 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003018 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003019 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003020 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003021 return mTethering.getTetherableIfaces();
3022 }
3023
Lorenzo Colitti18660282016-07-04 12:55:44 +09003024 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003025 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003026 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003027 return mTethering.getTetheredIfaces();
3028 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003029
Lorenzo Colitti18660282016-07-04 12:55:44 +09003030 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003031 public String[] getTetheringErroredIfaces() {
3032 enforceTetherAccessPermission();
3033 return mTethering.getErroredIfaces();
3034 }
3035
Lorenzo Colitti18660282016-07-04 12:55:44 +09003036 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003037 public String[] getTetheredDhcpRanges() {
3038 enforceConnectivityInternalPermission();
3039 return mTethering.getTetheredDhcpRanges();
3040 }
3041
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003042 // if ro.tether.denied = true we default to no tethering
3043 // gservices could set the secure setting to 1 though to enable it on a build where it
3044 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003045 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003046 public boolean isTetheringSupported() {
3047 enforceTetherAccessPermission();
3048 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003049 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003050 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3051 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003052 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
3053 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003054 mTethering.getTetherableWifiRegexs().length != 0 ||
3055 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3056 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003057 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003058
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003059 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003060 public void startTethering(int type, ResultReceiver receiver,
3061 boolean showProvisioningUi) {
3062 ConnectivityManager.enforceTetherChangePermission(mContext);
3063 if (!isTetheringSupported()) {
3064 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3065 return;
3066 }
3067 mTethering.startTethering(type, receiver, showProvisioningUi);
3068 }
3069
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003070 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003071 public void stopTethering(int type) {
3072 ConnectivityManager.enforceTetherChangePermission(mContext);
3073 mTethering.stopTethering(type);
3074 }
3075
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003076 // Called when we lose the default network and have no replacement yet.
3077 // This will automatically be cleared after X seconds or a new default network
3078 // becomes CONNECTED, whichever happens first. The timer is started by the
3079 // first caller and not restarted by subsequent callers.
3080 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003081 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003082 synchronized (this) {
3083 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003084 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003085 mNetTransitionWakeLock.acquire();
3086 mNetTransitionWakeLockCausedBy = forWhom;
3087 }
3088 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003089 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003090 mNetTransitionWakeLockTimeout);
3091 return;
3092 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003093
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003094 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003095 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003096 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003097 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003098 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003099 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003100 }
3101
Lorenzo Colitti18660282016-07-04 12:55:44 +09003102 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003103 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003104 enforceAccessPermission();
3105 enforceInternetPermission();
3106
Paul Jensenbfd17b72015-04-07 12:43:13 -04003107 NetworkAgentInfo nai;
3108 if (network == null) {
3109 nai = getDefaultNetwork();
3110 } else {
3111 nai = getNetworkAgentInfoForNetwork(network);
3112 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003113 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3114 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3115 return;
3116 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003117 // Revalidate if the app report does not match our current validated state.
3118 if (hasConnectivity == nai.lastValidated) return;
3119 final int uid = Binder.getCallingUid();
3120 if (DBG) {
3121 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3122 ") by " + uid);
3123 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003124 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003125 // Validating a network that has not yet connected could result in a call to
3126 // rematchNetworkAndRequests() which is not meant to work on such networks.
3127 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003128
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003129 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003130
3131 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3132 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003133 }
3134
Paul Jensencee9b512015-05-06 07:32:40 -04003135 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003136 // this information is already available as a world read/writable jvm property
3137 // so this API change wouldn't have a benifit. It also breaks the passing
3138 // of proxy info to all the JVMs.
3139 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003140 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003141 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003142 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3143 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003144 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003145 }
3146
Lorenzo Colitti18660282016-07-04 12:55:44 +09003147 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003148 public ProxyInfo getProxyForNetwork(Network network) {
3149 if (network == null) return getDefaultProxy();
3150 final ProxyInfo globalProxy = getGlobalProxy();
3151 if (globalProxy != null) return globalProxy;
3152 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3153 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3154 // caller may not have.
3155 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3156 if (nai == null) return null;
3157 synchronized (nai) {
3158 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3159 if (proxyInfo == null) return null;
3160 return new ProxyInfo(proxyInfo);
3161 }
3162 }
3163
Paul Jensene0bef712014-12-10 15:12:18 -05003164 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3165 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3166 // proxy is null then there is no proxy in place).
3167 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3168 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3169 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3170 proxy = null;
3171 }
3172 return proxy;
3173 }
3174
3175 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3176 // better for determining if a new proxy broadcast is necessary:
3177 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3178 // avoid unnecessary broadcasts.
3179 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3180 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3181 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3182 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3183 // all set.
3184 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3185 a = canonicalizeProxyInfo(a);
3186 b = canonicalizeProxyInfo(b);
3187 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3188 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3189 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3190 }
3191
Jason Monk207900c2014-04-25 15:00:09 -04003192 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003193 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003194
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003195 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003196 if (proxyProperties == mGlobalProxy) return;
3197 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3198 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3199
3200 String host = "";
3201 int port = 0;
3202 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003203 String pacFileUrl = "";
3204 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003205 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003206 if (!proxyProperties.isValid()) {
3207 if (DBG)
3208 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3209 return;
3210 }
Jason Monk207900c2014-04-25 15:00:09 -04003211 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003212 host = mGlobalProxy.getHost();
3213 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003214 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003215 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003216 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003217 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003218 } else {
3219 mGlobalProxy = null;
3220 }
3221 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003222 final long token = Binder.clearCallingIdentity();
3223 try {
3224 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3225 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3226 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3227 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003228 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003229 } finally {
3230 Binder.restoreCallingIdentity(token);
3231 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003232
Jason Monkcf0f97a2014-10-02 15:39:38 -04003233 if (mGlobalProxy == null) {
3234 proxyProperties = mDefaultProxy;
3235 }
3236 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003237 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003238 }
3239
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003240 private void loadGlobalProxy() {
3241 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003242 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3243 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3244 String exclList = Settings.Global.getString(res,
3245 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003246 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3247 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003248 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003249 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003250 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003251 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003252 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003253 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003254 if (!proxyProperties.isValid()) {
3255 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3256 return;
3257 }
3258
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003259 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003260 mGlobalProxy = proxyProperties;
3261 }
3262 }
3263 }
3264
Jason Monk207900c2014-04-25 15:00:09 -04003265 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003266 // this information is already available as a world read/writable jvm property
3267 // so this API change wouldn't have a benifit. It also breaks the passing
3268 // of proxy info to all the JVMs.
3269 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003270 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003271 return mGlobalProxy;
3272 }
3273 }
3274
Jason Monk207900c2014-04-25 15:00:09 -04003275 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003276 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003277 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003278 proxy = null;
3279 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003280 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003281 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003282 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003283 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003284 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3285 return;
3286 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003287
3288 // This call could be coming from the PacManager, containing the port of the local
3289 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3290 // global (to get the correct local port), and send a broadcast.
3291 // TODO: Switch PacManager to have its own message to send back rather than
3292 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003293 if ((mGlobalProxy != null) && (proxy != null)
3294 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003295 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3296 mGlobalProxy = proxy;
3297 sendProxyBroadcast(mGlobalProxy);
3298 return;
3299 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003300 mDefaultProxy = proxy;
3301
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003302 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003303 if (!mDefaultProxyDisabled) {
3304 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003305 }
3306 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003307 }
3308
Paul Jensene0bef712014-12-10 15:12:18 -05003309 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3310 // This method gets called when any network changes proxy, but the broadcast only ever contains
3311 // the default proxy (even if it hasn't changed).
3312 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3313 // world where an app might be bound to a non-default network.
3314 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3315 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3316 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3317
3318 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3319 sendProxyBroadcast(getDefaultProxy());
3320 }
3321 }
3322
Robert Greenwalt434203a2010-10-11 16:00:27 -07003323 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003324 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3325 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003326 if (!TextUtils.isEmpty(proxy)) {
3327 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003328 if (data.length == 0) {
3329 return;
3330 }
3331
Robert Greenwalt434203a2010-10-11 16:00:27 -07003332 String proxyHost = data[0];
3333 int proxyPort = 8080;
3334 if (data.length > 1) {
3335 try {
3336 proxyPort = Integer.parseInt(data[1]);
3337 } catch (NumberFormatException e) {
3338 return;
3339 }
3340 }
Jason Monk207900c2014-04-25 15:00:09 -04003341 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003342 setGlobalProxy(p);
3343 }
3344 }
3345
Jason Monk207900c2014-04-25 15:00:09 -04003346 private void sendProxyBroadcast(ProxyInfo proxy) {
3347 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003348 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003349 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003350 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003351 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3352 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003353 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003354 final long ident = Binder.clearCallingIdentity();
3355 try {
3356 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3357 } finally {
3358 Binder.restoreCallingIdentity(ident);
3359 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003360 }
3361
3362 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003363 final private HashMap<Uri, Integer> mUriEventMap;
3364 final private Context mContext;
3365 final private Handler mHandler;
3366
3367 SettingsObserver(Context context, Handler handler) {
3368 super(null);
3369 mUriEventMap = new HashMap<Uri, Integer>();
3370 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003371 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003372 }
3373
Erik Klineda4bfa82015-04-30 12:58:40 +09003374 void observe(Uri uri, int what) {
3375 mUriEventMap.put(uri, what);
3376 final ContentResolver resolver = mContext.getContentResolver();
3377 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003378 }
3379
3380 @Override
3381 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003382 Slog.wtf(TAG, "Should never be reached.");
3383 }
3384
3385 @Override
3386 public void onChange(boolean selfChange, Uri uri) {
3387 final Integer what = mUriEventMap.get(uri);
3388 if (what != null) {
3389 mHandler.obtainMessage(what.intValue()).sendToTarget();
3390 } else {
3391 loge("No matching event to send for URI=" + uri);
3392 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003393 }
3394 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003395
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003396 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003397 Slog.d(TAG, s);
3398 }
3399
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003400 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003401 Slog.e(TAG, s);
3402 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003403
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003404 private static <T> T checkNotNull(T value, String message) {
3405 if (value == null) {
3406 throw new NullPointerException(message);
3407 }
3408 return value;
3409 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003410
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003411 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003412 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003413 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3414 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3415 *
3416 * @param oldPackage Package name of the application which currently controls VPN, which will
3417 * be replaced. If there is no such application, this should should either be
3418 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3419 * @param newPackage Package name of the application which should gain control of VPN, or
3420 * {@code null} to disable.
3421 * @param userId User for whom to prepare the new VPN.
3422 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003423 * @hide
3424 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003425 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003426 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3427 int userId) {
3428 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003429 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003430
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003431 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003432 Vpn vpn = mVpns.get(userId);
3433 if (vpn != null) {
3434 return vpn.prepare(oldPackage, newPackage);
3435 } else {
3436 return false;
3437 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003438 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003439 }
3440
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003441 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003442 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3443 * This method is used by system-privileged apps.
3444 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3445 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3446 *
3447 * @param packageName The package for which authorization state should change.
3448 * @param userId User for whom {@code packageName} is installed.
3449 * @param authorized {@code true} if this app should be able to start a VPN connection without
3450 * explicit user approval, {@code false} if not.
3451 *
Jeff Davidson05542602014-08-11 14:07:27 -07003452 * @hide
3453 */
3454 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003455 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3456 enforceCrossUserPermission(userId);
3457
Jeff Davidson05542602014-08-11 14:07:27 -07003458 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003459 Vpn vpn = mVpns.get(userId);
3460 if (vpn != null) {
3461 vpn.setPackageAuthorization(packageName, authorized);
3462 }
Jeff Davidson05542602014-08-11 14:07:27 -07003463 }
3464 }
3465
3466 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003467 * Configure a TUN interface and return its file descriptor. Parameters
3468 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003469 * and not available in ConnectivityManager. Permissions are checked in
3470 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003471 * @hide
3472 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003473 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003474 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003475 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003476 int user = UserHandle.getUserId(Binder.getCallingUid());
3477 synchronized(mVpns) {
3478 return mVpns.get(user).establish(config);
3479 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003480 }
3481
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003482 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003483 * Start legacy VPN, controlling native daemons as needed. Creates a
3484 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003485 */
3486 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003487 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003488 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003489 final LinkProperties egress = getActiveLinkProperties();
3490 if (egress == null) {
3491 throw new IllegalStateException("Missing active network connection");
3492 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003493 int user = UserHandle.getUserId(Binder.getCallingUid());
3494 synchronized(mVpns) {
3495 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3496 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003497 }
3498
3499 /**
3500 * Return the information of the ongoing legacy VPN. This method is used
3501 * by VpnSettings and not available in ConnectivityManager. Permissions
3502 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003503 */
3504 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003505 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3506 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003507
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003508 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003509 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003510 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003511 }
3512
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003513 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003514 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3515 * and not available in ConnectivityManager.
3516 */
3517 @Override
3518 public VpnInfo[] getAllVpnInfo() {
3519 enforceConnectivityInternalPermission();
3520 if (mLockdownEnabled) {
3521 return new VpnInfo[0];
3522 }
3523
3524 synchronized(mVpns) {
3525 List<VpnInfo> infoList = new ArrayList<>();
3526 for (int i = 0; i < mVpns.size(); i++) {
3527 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3528 if (info != null) {
3529 infoList.add(info);
3530 }
3531 }
3532 return infoList.toArray(new VpnInfo[infoList.size()]);
3533 }
3534 }
3535
3536 /**
3537 * @return VPN information for accounting, or null if we can't retrieve all required
3538 * information, e.g primary underlying iface.
3539 */
3540 @Nullable
3541 private VpnInfo createVpnInfo(Vpn vpn) {
3542 VpnInfo info = vpn.getVpnInfo();
3543 if (info == null) {
3544 return null;
3545 }
3546 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3547 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3548 // the underlyingNetworks list.
3549 if (underlyingNetworks == null) {
3550 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3551 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3552 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3553 }
3554 } else if (underlyingNetworks.length > 0) {
3555 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3556 if (linkProperties != null) {
3557 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3558 }
3559 }
3560 return info.primaryUnderlyingIface == null ? null : info;
3561 }
3562
3563 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003564 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3565 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003566 * Permissions are checked in Vpn class.
3567 * @hide
3568 */
3569 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003570 public VpnConfig getVpnConfig(int userId) {
3571 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003572 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003573 Vpn vpn = mVpns.get(userId);
3574 if (vpn != null) {
3575 return vpn.getVpnConfig();
3576 } else {
3577 return null;
3578 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003579 }
3580 }
3581
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003582 @Override
3583 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003584 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3585 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3586 return false;
3587 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003588
3589 // Tear down existing lockdown if profile was removed
3590 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3591 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003592 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3593 final VpnProfile profile = VpnProfile.decode(
3594 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003595 if (profile == null) {
3596 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3597 setLockdownTracker(null);
3598 return true;
3599 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003600 int user = UserHandle.getUserId(Binder.getCallingUid());
3601 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003602 Vpn vpn = mVpns.get(user);
3603 if (vpn == null) {
3604 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3605 return false;
3606 }
3607 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003608 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003609 } else {
3610 setLockdownTracker(null);
3611 }
3612
3613 return true;
3614 }
3615
3616 /**
3617 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3618 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3619 */
3620 private void setLockdownTracker(LockdownVpnTracker tracker) {
3621 // Shutdown any existing tracker
3622 final LockdownVpnTracker existing = mLockdownTracker;
3623 mLockdownTracker = null;
3624 if (existing != null) {
3625 existing.shutdown();
3626 }
3627
3628 try {
3629 if (tracker != null) {
3630 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003631 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003632 mLockdownTracker = tracker;
3633 mLockdownTracker.init();
3634 } else {
3635 mNetd.setFirewallEnabled(false);
3636 }
3637 } catch (RemoteException e) {
3638 // ignored; NMS lives inside system_server
3639 }
3640 }
3641
3642 private void throwIfLockdownEnabled() {
3643 if (mLockdownEnabled) {
3644 throw new IllegalStateException("Unavailable in lockdown mode");
3645 }
3646 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003647
Robin Lee244ce8e2016-01-05 18:03:46 +00003648 /**
Robin Lee17e61832016-05-09 13:46:28 +01003649 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3650 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003651 *
Robin Lee17e61832016-05-09 13:46:28 +01003652 * @return {@code true} if the service was started, the service was already connected, or there
3653 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003654 */
Robin Lee17e61832016-05-09 13:46:28 +01003655 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003656 synchronized (mVpns) {
3657 Vpn vpn = mVpns.get(userId);
3658 if (vpn == null) {
3659 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3660 // exists already.
3661 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3662 return false;
3663 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003664
Robin Lee812800c2016-05-13 15:38:08 +01003665 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003666 }
3667 }
3668
3669 @Override
Robin Leedc679712016-05-03 13:23:03 +01003670 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003671 enforceConnectivityInternalPermission();
3672 enforceCrossUserPermission(userId);
3673
3674 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3675 if (LockdownVpnTracker.isEnabled()) {
3676 return false;
3677 }
3678
Robin Lee244ce8e2016-01-05 18:03:46 +00003679 synchronized (mVpns) {
3680 Vpn vpn = mVpns.get(userId);
3681 if (vpn == null) {
3682 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3683 return false;
3684 }
Robin Lee17e61832016-05-09 13:46:28 +01003685 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003686 return false;
3687 }
Robin Lee17e61832016-05-09 13:46:28 +01003688 if (!startAlwaysOnVpn(userId)) {
3689 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003690 return false;
3691 }
Robin Lee17e61832016-05-09 13:46:28 +01003692
Robin Lee812800c2016-05-13 15:38:08 +01003693 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003694 }
3695 return true;
3696 }
3697
3698 @Override
3699 public String getAlwaysOnVpnPackage(int userId) {
3700 enforceConnectivityInternalPermission();
3701 enforceCrossUserPermission(userId);
3702
3703 synchronized (mVpns) {
3704 Vpn vpn = mVpns.get(userId);
3705 if (vpn == null) {
3706 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3707 return null;
3708 }
3709 return vpn.getAlwaysOnPackage();
3710 }
3711 }
3712
Wink Savilleab9321d2013-06-29 21:10:57 -07003713 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003714 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003715 // TODO: Remove? Any reason to trigger a provisioning check?
3716 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003717 }
3718
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003719 /** Location to an updatable file listing carrier provisioning urls.
3720 * An example:
3721 *
3722 * <?xml version="1.0" encoding="utf-8"?>
3723 * <provisioningUrls>
3724 * <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 -07003725 * </provisioningUrls>
3726 */
3727 private static final String PROVISIONING_URL_PATH =
3728 "/data/misc/radio/provisioning_urls.xml";
3729 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003730
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003731 /** XML tag for root element. */
3732 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3733 /** XML tag for individual url */
3734 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003735 /** XML attribute for mcc */
3736 private static final String ATTR_MCC = "mcc";
3737 /** XML attribute for mnc */
3738 private static final String ATTR_MNC = "mnc";
3739
Paul Jensen434dde82015-06-11 09:43:30 -04003740 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003741 FileReader fileReader = null;
3742 XmlPullParser parser = null;
3743 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003744
3745 try {
3746 fileReader = new FileReader(mProvisioningUrlFile);
3747 parser = Xml.newPullParser();
3748 parser.setInput(fileReader);
3749 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3750
3751 while (true) {
3752 XmlUtils.nextElement(parser);
3753
3754 String element = parser.getName();
3755 if (element == null) break;
3756
Paul Jensen434dde82015-06-11 09:43:30 -04003757 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003758 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3759 try {
3760 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3761 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3762 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3763 parser.next();
3764 if (parser.getEventType() == XmlPullParser.TEXT) {
3765 return parser.getText();
3766 }
3767 }
3768 }
3769 } catch (NumberFormatException e) {
3770 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3771 }
3772 }
3773 }
3774 return null;
3775 } catch (FileNotFoundException e) {
3776 loge("Carrier Provisioning Urls file not found");
3777 } catch (XmlPullParserException e) {
3778 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3779 } catch (IOException e) {
3780 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3781 } finally {
3782 if (fileReader != null) {
3783 try {
3784 fileReader.close();
3785 } catch (IOException e) {}
3786 }
3787 }
3788 return null;
3789 }
3790
Wink Saville42d4f082013-07-20 20:31:59 -07003791 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003792 public String getMobileProvisioningUrl() {
3793 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003794 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003795 if (TextUtils.isEmpty(url)) {
3796 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003797 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003798 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003799 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003800 }
Wink Saville8cf35602013-07-10 23:00:07 -07003801 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003802 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003803 String phoneNumber = mTelephonyManager.getLine1Number();
3804 if (TextUtils.isEmpty(phoneNumber)) {
3805 phoneNumber = "0000000000";
3806 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003807 url = String.format(url,
3808 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3809 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003810 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003811 }
3812
Wink Savilleab9321d2013-06-29 21:10:57 -07003813 return url;
3814 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003815
Wink Saville948282b2013-08-29 08:55:16 -07003816 @Override
3817 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003818 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003819 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003820 final long ident = Binder.clearCallingIdentity();
3821 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003822 // Concatenate the range of types onto the range of NetIDs.
3823 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3824 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003825 } finally {
3826 Binder.restoreCallingIdentity(ident);
3827 }
Wink Saville948282b2013-08-29 08:55:16 -07003828 }
Wink Saville7788c612013-08-29 14:57:08 -07003829
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003830 @Override
3831 public void setAirplaneMode(boolean enable) {
3832 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003833 final long ident = Binder.clearCallingIdentity();
3834 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003835 final ContentResolver cr = mContext.getContentResolver();
3836 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3837 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3838 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003839 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003840 } finally {
3841 Binder.restoreCallingIdentity(ident);
3842 }
3843 }
3844
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003845 private void onUserStart(int userId) {
3846 synchronized(mVpns) {
3847 Vpn userVpn = mVpns.get(userId);
3848 if (userVpn != null) {
3849 loge("Starting user already has a VPN");
3850 return;
3851 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003852 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003853 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003854
3855 final ContentResolver cr = mContext.getContentResolver();
3856 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3857 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3858 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3859 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3860 if (alwaysOnPackage != null) {
3861 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3862 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003863 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003864 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3865 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003866 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003867 }
3868
3869 private void onUserStop(int userId) {
3870 synchronized(mVpns) {
3871 Vpn userVpn = mVpns.get(userId);
3872 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003873 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003874 return;
3875 }
Robin Lee17e61832016-05-09 13:46:28 +01003876 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003877 mVpns.delete(userId);
3878 }
3879 }
3880
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003881 private void onUserAdded(int userId) {
3882 synchronized(mVpns) {
3883 final int vpnsSize = mVpns.size();
3884 for (int i = 0; i < vpnsSize; i++) {
3885 Vpn vpn = mVpns.valueAt(i);
3886 vpn.onUserAdded(userId);
3887 }
3888 }
3889 }
3890
3891 private void onUserRemoved(int userId) {
3892 synchronized(mVpns) {
3893 final int vpnsSize = mVpns.size();
3894 for (int i = 0; i < vpnsSize; i++) {
3895 Vpn vpn = mVpns.valueAt(i);
3896 vpn.onUserRemoved(userId);
3897 }
3898 }
3899 }
3900
Robin Lee89e7a692016-02-29 14:38:17 +00003901 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003902 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3903 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3904 updateLockdownVpn();
3905 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003906 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003907 }
3908 }
3909
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003910 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3911 @Override
3912 public void onReceive(Context context, Intent intent) {
3913 final String action = intent.getAction();
3914 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3915 if (userId == UserHandle.USER_NULL) return;
3916
Robin Lee323f29d2016-05-04 16:38:06 +01003917 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003918 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003919 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003920 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003921 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3922 onUserAdded(userId);
3923 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3924 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003925 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3926 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003927 }
3928 }
3929 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003930
Robert Greenwalta67be032014-05-16 15:49:14 -07003931 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3932 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003933 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3934 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003935
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003936 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3937 // Map from UID to number of NetworkRequests that UID has filed.
3938 @GuardedBy("mUidToNetworkRequestCount")
3939 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3940
Robert Greenwalta67be032014-05-16 15:49:14 -07003941 private static class NetworkFactoryInfo {
3942 public final String name;
3943 public final Messenger messenger;
3944 public final AsyncChannel asyncChannel;
3945
3946 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3947 this.name = name;
3948 this.messenger = messenger;
3949 this.asyncChannel = asyncChannel;
3950 }
3951 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003952
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003953 private void ensureNetworkRequestHasType(NetworkRequest request) {
3954 if (request.type == NetworkRequest.Type.NONE) {
3955 throw new IllegalArgumentException(
3956 "All NetworkRequests in ConnectivityService must have a type");
3957 }
3958 }
3959
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003960 /**
3961 * Tracks info about the requester.
3962 * Also used to notice when the calling process dies so we can self-expire
3963 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003964 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003965 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003966 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003967 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003968 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003969 final int mPid;
3970 final int mUid;
3971 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003972
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003973 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003974 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003975 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003976 mPendingIntent = pi;
3977 messenger = null;
3978 mBinder = null;
3979 mPid = getCallingPid();
3980 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003981 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003982 }
3983
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003984 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003985 super();
3986 messenger = m;
3987 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003988 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003989 mBinder = binder;
3990 mPid = getCallingPid();
3991 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003992 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003993 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003994
3995 try {
3996 mBinder.linkToDeath(this, 0);
3997 } catch (RemoteException e) {
3998 binderDied();
3999 }
4000 }
4001
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004002 private void enforceRequestCountLimit() {
4003 synchronized (mUidToNetworkRequestCount) {
4004 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4005 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4006 throw new IllegalArgumentException("Too many NetworkRequests filed");
4007 }
4008 mUidToNetworkRequestCount.put(mUid, networkRequests);
4009 }
4010 }
4011
Robert Greenwalt9258c642014-03-26 16:47:06 -07004012 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004013 if (mBinder != null) {
4014 mBinder.unlinkToDeath(this, 0);
4015 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004016 }
4017
4018 public void binderDied() {
4019 log("ConnectivityService NetworkRequestInfo binderDied(" +
4020 request + ", " + mBinder + ")");
4021 releaseNetworkRequest(request);
4022 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004023
4024 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004025 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004026 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004027 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004028 }
4029
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004030 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4031 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4032 if (badCapability != null) {
4033 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004034 }
4035 }
4036
Erik Kline9d598e12015-07-13 16:37:51 +09004037 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004038 final SortedSet<Integer> thresholds = new TreeSet();
4039 synchronized (nai) {
4040 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4041 if (nri.request.networkCapabilities.hasSignalStrength() &&
4042 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4043 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4044 }
4045 }
4046 }
Erik Kline9d598e12015-07-13 16:37:51 +09004047 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004048 }
4049
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004050 private void updateSignalStrengthThresholds(
4051 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4052 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004053 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004054 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4055
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004056 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004057 String detail;
4058 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4059 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4060 } else {
4061 detail = reason;
4062 }
4063 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4064 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4065 }
4066
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004067 nai.asyncChannel.sendMessage(
4068 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004069 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004070 }
4071
Robert Greenwalt9258c642014-03-26 16:47:06 -07004072 @Override
4073 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004074 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004075 final NetworkRequest.Type type = (networkCapabilities == null)
4076 ? NetworkRequest.Type.TRACK_DEFAULT
4077 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004078 // If the requested networkCapabilities is null, take them instead from
4079 // the default network request. This allows callers to keep track of
4080 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004081 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004082 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4083 enforceAccessPermission();
4084 } else {
4085 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4086 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004087 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4088 // of the app when the request is filed, but we never change the request if the app
4089 // changes network state. http://b/29964605
4090 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004091 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004092 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004093
Robert Greenwalt6078b502014-06-11 16:05:07 -07004094 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004095 throw new IllegalArgumentException("Bad timeout specified");
4096 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004097
Etan Cohenddb9ef02015-11-18 10:56:15 -08004098 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4099 .equals(networkCapabilities.getNetworkSpecifier())) {
4100 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4101 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4102 }
4103
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004104 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004105 nextNetworkRequestId(), type);
4106 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004107 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004108
4109 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004110 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004111 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004112 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004113 }
4114 return networkRequest;
4115 }
4116
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004117 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004118 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004119 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004120 } else {
4121 enforceChangePermission();
4122 }
4123 }
4124
fenglub15e72b2015-03-20 11:29:56 -07004125 @Override
fengludb571472015-04-21 17:12:05 -07004126 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004127 enforceAccessPermission();
4128 NetworkAgentInfo nai = null;
4129 if (network == null) {
4130 return false;
4131 }
4132 synchronized (mNetworkForNetId) {
4133 nai = mNetworkForNetId.get(network.netId);
4134 }
4135 if (nai != null) {
4136 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4137 return true;
4138 }
4139 return false;
4140 }
4141
Felipe Lemeee27cab2016-06-20 16:36:29 -07004142 private boolean isSystem(int uid) {
4143 return uid < Process.FIRST_APPLICATION_UID;
4144 }
fenglub15e72b2015-03-20 11:29:56 -07004145
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004146 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004147 final int uid = Binder.getCallingUid();
4148 if (isSystem(uid)) {
4149 return;
4150 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004151 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004152 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004153 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004154 synchronized(mRulesLock) {
4155 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4156 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004157 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4158 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004159 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004160 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004161 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004162 }
4163 }
4164 }
4165
Robert Greenwalt9258c642014-03-26 16:47:06 -07004166 @Override
4167 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4168 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004169 checkNotNull(operation, "PendingIntent cannot be null.");
4170 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4171 enforceNetworkRequestPermissions(networkCapabilities);
4172 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004173 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004174
4175 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004176 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4177 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004178 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004179 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4180 nri));
4181 return networkRequest;
4182 }
4183
Jeremy Joslin79294842014-12-03 17:15:28 -08004184 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4185 mHandler.sendMessageDelayed(
4186 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4187 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4188 }
4189
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004190 @Override
4191 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004192 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004193 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4194 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004195 }
4196
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004197 // In order to implement the compatibility measure for pre-M apps that call
4198 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4199 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4200 // This ensures it has permission to do so.
4201 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4202 if (nc == null) {
4203 return false;
4204 }
4205 int[] transportTypes = nc.getTransportTypes();
4206 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4207 return false;
4208 }
4209 try {
4210 mContext.enforceCallingOrSelfPermission(
4211 android.Manifest.permission.ACCESS_WIFI_STATE,
4212 "ConnectivityService");
4213 } catch (SecurityException e) {
4214 return false;
4215 }
4216 return true;
4217 }
4218
Robert Greenwalt9258c642014-03-26 16:47:06 -07004219 @Override
4220 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4221 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004222 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4223 enforceAccessPermission();
4224 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004225
Erik Kline7523eb32015-07-09 18:24:03 +09004226 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004227 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4228 NetworkRequest.Type.LISTEN);
4229 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004230 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004231
4232 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4233 return networkRequest;
4234 }
4235
4236 @Override
4237 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4238 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004239 checkNotNull(operation, "PendingIntent cannot be null.");
4240 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4241 enforceAccessPermission();
4242 }
4243
Erik Kline7523eb32015-07-09 18:24:03 +09004244 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004245 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4246 NetworkRequest.Type.LISTEN);
4247 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004248 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004249
4250 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004251 }
4252
4253 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004254 public void requestLinkProperties(NetworkRequest networkRequest) {
4255 ensureNetworkRequestHasType(networkRequest);
4256 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4257 mHandler.sendMessage(mHandler.obtainMessage(
4258 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4259 }
4260
4261 @Override
4262 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4263 ensureNetworkRequestHasType(networkRequest);
4264 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4265 mHandler.sendMessage(mHandler.obtainMessage(
4266 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4267 }
4268
4269 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004270 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004271 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004272 mHandler.sendMessage(mHandler.obtainMessage(
4273 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004274 }
4275
4276 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004277 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004278 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004279 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4280 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004281 }
4282
Robert Greenwalta67be032014-05-16 15:49:14 -07004283 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004284 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004285 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4286 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4287 }
4288
4289 @Override
4290 public void unregisterNetworkFactory(Messenger messenger) {
4291 enforceConnectivityInternalPermission();
4292 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4293 }
4294
4295 private void handleUnregisterNetworkFactory(Messenger messenger) {
4296 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4297 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004298 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004299 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004300 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004301 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004302 }
4303
Robert Greenwalt7b816022014-04-18 15:25:25 -07004304 /**
4305 * NetworkAgentInfo supporting a request by requestId.
4306 * These have already been vetted (their Capabilities satisfy the request)
4307 * and the are the highest scored network available.
4308 * the are keyed off the Requests requestId.
4309 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004310 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004311 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4312 new SparseArray<NetworkAgentInfo>();
4313
Paul Jensen31a94f42015-02-13 14:18:39 -05004314 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4315 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004316 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4317 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004318 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4319 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4320 // there may not be a strict 1:1 correlation between the two.
4321 @GuardedBy("mNetworkForNetId")
4322 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004323
Robert Greenwalt7b816022014-04-18 15:25:25 -07004324 // NetworkAgentInfo keyed off its connecting messenger
4325 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004326 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004327 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4328 new HashMap<Messenger, NetworkAgentInfo>();
4329
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004330 @GuardedBy("mBlockedAppUids")
4331 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4332
Paul Jensen2c311d62014-11-17 12:34:51 -05004333 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004334 private final NetworkRequest mDefaultRequest;
4335
Erik Klineda4bfa82015-04-30 12:58:40 +09004336 // Request used to optionally keep mobile data active even when higher
4337 // priority networks like Wi-Fi are active.
4338 private final NetworkRequest mDefaultMobileDataRequest;
4339
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004340 private NetworkAgentInfo getDefaultNetwork() {
4341 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4342 }
4343
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004344 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004345 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004346 }
4347
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004348 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4349 return nri.request.requestId == mDefaultRequest.requestId;
4350 }
4351
Paul Jensen31a94f42015-02-13 14:18:39 -05004352 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004353 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004354 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004355 enforceConnectivityInternalPermission();
4356
Paul Jensen2c311d62014-11-17 12:34:51 -05004357 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4358 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004359 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004360 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4361 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004362 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004363 synchronized (this) {
4364 nai.networkMonitor.systemReady = mSystemReady;
4365 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004366 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4367 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004368 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004369 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004370 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004371 }
4372
4373 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4374 if (VDBG) log("Got NetworkAgent Messenger");
4375 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004376 synchronized (mNetworkForNetId) {
4377 mNetworkForNetId.put(na.network.netId, na);
4378 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004379 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4380 NetworkInfo networkInfo = na.networkInfo;
4381 na.networkInfo = null;
4382 updateNetworkInfo(na, networkInfo);
4383 }
4384
4385 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4386 LinkProperties newLp = networkAgent.linkProperties;
4387 int netId = networkAgent.network.netId;
4388
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004389 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4390 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004391 if (networkAgent.clatd != null) {
4392 networkAgent.clatd.fixupLinkProperties(oldLp);
4393 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004394
Paul Jensen992f2522014-04-28 10:33:11 -04004395 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004396 updateMtu(newLp, oldLp);
4397 // TODO - figure out what to do for clat
4398// for (LinkProperties lp : newLp.getStackedLinks()) {
4399// updateMtu(lp, null);
4400// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004401 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004402
Erik Kline94887872016-04-05 13:30:49 +09004403 updateRoutes(newLp, oldLp, netId);
4404 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004405
Paul Jensen3b759822014-05-13 11:44:01 -04004406 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004407 if (isDefaultNetwork(networkAgent)) {
4408 handleApplyDefaultProxy(newLp.getHttpProxy());
4409 } else {
4410 updateProxy(newLp, oldLp, networkAgent);
4411 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004412 // TODO - move this check to cover the whole function
4413 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004414 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004415 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4416 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004417
4418 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004419 }
4420
Lorenzo Colitti95439462014-10-09 13:44:48 +09004421 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4422 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4423 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004424
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004425 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004426 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4427 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004428 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004429 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004430 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004431 }
Paul Jensen992f2522014-04-28 10:33:11 -04004432
4433 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4434 CompareResult<String> interfaceDiff = new CompareResult<String>();
4435 if (oldLp != null) {
4436 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4437 } else if (newLp != null) {
4438 interfaceDiff.added = newLp.getAllInterfaceNames();
4439 }
4440 for (String iface : interfaceDiff.added) {
4441 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004442 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004443 mNetd.addInterfaceToNetwork(iface, netId);
4444 } catch (Exception e) {
4445 loge("Exception adding interface: " + e);
4446 }
4447 }
4448 for (String iface : interfaceDiff.removed) {
4449 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004450 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004451 mNetd.removeInterfaceFromNetwork(iface, netId);
4452 } catch (Exception e) {
4453 loge("Exception removing interface: " + e);
4454 }
4455 }
4456 }
4457
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004458 /**
4459 * Have netd update routes from oldLp to newLp.
4460 * @return true if routes changed between oldLp and newLp
4461 */
4462 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004463 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4464 if (oldLp != null) {
4465 routeDiff = oldLp.compareAllRoutes(newLp);
4466 } else if (newLp != null) {
4467 routeDiff.added = newLp.getAllRoutes();
4468 }
4469
4470 // add routes before removing old in case it helps with continuous connectivity
4471
4472 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4473 for (RouteInfo route : routeDiff.added) {
4474 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004475 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004476 try {
4477 mNetd.addRoute(netId, route);
4478 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004479 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4480 loge("Exception in addRoute for non-gateway: " + e);
4481 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004482 }
4483 }
4484 for (RouteInfo route : routeDiff.added) {
4485 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004486 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004487 try {
4488 mNetd.addRoute(netId, route);
4489 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004490 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4491 loge("Exception in addRoute for gateway: " + e);
4492 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004493 }
4494 }
4495
4496 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004497 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004498 try {
4499 mNetd.removeRoute(netId, route);
4500 } catch (Exception e) {
4501 loge("Exception in removeRoute: " + e);
4502 }
4503 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004504 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004505 }
Erik Kline41368502015-06-17 13:19:54 +09004506
Erik Kline94887872016-04-05 13:30:49 +09004507 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4508 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4509 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004510 }
Erik Kline94887872016-04-05 13:30:49 +09004511
4512 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004513 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004514 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004515 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004516 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4517 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004518 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004519 }
4520 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4521 if (defaultNai != null && defaultNai.network.netId == netId) {
4522 setDefaultDnsSystemProperties(dnses);
4523 }
4524 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004525 }
4526
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004527 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4528 int last = 0;
4529 for (InetAddress dns : dnses) {
4530 ++last;
4531 String key = "net.dns" + last;
4532 String value = dns.getHostAddress();
4533 SystemProperties.set(key, value);
4534 }
4535 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4536 String key = "net.dns" + i;
4537 SystemProperties.set(key, "");
4538 }
4539 mNumDnsEntries = last;
4540 }
4541
Paul Jensen3d194ea2015-06-16 14:27:36 -04004542 /**
4543 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4544 * augmented with any stateful capabilities implied from {@code networkAgent}
4545 * (e.g., validated status and captive portal status).
4546 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004547 * @param oldScore score of the network before any of the changes that prompted us
4548 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004549 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004550 * @param networkCapabilities the new network capabilities.
4551 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004552 private void updateCapabilities(
4553 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004554 // Don't modify caller's NetworkCapabilities.
4555 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004556 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004557 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4558 } else {
4559 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4560 }
Paul Jensene0988542015-06-25 15:30:08 -04004561 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004562 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4563 } else {
4564 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4565 }
Paul Jensene0988542015-06-25 15:30:08 -04004566 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
Paul Jensen487ffe72015-07-24 15:57:11 -04004567 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4568 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4569 try {
4570 mNetd.setNetworkPermission(nai.network.netId,
4571 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4572 null : NetworkManagementService.PERMISSION_SYSTEM);
4573 } catch (RemoteException e) {
4574 loge("Exception in setNetworkPermission: " + e);
4575 }
4576 }
Paul Jensene0988542015-06-25 15:30:08 -04004577 synchronized (nai) {
4578 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004579 }
Paul Jensene0988542015-06-25 15:30:08 -04004580 rematchAllNetworksAndRequests(nai, oldScore);
4581 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004582 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004583 }
4584
Paul Jensenc8b9a742014-09-30 15:37:41 -04004585 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004586 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4587 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004588 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004589 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004590 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4591 }
4592 }
4593
Robert Greenwalt7b816022014-04-18 15:25:25 -07004594 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4595 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004596 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004597 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4598 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004599 }
4600 }
4601
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004602 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4603 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004604 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004605 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004606 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4607 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004608 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004609 sendIntent(nri.mPendingIntent, intent);
4610 }
4611 // else not handled
4612 }
4613
4614 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4615 mPendingIntentWakeLock.acquire();
4616 try {
4617 if (DBG) log("Sending " + pendingIntent);
4618 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4619 } catch (PendingIntent.CanceledException e) {
4620 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4621 mPendingIntentWakeLock.release();
4622 releasePendingNetworkRequest(pendingIntent);
4623 }
4624 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4625 }
4626
4627 @Override
4628 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4629 String resultData, Bundle resultExtras) {
4630 if (DBG) log("Finished sending " + pendingIntent);
4631 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004632 // Release with a delay so the receiving client has an opportunity to put in its
4633 // own request.
4634 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004635 }
4636
Robert Greenwalt9258c642014-03-26 16:47:06 -07004637 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004638 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004639 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004640 Bundle bundle = new Bundle();
4641 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4642 new NetworkRequest(nri.request));
4643 Message msg = Message.obtain();
4644 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4645 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4646 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4647 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004648 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004649 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004650 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004651 break;
4652 }
4653 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4654 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4655 new NetworkCapabilities(networkAgent.networkCapabilities));
4656 break;
4657 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004658 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004659 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4660 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004661 break;
4662 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004663 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004664 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004665 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004666 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004667 if (VDBG) {
4668 log("sending notification " + notifyTypeToName(notificationType) +
4669 " for " + nri.request);
4670 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004671 nri.messenger.send(msg);
4672 } catch (RemoteException e) {
4673 // may occur naturally in the race of binder death.
4674 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4675 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004676 }
4677
Paul Jensenc8b9a742014-09-30 15:37:41 -04004678 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004679 if (nai.numRequestNetworkRequests() != 0) {
4680 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4681 NetworkRequest nr = nai.requestAt(i);
4682 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004683 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004684 loge("Dead network still had at least " + nr);
4685 break;
4686 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004687 }
4688 nai.asyncChannel.disconnect();
4689 }
4690
Robert Greenwalt7b816022014-04-18 15:25:25 -07004691 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4692 if (oldNetwork == null) {
4693 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4694 return;
4695 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004696 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004697
4698 // If we get here it means that the last linger timeout for this network expired. So there
4699 // must be no other active linger timers, and we must stop lingering.
4700 oldNetwork.clearLingerState();
4701
4702 if (unneeded(oldNetwork)) {
4703 teardownUnneededNetwork(oldNetwork);
4704 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004705 }
4706
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004707 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004708 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004709 setupDataActivityTracking(newNetwork);
4710 try {
4711 mNetd.setDefaultNetId(newNetwork.network.netId);
4712 } catch (Exception e) {
4713 loge("Exception setting default network :" + e);
4714 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004715 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004716 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004717 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004718 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004719 }
4720
Paul Jensen2161a8e2014-09-11 11:00:39 -04004721 // Handles a network appearing or improving its score.
4722 //
4723 // - Evaluates all current NetworkRequests that can be
4724 // satisfied by newNetwork, and reassigns to newNetwork
4725 // any such requests for which newNetwork is the best.
4726 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004727 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004728 // needed. A network is needed if it is the best network for
4729 // one or more NetworkRequests, or if it is a VPN.
4730 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004731 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004732 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004733 //
4734 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4735 // networks that have no chance (i.e. even if validated)
4736 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004737 //
4738 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4739 // it does not remove NetworkRequests that other Networks could better satisfy.
4740 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4741 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4742 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004743 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004744 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004745 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4746 // performed to tear down unvalidated networks that have no chance (i.e. even if
4747 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004748 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004749 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004750 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004751 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004752 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004753 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004754 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004755 // Find and migrate to this Network any NetworkRequests for
4756 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004757 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004758 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004759 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004760 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004761 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4762 final boolean satisfies = newNetwork.satisfies(nri.request);
4763 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004764 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004765 log("Network " + newNetwork.name() + " was already satisfying" +
4766 " request " + nri.request.requestId + ". No change.");
4767 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004768 keep = true;
4769 continue;
4770 }
4771
4772 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004773 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004774 if (satisfies) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004775 if (nri.request.isListen()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004776 // This is not a request, it's a callback listener.
4777 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004778 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004779 continue;
4780 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004781
Robert Greenwalt7b816022014-04-18 15:25:25 -07004782 // next check if it's better than any current network we're using for
4783 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004784 if (VDBG) {
4785 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004786 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4787 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004788 }
4789 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004790 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004791 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004792 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004793 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004794 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004795 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004796 affectedNetworks.add(currentNetwork);
4797 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004798 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004799 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004800 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004801 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004802 if (!newNetwork.addRequest(nri.request)) {
4803 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4804 }
4805 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004806 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004807 // Tell NetworkFactories about the new score, so they can stop
4808 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004809 // TODO - this could get expensive if we have alot of requests for this
4810 // network. Think about if there is a way to reduce this. Push
4811 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004812 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004813 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004814 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004815 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004816 if (currentNetwork != null) {
4817 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4818 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004819 }
4820 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004821 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004822 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4823 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004824 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004825 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4826 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4827 // This means this code doesn't have to handle the case where "currentNetwork" no
4828 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4829 if (DBG) {
4830 log("Network " + newNetwork.name() + " stopped satisfying" +
4831 " request " + nri.request.requestId);
4832 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004833 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004834 if (currentNetwork == newNetwork) {
4835 mNetworkForRequestId.remove(nri.request.requestId);
4836 sendUpdatedScoreToFactories(nri.request, 0);
4837 } else {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004838 if (nri.request.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004839 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4840 newNetwork.name() +
4841 " without updating mNetworkForRequestId or factories!");
4842 }
4843 }
4844 // TODO: technically, sending CALLBACK_LOST here is
4845 // incorrect if nri is a request (not a listen) and there
4846 // is a replacement network currently connected that can
4847 // satisfy it. However, the only capability that can both
4848 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4849 // so this code is only incorrect for a network that loses
4850 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004851 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004852 }
4853 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004854 if (isNewDefault) {
4855 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004856 makeDefault(newNetwork);
4857 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4858 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004859 synchronized (ConnectivityService.this) {
4860 // have a new default network, release the transition wakelock in
4861 // a second if it's held. The second pause is to allow apps
4862 // to reconnect over the new network
4863 if (mNetTransitionWakeLock.isHeld()) {
4864 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4865 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4866 mNetTransitionWakeLockSerialNumber, 0),
4867 1000);
4868 }
4869 }
4870 }
4871
4872 // do this after the default net is switched, but
4873 // before LegacyTypeTracker sends legacy broadcasts
4874 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4875
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004876 // Linger any networks that are no longer needed. This should be done after sending the
4877 // available callback for newNetwork.
4878 for (NetworkAgentInfo nai : affectedNetworks) {
4879 updateLingerState(nai, now);
4880 }
4881 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4882 // does not need to be done in any particular order.
4883 updateLingerState(newNetwork, now);
4884
Paul Jensencf4c2c62015-07-01 14:16:32 -04004885 if (isNewDefault) {
4886 // Maintain the illusion: since the legacy API only
4887 // understands one network at a time, we must pretend
4888 // that the current default network disconnected before
4889 // the new one connected.
4890 if (oldDefaultNetwork != null) {
4891 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4892 oldDefaultNetwork, true);
4893 }
4894 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4895 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4896 notifyLockdownVpn(newNetwork);
4897 }
4898
Robert Greenwalt7b816022014-04-18 15:25:25 -07004899 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004900 // Notify battery stats service about this network, both the normal
4901 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004902 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004903 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004904 final IBatteryStats bs = BatteryStatsService.getService();
4905 final int type = newNetwork.networkInfo.getType();
4906
4907 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4908 bs.noteNetworkInterfaceType(baseIface, type);
4909 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4910 final String stackedIface = stacked.getInterfaceName();
4911 bs.noteNetworkInterfaceType(stackedIface, type);
4912 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4913 }
4914 } catch (RemoteException ignored) {
4915 }
4916
Robert Greenwalt152ed372014-12-17 17:19:53 -08004917 // This has to happen after the notifyNetworkCallbacks as that tickles each
4918 // ConnectivityManager instance so that legacy requests correctly bind dns
4919 // requests to this network. The legacy users are listening for this bcast
4920 // and will generally do a dns request so they can ensureRouteToHost and if
4921 // they do that before the callbacks happen they'll use the default network.
4922 //
4923 // TODO: Is there still a race here? We send the broadcast
4924 // after sending the callback, but if the app can receive the
4925 // broadcast before the callback, it might still break.
4926 //
4927 // This *does* introduce a race where if the user uses the new api
4928 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4929 // they may get old info. Reverse this after the old startUsing api is removed.
4930 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004931 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4932 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004933 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004934 // legacy type tracker filters out repeat adds
4935 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4936 }
4937 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004938
4939 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4940 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4941 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4942 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4943 if (newNetwork.isVPN()) {
4944 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4945 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004946 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004947 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4948 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004949 if (unneeded(nai)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004950 if (nai.getLingerExpiry() > 0) {
4951 // This network has active linger timers and no requests, but is not
4952 // lingering. Linger it.
4953 //
4954 // One way (the only way?) this can happen if this network is unvalidated
4955 // and became unneeded due to another network improving its score to the
4956 // point where this network will no longer be able to satisfy any requests
4957 // even if it validates.
4958 updateLingerState(nai, now);
4959 } else {
4960 if (DBG) log("Reaping " + nai.name());
4961 teardownUnneededNetwork(nai);
4962 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004963 }
4964 }
4965 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004966 }
4967
Paul Jensen1c7ba022015-06-16 14:27:36 -04004968 /**
4969 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4970 * being disconnected.
4971 * @param changed If only one Network's score or capabilities have been modified since the last
4972 * time this function was called, pass this Network in this argument, otherwise pass
4973 * null.
4974 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4975 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4976 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4977 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4978 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004979 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004980 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004981 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4982 // to avoid the slowness. It is not simply enough to process just "changed", for
4983 // example in the case where "changed"'s score decreases and another network should begin
4984 // satifying a NetworkRequest that "changed" currently satisfies.
4985
4986 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4987 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4988 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004989 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04004990 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004991 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004992 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004993 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4994 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4995 // Rematch higher scoring networks first to prevent requests first matching a lower
4996 // scoring network and then a higher scoring network, which could produce multiple
4997 // callbacks and inadvertently unlinger networks.
4998 Arrays.sort(nais);
4999 for (NetworkAgentInfo nai : nais) {
5000 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005001 // Only reap the last time through the loop. Reaping before all rematching
5002 // is complete could incorrectly teardown a network that hasn't yet been
5003 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005004 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005005 : ReapUnvalidatedNetworks.REAP,
5006 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005007 }
5008 }
5009 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005010
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005011 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005012 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005013 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005014 // For now only update icons for default connection.
5015 // TODO: Update WiFi and cellular icons separately. b/17237507
5016 if (!isDefaultNetwork(nai)) return;
5017
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005018 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005019 // Don't repeat publish.
5020 if (newInetCondition == mDefaultInetConditionPublished) return;
5021
5022 mDefaultInetConditionPublished = newInetCondition;
5023 sendInetConditionBroadcast(nai.networkInfo);
5024 }
5025
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005026 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5027 if (mLockdownTracker != null) {
5028 if (nai != null && nai.isVPN()) {
5029 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5030 } else {
5031 mLockdownTracker.onNetworkInfoChanged();
5032 }
5033 }
5034 }
5035
Robert Greenwalt7b816022014-04-18 15:25:25 -07005036 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5037 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005038 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005039 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005040 synchronized (networkAgent) {
5041 oldInfo = networkAgent.networkInfo;
5042 networkAgent.networkInfo = newInfo;
5043 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005044 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005045
5046 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005047 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5048 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5049 notifyIfacesChangedForNetworkStats();
5050 } else if (VDBG) log("ignoring duplicate network state non-change");
5051 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005052 return;
5053 }
5054 if (DBG) {
5055 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5056 (oldInfo == null ? "null" : oldInfo.getState()) +
5057 " to " + state);
5058 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005059
Robin Lee585e2482016-05-01 23:00:00 +01005060 if (!networkAgent.created
5061 && (state == NetworkInfo.State.CONNECTED
5062 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005063 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005064 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005065 if (networkAgent.isVPN()) {
5066 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005067 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5068 (networkAgent.networkMisc == null ||
5069 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005070 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005071 mNetd.createPhysicalNetwork(networkAgent.network.netId,
5072 networkAgent.networkCapabilities.hasCapability(
5073 NET_CAPABILITY_NOT_RESTRICTED) ?
5074 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005075 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005076 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005077 loge("Error creating network " + networkAgent.network.netId + ": "
5078 + e.getMessage());
5079 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005080 }
Paul Jenseneec75412014-08-04 12:21:19 -04005081 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005082 }
5083
5084 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5085 networkAgent.everConnected = true;
5086
Robert Greenwalt7b816022014-04-18 15:25:25 -07005087 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005088 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005089
Paul Jensenca8f16a2014-05-09 12:47:55 -04005090 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005091 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005092
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005093 if (networkAgent.isVPN()) {
5094 // Temporarily disable the default proxy (not global).
5095 synchronized (mProxyLock) {
5096 if (!mDefaultProxyDisabled) {
5097 mDefaultProxyDisabled = true;
5098 if (mGlobalProxy == null && mDefaultProxy != null) {
5099 sendProxyBroadcast(null);
5100 }
5101 }
5102 }
5103 // TODO: support proxy per network.
5104 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005105
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005106 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5107 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5108 // capabilities, so it only needs to be done once on initial connect, not every time the
5109 // network's capabilities change. Note that we do this before rematching the network,
5110 // so we could decide to tear it down immediately afterwards. That's fine though - on
5111 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5112 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005113 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005114
Paul Jensen2161a8e2014-09-11 11:00:39 -04005115 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005116 final long now = SystemClock.elapsedRealtime();
5117 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005118
5119 // This has to happen after matching the requests, because callbacks are just requests.
5120 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005121 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005122 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005123 if (networkAgent.isVPN()) {
5124 synchronized (mProxyLock) {
5125 if (mDefaultProxyDisabled) {
5126 mDefaultProxyDisabled = false;
5127 if (mGlobalProxy == null && mDefaultProxy != null) {
5128 sendProxyBroadcast(mDefaultProxy);
5129 }
5130 }
5131 }
5132 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005133 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5134 state == NetworkInfo.State.SUSPENDED) {
5135 // going into or coming out of SUSPEND: rescore and notify
5136 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005137 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005138 }
5139 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5140 ConnectivityManager.CALLBACK_SUSPENDED :
5141 ConnectivityManager.CALLBACK_RESUMED));
5142 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005143 }
5144 }
5145
Robert Greenwaltac96c522014-06-03 16:43:57 -07005146 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005147 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005148 if (score < 0) {
5149 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5150 "). Bumping score to min of 0");
5151 score = 0;
5152 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005153
Paul Jensen2161a8e2014-09-11 11:00:39 -04005154 final int oldScore = nai.getCurrentScore();
5155 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005156
Paul Jensen85cf78e2015-06-25 13:25:07 -04005157 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005158
Paul Jensenc8b9a742014-09-30 15:37:41 -04005159 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005160 }
5161
Robert Greenwalt9258c642014-03-26 16:47:06 -07005162 // notify only this one new request of the current state
5163 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5164 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005165 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005166 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005167 } else {
5168 sendPendingIntentForRequest(nri, nai, notifyType);
5169 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005170 }
5171
Robert Greenwalt8d482522015-06-24 13:23:42 -07005172 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005173 // The NetworkInfo we actually send out has no bearing on the real
5174 // state of affairs. For example, if the default connection is mobile,
5175 // and a request for HIPRI has just gone away, we need to pretend that
5176 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5177 // the state to DISCONNECTED, even though the network is of type MOBILE
5178 // and is still connected.
5179 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5180 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005181 if (state != DetailedState.DISCONNECTED) {
5182 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005183 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005184 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005185 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005186 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5187 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5188 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5189 if (info.isFailover()) {
5190 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5191 nai.networkInfo.setFailover(false);
5192 }
5193 if (info.getReason() != null) {
5194 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5195 }
5196 if (info.getExtraInfo() != null) {
5197 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5198 }
5199 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005200 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005201 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005202 if (newDefaultAgent != null) {
5203 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5204 newDefaultAgent.networkInfo);
5205 } else {
5206 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5207 }
5208 }
5209 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5210 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005211 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005212 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005213 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005214 }
5215 }
5216 }
5217
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005218 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005219 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005220 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5221 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005222 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5223 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005224 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005225 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005226 } else {
5227 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5228 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005229 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005230 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005231
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005232 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5233 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5234 }
5235
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005236 private String notifyTypeToName(int notifyType) {
5237 switch (notifyType) {
5238 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5239 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5240 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5241 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5242 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5243 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5244 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5245 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5246 }
5247 return "UNKNOWN";
5248 }
5249
Jeff Sharkey69736342014-12-08 14:50:12 -08005250 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005251 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5252 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005253 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005254 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005255 try {
5256 mStatsService.forceUpdateIfaces();
5257 } catch (Exception ignored) {
5258 }
5259 }
5260
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005261 @Override
5262 public boolean addVpnAddress(String address, int prefixLength) {
5263 throwIfLockdownEnabled();
5264 int user = UserHandle.getUserId(Binder.getCallingUid());
5265 synchronized (mVpns) {
5266 return mVpns.get(user).addAddress(address, prefixLength);
5267 }
5268 }
5269
5270 @Override
5271 public boolean removeVpnAddress(String address, int prefixLength) {
5272 throwIfLockdownEnabled();
5273 int user = UserHandle.getUserId(Binder.getCallingUid());
5274 synchronized (mVpns) {
5275 return mVpns.get(user).removeAddress(address, prefixLength);
5276 }
5277 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005278
5279 @Override
5280 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5281 throwIfLockdownEnabled();
5282 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005283 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005284 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005285 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005286 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005287 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005288 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005289 }
5290 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005291 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005292
5293 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005294 public String getCaptivePortalServerUrl() {
5295 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5296 }
5297
5298 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005299 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5300 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5301 enforceKeepalivePermission();
5302 mKeepaliveTracker.startNattKeepalive(
5303 getNetworkAgentInfoForNetwork(network),
5304 intervalSeconds, messenger, binder,
5305 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5306 }
5307
5308 @Override
5309 public void stopKeepalive(Network network, int slot) {
5310 mHandler.sendMessage(mHandler.obtainMessage(
5311 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5312 }
5313
5314 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005315 public void factoryReset() {
5316 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005317
5318 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5319 return;
5320 }
5321
Robin Lee3b3dd942015-05-12 18:14:58 +01005322 final int userId = UserHandle.getCallingUserId();
5323
Stuart Scottf1fb3972015-04-02 18:00:02 -07005324 // Turn airplane mode off
5325 setAirplaneMode(false);
5326
Stuart Scotte3e314d2015-04-20 14:07:45 -07005327 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5328 // Untether
5329 for (String tether : getTetheredIfaces()) {
5330 untether(tether);
5331 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005332 }
5333
Stuart Scotte3e314d2015-04-20 14:07:45 -07005334 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005335 // Remove always-on package
5336 synchronized (mVpns) {
5337 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5338 if (alwaysOnPackage != null) {
5339 setAlwaysOnVpnPackage(userId, null, false);
5340 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5341 }
5342 }
5343
Stuart Scotte3e314d2015-04-20 14:07:45 -07005344 // Turn VPN off
5345 VpnConfig vpnConfig = getVpnConfig(userId);
5346 if (vpnConfig != null) {
5347 if (vpnConfig.legacy) {
5348 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5349 } else {
5350 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5351 // in the future without user intervention.
5352 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005353
Victor Changb04a5ea2016-05-30 20:36:30 +01005354 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005355 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005356 }
5357 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005358
5359 Settings.Global.putString(mContext.getContentResolver(),
5360 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005361 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005362
5363 @VisibleForTesting
5364 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5365 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5366 return new NetworkMonitor(context, handler, nai, defaultRequest);
5367 }
Erik Kline48f12f22016-04-14 17:30:59 +09005368
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005369 @VisibleForTesting
5370 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5371 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5372 }
5373
Hugo Benichicfddd682016-05-31 16:28:06 +09005374 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005375 int newNetid = NETID_UNSET;
5376 int prevNetid = NETID_UNSET;
5377 int[] transports = new int[0];
5378 boolean hadIPv4 = false;
5379 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005380
Hugo Benichi5f16f762016-04-20 12:09:33 +09005381 if (newNai != null) {
5382 newNetid = newNai.network.netId;
5383 transports = newNai.networkCapabilities.getTransportTypes();
5384 }
5385 if (prevNai != null) {
5386 prevNetid = prevNai.network.netId;
5387 final LinkProperties lp = prevNai.linkProperties;
5388 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5389 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5390 }
5391
Hugo Benichicfddd682016-05-31 16:28:06 +09005392 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5393 }
5394
5395 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5396 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398}