blob: ee455af5e31a73628ec4c5c67ea08737f720a70b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070032import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060033import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070034import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070036import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070038import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060039
Wenchao Tongf5ea3402015-03-04 13:26:38 -080040import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080041import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090042import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070043import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070048import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090051import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070052import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090054import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070056import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.INetworkPolicyListener;
58import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070059import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070063import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070065import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070067import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070068import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070069import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070070import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070071import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070072import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070073import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040074import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070075import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040076import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040077import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090078import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090079import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090080import android.net.metrics.NetworkEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080082import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070083import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040084import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070086import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070088import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.Looper;
90import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070091import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070092import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070093import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070094import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070095import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080096import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090097import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070099import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400100import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700102import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700103import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700104import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700105import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600106import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700107import android.util.LocalLog;
108import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600109import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700110import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800111import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700112import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500113import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700115import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Wink Savilleab9321d2013-06-29 21:10:57 -0700117import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400118import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400119import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700121import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700123import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800124import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700125import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700126import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700127import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900128import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900129import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700130import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700131import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400132import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900133import com.android.server.connectivity.KeepaliveTracker;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900134import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900135import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700136import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600137import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400138import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900139import com.android.server.connectivity.NetworkNotificationManager;
140import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400141import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700142import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800143import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700144import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700145import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700146import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600147
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700148import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700149
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700150import org.xmlpull.v1.XmlPullParser;
151import org.xmlpull.v1.XmlPullParserException;
152
153import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700155import java.io.FileNotFoundException;
156import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700157import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700159import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700160import java.net.InetAddress;
161import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700162import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700163import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700164import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700165import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700166import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700167import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700168import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700169import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700170import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600171import java.util.SortedSet;
172import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
174/**
175 * @hide
176 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800177public class ConnectivityService extends IConnectivityManager.Stub
178 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900179 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900181 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700182 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
Jake Hamby786e71a2014-02-06 14:43:50 -0800184 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900185 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700186
Jeff Sharkey899223b2012-08-04 15:24:58 -0700187 // TODO: create better separation between radio types and network types
188
Robert Greenwalt42acef32009-08-12 16:08:25 -0700189 // how long to wait before switching back to a radio's default network
190 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
191 // system property that can override the above value
192 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
193 "android.telephony.apn-restore";
194
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900195 // How long to wait before putting up a "This network doesn't have an Internet connection,
196 // connect anyway?" dialog after the user selects a network that doesn't validate.
197 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
198
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900199 // Default to 30s linger time-out. Modifiable only for testing.
200 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
201 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
202 @VisibleForTesting
203 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
204
Jeremy Joslin79294842014-12-03 17:15:28 -0800205 // How long to delay to removal of a pending intent based request.
206 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
207 private final int mReleasePendingIntentDelayMs;
208
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800209 private Tethering mTethering;
210
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700211 private final PermissionMonitor mPermissionMonitor;
212
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700213 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700214
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700215 @GuardedBy("mVpns")
216 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700217
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700218 private boolean mLockdownEnabled;
219 private LockdownVpnTracker mLockdownTracker;
220
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700221 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
222 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700223 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600224 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700225 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700226 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600227 @GuardedBy("mRulesLock")
228 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
229 /** Flag indicating if background data is restricted. */
230 @GuardedBy("mRulesLock")
231 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700232
Erik Klineda4bfa82015-04-30 12:58:40 +0900233 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700235 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700236 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800238 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700241 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700243 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800244 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700245 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700246
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700247 private String mCurrentTcpBufferSizes;
248
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700249 private static final int ENABLED = 1;
250 private static final int DISABLED = 0;
251
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900252 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900253 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
254 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900255
Paul Jensenb10e37f2014-11-25 12:33:08 -0500256 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400257 // Tear down networks that have no chance (e.g. even if validated) of becoming
258 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500259 // all networks have been rematched against all NetworkRequests.
260 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400261 // Don't reap networks. This should be passed when some networks have not yet been
262 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500263 DONT_REAP
264 };
265
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900266 private enum UnneededFor {
267 LINGER, // Determine whether this network is unneeded and should be lingered.
268 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
269 }
270
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700271 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700272 * used internally to change our mobile data enabled flag
273 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700274 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700275
276 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700277 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700278 * from one net to another. Clear happens when we get a new
279 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
280 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700281 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700282 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700283
Robert Greenwalt434203a2010-10-11 16:00:27 -0700284 /**
285 * used internally to reload global proxy settings
286 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700287 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700288
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700289 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400290 * PAC manager has received new port.
291 */
292 private static final int EVENT_PROXY_HAS_CHANGED = 16;
293
Robert Greenwalte049c232014-04-11 15:53:27 -0700294 /**
295 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700296 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700297 */
298 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
299
Robert Greenwalt7b816022014-04-18 15:25:25 -0700300 /**
301 * used internally when registering NetworkAgents
302 * obj = Messenger
303 */
304 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
305
Robert Greenwalt9258c642014-03-26 16:47:06 -0700306 /**
307 * used to add a network request
308 * includes a NetworkRequestInfo
309 */
310 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
311
312 /**
313 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900314 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700315 * cancel it.
316 * includes a NetworkRequestInfo
317 */
318 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
319
320 /**
321 * used to add a network listener - no request
322 * includes a NetworkRequestInfo
323 */
324 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
325
326 /**
327 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400328 * arg1 = UID of caller
329 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700330 */
331 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
332
Robert Greenwalta67be032014-05-16 15:49:14 -0700333 /**
334 * used internally when registering NetworkFactories
335 * obj = Messenger
336 */
337 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
338
Robert Greenwalt27711812014-06-25 16:45:57 -0700339 /**
340 * used internally to expire a wakelock when transitioning
341 * from one net to another. Expire happens when we fail to find
342 * a new network (typically after 1 minute) -
343 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
344 * a replacement network.
345 */
346 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
347
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700348 /**
349 * Used internally to indicate the system is ready.
350 */
351 private static final int EVENT_SYSTEM_READY = 25;
352
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800353 /**
354 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400355 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800356 */
357 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
358
359 /**
360 * used to remove a pending intent and its associated network request.
361 * arg1 = UID of caller
362 * obj = PendingIntent
363 */
364 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
365
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900366 /**
367 * used to specify whether a network should be used even if unvalidated.
368 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
369 * arg2 = whether to remember this choice in the future (1 or 0)
370 * obj = network
371 */
372 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
373
374 /**
375 * used to ask the user to confirm a connection to an unvalidated network.
376 * obj = network
377 */
378 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700379
Erik Klineda4bfa82015-04-30 12:58:40 +0900380 /**
381 * used internally to (re)configure mobile data always-on settings.
382 */
383 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
384
Paul Jensen694f2b82015-06-17 14:15:39 -0400385 /**
386 * used to add a network listener with a pending intent
387 * obj = NetworkRequestInfo
388 */
389 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
390
Erik Klineacdd6392016-07-07 16:50:58 +0900391 /**
392 * Indicates a caller has requested to have its callback invoked with
393 * the latest LinkProperties or NetworkCapabilities.
394 *
395 * arg1 = UID of caller
396 * obj = NetworkRequest
397 */
398 private static final int EVENT_REQUEST_LINKPROPERTIES = 32;
399 private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
400
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900401 /** Handler thread used for both of the handlers below. */
402 @VisibleForTesting
403 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700404 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700405 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700406 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700407 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700408
Mike Lockwood0f79b542009-08-14 14:18:49 -0400409 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800410 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400411
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700412 private PowerManager.WakeLock mNetTransitionWakeLock;
413 private String mNetTransitionWakeLockCausedBy = "";
414 private int mNetTransitionWakeLockSerialNumber;
415 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800416 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700417
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700418 // used in DBG mode to track inet condition reports
419 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
420 private ArrayList mInetLog;
421
Robert Greenwalt434203a2010-10-11 16:00:27 -0700422 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400423 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700424 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700425 private boolean mDefaultProxyDisabled = false;
426
Robert Greenwalt434203a2010-10-11 16:00:27 -0700427 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400428 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700429
Jason Monk602b2322013-07-03 17:04:33 -0400430 private PacManager mPacManager = null;
431
Erik Klineda4bfa82015-04-30 12:58:40 +0900432 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700433
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400434 private UserManager mUserManager;
435
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700436 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700437 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700438
Robert Greenwalt50393202011-06-21 17:26:14 -0700439 // the set of network types that can only be enabled by system/sig apps
440 List mProtectedNetworks;
441
John Spurlockbf991a82013-06-24 14:20:23 -0400442 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700443
Wink Savilleab9321d2013-06-29 21:10:57 -0700444 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400445
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900446 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900447 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900448 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900449
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700450 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
451 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700452 private final static int MAX_NET_ID = 65535;
453 private int mNextNetId = MIN_NET_ID;
454
Robert Greenwalt34524f02014-05-18 16:22:10 -0700455 // sequence number of NetworkRequests
456 private int mNextNetworkRequestId = 1;
457
Erik Kline7523eb32015-07-09 18:24:03 +0900458 // NetworkRequest activity String log entries.
459 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
460 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
461
Hugo Benichic2ae2872016-07-11 11:05:12 +0900462 // NetworkInfo blocked and unblocked String log entries
463 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
464 private static final int MAX_NETWORK_INFO_LOGS = 100;
465 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
466
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700467 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
468 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400469 private static class ValidationLog {
470 final Network mNetwork;
471 final String mNetworkExtraInfo;
472 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700473
Paul Jensen0808eb82016-06-03 13:51:21 -0400474 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
475 mNetwork = network;
476 mNetworkExtraInfo = networkExtraInfo;
477 mLog = log;
478 }
479 }
480 private final ArrayDeque<ValidationLog> mValidationLogs =
481 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
482
483 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700484 synchronized(mValidationLogs) {
485 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
486 mValidationLogs.removeLast();
487 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400488 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700489 }
490 }
491
Hugo Benichif9fdf872016-07-28 17:53:06 +0900492 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900493
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700494 /**
495 * Implements support for the legacy "one network per network type" model.
496 *
497 * We used to have a static array of NetworkStateTrackers, one for each
498 * network type, but that doesn't work any more now that we can have,
499 * for example, more that one wifi network. This class stores all the
500 * NetworkAgentInfo objects that support a given type, but the legacy
501 * API will only see the first one.
502 *
503 * It serves two main purposes:
504 *
505 * 1. Provide information about "the network for a given type" (since this
506 * API only supports one).
507 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
508 * the first network for a given type changes, or if the default network
509 * changes.
510 */
511 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900512
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900513 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900514 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700516 /**
517 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
518 * Each list holds references to all NetworkAgentInfos that are used to
519 * satisfy requests for that network type.
520 *
521 * This array is built out at startup such that an unsupported network
522 * doesn't get an ArrayList instance, making this a tristate:
523 * unsupported, supported but not active and active.
524 *
525 * The actual lists are populated when we scan the network types that
526 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900527 *
528 * Threading model:
529 * - addSupportedType() is only called in the constructor
530 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
531 * They are therefore not thread-safe with respect to each other.
532 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
533 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
534 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700535 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900536 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700537
538 public LegacyTypeTracker() {
539 mTypeLists = (ArrayList<NetworkAgentInfo>[])
540 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
541 }
542
543 public void addSupportedType(int type) {
544 if (mTypeLists[type] != null) {
545 throw new IllegalStateException(
546 "legacy list for type " + type + "already initialized");
547 }
548 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
549 }
550
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700551 public boolean isTypeSupported(int type) {
552 return isNetworkTypeValid(type) && mTypeLists[type] != null;
553 }
554
555 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900556 synchronized (mTypeLists) {
557 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
558 return mTypeLists[type].get(0);
559 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900561 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700562 }
563
Robert Greenwalt8d482522015-06-24 13:23:42 -0700564 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900565 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900566 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700567 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900568 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900569 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900570 }
571 }
572
573 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700574 public void add(int type, NetworkAgentInfo nai) {
575 if (!isTypeSupported(type)) {
576 return; // Invalid network type.
577 }
578 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
579
580 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
581 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700582 return;
583 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900584 synchronized (mTypeLists) {
585 list.add(nai);
586 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900587
588 // 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 +0900589 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900590 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700591 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
592 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700593 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700594 }
595
Lorenzo Colittia793a672014-07-31 23:20:17 +0900596 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900597 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900598 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
599 if (list == null || list.isEmpty()) {
600 return;
601 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900602 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900603
Hugo Benichi78caa2582016-06-21 09:48:07 +0900604 synchronized (mTypeLists) {
605 if (!list.remove(nai)) {
606 return;
607 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608 }
609
Robert Greenwalt8d482522015-06-24 13:23:42 -0700610 final DetailedState state = DetailedState.DISCONNECTED;
611
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900612 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700613 maybeLogBroadcast(nai, state, type, wasDefault);
614 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900615 }
616
617 if (!list.isEmpty() && wasFirstNetwork) {
618 if (DBG) log("Other network available for type " + type +
619 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900620 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700621 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
622 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900623 }
624 }
625
626 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900627 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
628 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700629 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700631 }
632 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700633
Robert Greenwalt8d482522015-06-24 13:23:42 -0700634 // send out another legacy broadcast - currently only used for suspend/unsuspend
635 // toggle
636 public void update(NetworkAgentInfo nai) {
637 final boolean isDefault = isDefaultNetwork(nai);
638 final DetailedState state = nai.networkInfo.getDetailedState();
639 for (int type = 0; type < mTypeLists.length; type++) {
640 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700641 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900642 final boolean isFirst = contains && (nai == list.get(0));
643 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700644 maybeLogBroadcast(nai, state, type, isDefault);
645 sendLegacyNetworkBroadcast(nai, state, type);
646 }
647 }
648 }
649
Lorenzo Colittia793a672014-07-31 23:20:17 +0900650 private String naiToString(NetworkAgentInfo nai) {
651 String name = (nai != null) ? nai.name() : "null";
652 String state = (nai.networkInfo != null) ?
653 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
654 "???/???";
655 return name + " " + state;
656 }
657
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700658 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900659 pw.println("mLegacyTypeTracker:");
660 pw.increaseIndent();
661 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700662 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900663 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700664 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900665 pw.println();
666 pw.println("Current state:");
667 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900668 synchronized (mTypeLists) {
669 for (int type = 0; type < mTypeLists.length; type++) {
670 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
671 for (NetworkAgentInfo nai : mTypeLists[type]) {
672 pw.println(type + " " + naiToString(nai));
673 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900674 }
675 }
676 pw.decreaseIndent();
677 pw.decreaseIndent();
678 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700679 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700680 }
681 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
682
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900683 @VisibleForTesting
684 protected HandlerThread createHandlerThread() {
685 return new HandlerThread("ConnectivityServiceThread");
686 }
687
Jeff Sharkey899223b2012-08-04 15:24:58 -0700688 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700689 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900690 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
691 }
692
693 @VisibleForTesting
694 protected ConnectivityService(Context context, INetworkManagementService netManager,
695 INetworkStatsService statsService, INetworkPolicyManager policyManager,
696 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800697 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800698
Hugo Benichif9fdf872016-07-28 17:53:06 +0900699 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900700 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900701 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900702 mNetworkRequests.put(mDefaultRequest, defaultNRI);
703 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900704
705 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900706 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700707
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900708 mHandlerThread = createHandlerThread();
709 mHandlerThread.start();
710 mHandler = new InternalHandler(mHandlerThread.getLooper());
711 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700712
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800713 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800714 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
715 String id = Settings.Secure.getString(context.getContentResolver(),
716 Settings.Secure.ANDROID_ID);
717 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700718 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800719 SystemProperties.set("net.hostname", name);
720 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800721 }
722
Jeremy Joslin79294842014-12-03 17:15:28 -0800723 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
724 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
725
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900726 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
727
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700728 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700729 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800730 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700731 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700732 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700733 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700734
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700735 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600736 mPolicyManager.setConnectivityListener(mPolicyListener);
737 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700738 } catch (RemoteException e) {
739 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700740 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700741 }
742
743 final PowerManager powerManager = (PowerManager) context.getSystemService(
744 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700745 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
746 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
747 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800748 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700749
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700750 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700751
Wink Saville51f456f2013-04-23 14:26:51 -0700752 // TODO: What is the "correct" way to do determine if this is a wifi only device?
753 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
754 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700755 String[] naStrings = context.getResources().getStringArray(
756 com.android.internal.R.array.networkAttributes);
757 for (String naString : naStrings) {
758 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700759 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700760 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700761 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800762 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700763 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700764 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700765 }
Wink Saville51f456f2013-04-23 14:26:51 -0700766 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
767 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
768 n.type);
769 continue;
770 }
Wink Saville975c8482011-04-07 14:23:45 -0700771 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800772 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700773 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700774 continue;
775 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700776 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700777
Wink Saville975c8482011-04-07 14:23:45 -0700778 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700779 mNetworksDefined++;
780 } catch(Exception e) {
781 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700782 }
783 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700784
785 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
786 if (mNetConfigs[TYPE_VPN] == null) {
787 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
788 // don't need to add TYPE_VPN to mNetConfigs.
789 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
790 mNetworksDefined++; // used only in the log() statement below.
791 }
792
Wink Saville5e56bc52013-07-29 15:00:57 -0700793 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700794
Robert Greenwalt50393202011-06-21 17:26:14 -0700795 mProtectedNetworks = new ArrayList<Integer>();
796 int[] protectedNetworks = context.getResources().getIntArray(
797 com.android.internal.R.array.config_protectedNetworks);
798 for (int p : protectedNetworks) {
799 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
800 mProtectedNetworks.add(p);
801 } else {
802 if (DBG) loge("Ignoring protectedNetwork " + p);
803 }
804 }
805
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700806 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
807 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700808
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800809 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800810
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700811 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
812
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700813 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700814 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100815 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700816 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700817 intentFilter.addAction(Intent.ACTION_USER_ADDED);
818 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000819 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700820 mContext.registerReceiverAsUser(
821 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900822
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700823 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700824 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700825 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700826 } catch (RemoteException e) {
827 loge("Error registering observer :" + e);
828 }
829
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700830 if (DBG) {
831 mInetLog = new ArrayList();
832 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700833
Erik Klineda4bfa82015-04-30 12:58:40 +0900834 mSettingsObserver = new SettingsObserver(mContext, mHandler);
835 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800836
John Spurlockbf991a82013-06-24 14:20:23 -0400837 mDataConnectionStats = new DataConnectionStats(mContext);
838 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400839
Jason Monkdecd2952013-10-10 14:02:51 -0400840 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700841
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400842 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900843
844 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900845 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
846 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900847
848 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
849 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
850 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
851 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
852 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
853 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
854 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700856
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900857 private NetworkRequest createInternetRequestForTransport(
858 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900859 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900860 netCap.addCapability(NET_CAPABILITY_INTERNET);
861 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900862 if (transportType > -1) {
863 netCap.addTransportType(transportType);
864 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900865 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900866 }
867
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900868 // Used only for testing.
869 // TODO: Delete this and either:
870 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
871 // changing ContentResolver to make registerContentObserver non-final).
872 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
873 // by subclassing SettingsObserver.
874 @VisibleForTesting
875 void updateMobileDataAlwaysOn() {
876 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
877 }
878
Erik Klineda4bfa82015-04-30 12:58:40 +0900879 private void handleMobileDataAlwaysOn() {
880 final boolean enable = (Settings.Global.getInt(
881 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
882 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
883 if (enable == isEnabled) {
884 return; // Nothing to do.
885 }
886
887 if (enable) {
888 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900889 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900890 } else {
891 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
892 }
893 }
894
895 private void registerSettingsCallbacks() {
896 // Watch for global HTTP proxy changes.
897 mSettingsObserver.observe(
898 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
899 EVENT_APPLY_GLOBAL_HTTP_PROXY);
900
901 // Watch for whether or not to keep mobile data always on.
902 mSettingsObserver.observe(
903 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
904 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
905 }
906
Robert Greenwalt34524f02014-05-18 16:22:10 -0700907 private synchronized int nextNetworkRequestId() {
908 return mNextNetworkRequestId++;
909 }
910
Paul Jensen67b0b072015-06-10 11:22:17 -0400911 @VisibleForTesting
912 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400913 synchronized (mNetworkForNetId) {
914 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
915 int netId = mNextNetId;
916 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
917 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500918 if (!mNetIdInUse.get(netId)) {
919 mNetIdInUse.put(netId, true);
920 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400921 }
922 }
923 }
924 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700925 }
926
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600927 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800928 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600929 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
930 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800931 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600932 state = nai.getNetworkState();
933 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600935 final NetworkInfo info = new NetworkInfo(networkType, 0,
936 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800937 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
938 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600939 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
940 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800941 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600942 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600943 return state;
944 } else {
945 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800946 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400947 }
948
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800949 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
950 if (network == null) {
951 return null;
952 }
953 synchronized (mNetworkForNetId) {
954 return mNetworkForNetId.get(network.netId);
955 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600956 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800957
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900958 private Network[] getVpnUnderlyingNetworks(int uid) {
959 if (!mLockdownEnabled) {
960 int user = UserHandle.getUserId(uid);
961 synchronized (mVpns) {
962 Vpn vpn = mVpns.get(user);
963 if (vpn != null && vpn.appliesToUid(uid)) {
964 return vpn.getUnderlyingNetworks();
965 }
966 }
967 }
968 return null;
969 }
970
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800971 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400972 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800973
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900974 final Network[] networks = getVpnUnderlyingNetworks(uid);
975 if (networks != null) {
976 // getUnderlyingNetworks() returns:
977 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
978 // empty array => the VPN explicitly said "no default network".
979 // non-empty array => the VPN specified one or more default networks; we use the
980 // first one.
981 if (networks.length > 0) {
982 nai = getNetworkAgentInfoForNetwork(networks[0]);
983 } else {
984 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800985 }
986 }
987
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800988 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600989 return nai.getNetworkState();
990 } else {
991 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800992 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400993 }
994
995 /**
996 * Check if UID should be blocked from using the network with the given LinkProperties.
997 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600998 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
999 boolean ignoreBlocked) {
1000 // Networks aren't blocked when ignoring blocked status
1001 if (ignoreBlocked) return false;
1002 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001003 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001004
1005 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001006 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001007
Robin Lee17e61832016-05-09 13:46:28 +01001008 synchronized (mVpns) {
1009 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1010 if (vpn != null && vpn.isBlockingUid(uid)) {
1011 return true;
1012 }
1013 }
1014
Robert Greenwalt12e67352014-05-13 21:41:06 -07001015 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001016 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001017 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001018 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001020
Felipe Lemed31a97f2016-05-06 14:53:50 -07001021 boolean allowed = true;
1022 // Check Data Saver Mode first...
1023 if (networkMetered) {
1024 if ((uidRules & RULE_REJECT_METERED) != 0) {
1025 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1026 // Explicitly blacklisted.
1027 allowed = false;
1028 } else {
1029 allowed = !mRestrictBackground
1030 || (uidRules & RULE_ALLOW_METERED) != 0
1031 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1032 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1033 + " mRestrictBackground=" + mRestrictBackground
1034 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1035 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1036 + ": " + allowed);
1037 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001038 }
Felipe Leme781ba142016-05-09 16:24:48 -07001039 // ...then power restrictions.
1040 if (allowed) {
1041 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001042 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001043 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001044 }
1045 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001046 }
1047
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001048 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001049 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1050 return;
1051 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001052 boolean removed = false;
1053 boolean added = false;
1054 synchronized (mBlockedAppUids) {
1055 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1056 added = true;
1057 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1058 removed = true;
1059 }
1060 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001061 if (added) {
1062 log("Returning blocked NetworkInfo to uid=" + uid);
1063 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1064 } else if (removed) {
1065 log("Returning unblocked NetworkInfo to uid=" + uid);
1066 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1067 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001068 }
1069
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001070 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001071 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1072 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1073 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1074 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001075 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001076 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001077 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1078
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001079 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001080 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001081 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001082 if (mLockdownTracker != null) {
1083 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001084 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001085
1086 // TODO: apply metered state closer to NetworkAgentInfo
1087 final long token = Binder.clearCallingIdentity();
1088 try {
1089 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1090 } catch (RemoteException e) {
1091 } finally {
1092 Binder.restoreCallingIdentity(token);
1093 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001094 }
1095
1096 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 * Return NetworkInfo for the active (i.e., connected) network interface.
1098 * It is assumed that at most one network is active at a time. If more
1099 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001100 * @return the info for the active network, or {@code null} if none is
1101 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001103 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001105 enforceAccessPermission();
1106 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001107 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001108 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001109 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1110 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 }
1112
Paul Jensen31a94f42015-02-13 14:18:39 -05001113 @Override
1114 public Network getActiveNetwork() {
1115 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001116 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001117 }
1118
1119 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001120 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001121 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001123 }
1124
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001125 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001126 final int user = UserHandle.getUserId(uid);
1127 int vpnNetId = NETID_UNSET;
1128 synchronized (mVpns) {
1129 final Vpn vpn = mVpns.get(user);
1130 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1131 }
1132 NetworkAgentInfo nai;
1133 if (vpnNetId != NETID_UNSET) {
1134 synchronized (mNetworkForNetId) {
1135 nai = mNetworkForNetId.get(vpnNetId);
1136 }
1137 if (nai != null) return nai.network;
1138 }
1139 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001140 if (nai != null
1141 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1142 nai = null;
1143 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001144 return nai != null ? nai.network : null;
1145 }
1146
Lorenzo Colitti18660282016-07-04 12:55:44 +09001147 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001148 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1149 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001150 final int uid = Binder.getCallingUid();
1151 NetworkState state = getUnfilteredActiveNetworkState(uid);
1152 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001153 }
1154
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001155 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001156 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001158 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001159 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001160 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001161 }
1162
1163 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 public NetworkInfo getNetworkInfo(int networkType) {
1165 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001166 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001167 if (getVpnUnderlyingNetworks(uid) != null) {
1168 // A VPN is active, so we may need to return one of its underlying networks. This
1169 // information is not available in LegacyTypeTracker, so we have to get it from
1170 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001171 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001172 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001173 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001174 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001175 }
1176 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001177 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001178 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 }
1180
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001181 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001182 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001183 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001184 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001185 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001186 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001187 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001188 return state.networkInfo;
1189 } else {
1190 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001191 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001192 }
1193
1194 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 public NetworkInfo[] getAllNetworkInfo() {
1196 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001197 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001198 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1199 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001200 NetworkInfo info = getNetworkInfo(networkType);
1201 if (info != null) {
1202 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001205 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
1207
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001208 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001209 public Network getNetworkForType(int networkType) {
1210 enforceAccessPermission();
1211 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001212 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1213 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001214 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001215 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001216 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001217 }
1218
1219 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001220 public Network[] getAllNetworks() {
1221 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001222 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001223 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001224 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001225 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001226 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001227 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001228 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001229 }
1230
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001231 @Override
1232 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1233 // The basic principle is: if an app's traffic could possibly go over a
1234 // network, without the app doing anything multinetwork-specific,
1235 // (hence, by "default"), then include that network's capabilities in
1236 // the array.
1237 //
1238 // In the normal case, app traffic only goes over the system's default
1239 // network connection, so that's the only network returned.
1240 //
1241 // With a VPN in force, some app traffic may go into the VPN, and thus
1242 // over whatever underlying networks the VPN specifies, while other app
1243 // traffic may go over the system default network (e.g.: a split-tunnel
1244 // VPN, or an app disallowed by the VPN), so the set of networks
1245 // returned includes the VPN's underlying networks and the system
1246 // default.
1247 enforceAccessPermission();
1248
1249 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1250
1251 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001252 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001253 if (nc != null) {
1254 result.put(nai.network, nc);
1255 }
1256
1257 if (!mLockdownEnabled) {
1258 synchronized (mVpns) {
1259 Vpn vpn = mVpns.get(userId);
1260 if (vpn != null) {
1261 Network[] networks = vpn.getUnderlyingNetworks();
1262 if (networks != null) {
1263 for (Network network : networks) {
1264 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001265 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001266 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001267 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001268 }
1269 }
1270 }
1271 }
1272 }
1273 }
1274
1275 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1276 out = result.values().toArray(out);
1277 return out;
1278 }
1279
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001280 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001281 public boolean isNetworkSupported(int networkType) {
1282 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001283 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001284 }
1285
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001286 /**
1287 * Return LinkProperties for the active (i.e., connected) default
1288 * network interface. It is assumed that at most one default network
1289 * is active at a time. If more than one is active, it is indeterminate
1290 * which will be returned.
1291 * @return the ip properties for the active network, or {@code null} if
1292 * none is active
1293 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001294 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001295 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001296 enforceAccessPermission();
1297 final int uid = Binder.getCallingUid();
1298 NetworkState state = getUnfilteredActiveNetworkState(uid);
1299 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001300 }
1301
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001302 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001303 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001304 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001305 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1306 if (nai != null) {
1307 synchronized (nai) {
1308 return new LinkProperties(nai.linkProperties);
1309 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001310 }
1311 return null;
1312 }
1313
Robert Greenwalt12e67352014-05-13 21:41:06 -07001314 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001315 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001316 public LinkProperties getLinkProperties(Network network) {
1317 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001318 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001319 if (nai != null) {
1320 synchronized (nai) {
1321 return new LinkProperties(nai.linkProperties);
1322 }
1323 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001324 return null;
1325 }
1326
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001327 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001328 if (nai != null) {
1329 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001330 if (nai.networkCapabilities != null) {
1331 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001332 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001333 }
1334 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001335 return null;
1336 }
1337
1338 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001339 public NetworkCapabilities getNetworkCapabilities(Network network) {
1340 enforceAccessPermission();
1341 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1342 }
1343
1344 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001345 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001346 // Require internal since we're handing out IMSI details
1347 enforceConnectivityInternalPermission();
1348
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001349 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001350 for (Network network : getAllNetworks()) {
1351 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1352 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001353 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001354 }
1355 }
1356 return result.toArray(new NetworkState[result.size()]);
1357 }
1358
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001359 @Override
1360 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1361 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001362 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001363 final long token = Binder.clearCallingIdentity();
1364 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001365 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1366 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001367 try {
1368 return mPolicyManager.getNetworkQuotaInfo(state);
1369 } catch (RemoteException e) {
1370 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001371 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001372 return null;
1373 } finally {
1374 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001375 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001376 }
1377
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001378 @Override
1379 public boolean isActiveNetworkMetered() {
1380 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001381
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001382 final NetworkInfo info = getActiveNetworkInfo();
1383 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001384 }
1385
Jeff Sharkey216c1812012-08-05 14:29:23 -07001386 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1387 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001388 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001389 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001390 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001391 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001392 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001393
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001394 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 * Ensure that a network route exists to deliver traffic to the specified
1396 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001397 * @param networkType the type of the network over which traffic to the
1398 * specified host is to be routed
1399 * @param hostAddress the IP address of the host to which the route is
1400 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 * @return {@code true} on success, {@code false} on failure
1402 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001403 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001404 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001406 if (mProtectedNetworks.contains(networkType)) {
1407 enforceConnectivityInternalPermission();
1408 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001409
Chad Brubakerc0234532014-02-14 13:24:29 -08001410 InetAddress addr;
1411 try {
1412 addr = InetAddress.getByAddress(hostAddress);
1413 } catch (UnknownHostException e) {
1414 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1415 return false;
1416 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001419 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 return false;
1421 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001422
1423 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1424 if (nai == null) {
1425 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1426 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1427 } else {
1428 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1429 }
1430 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001431 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001432
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001433 DetailedState netState;
1434 synchronized (nai) {
1435 netState = nai.networkInfo.getDetailedState();
1436 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001437
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001438 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001439 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001440 log("requestRouteToHostAddress on down network "
1441 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001442 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001443 }
1444 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001446
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001447 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001448 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001449 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001450 LinkProperties lp;
1451 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001452 synchronized (nai) {
1453 lp = nai.linkProperties;
1454 netId = nai.network.netId;
1455 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001456 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001457 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1458 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001459 } finally {
1460 Binder.restoreCallingIdentity(token);
1461 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001462 }
1463
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001464 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001465 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001466 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001467 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001468 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001469 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001470 if (bestRoute.getGateway().equals(addr)) {
1471 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001472 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001473 } else {
1474 // if we will connect to this through another route, add a direct route
1475 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001476 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001477 }
1478 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001479 if (DBG) log("Adding legacy route " + bestRoute +
1480 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001481 try {
1482 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1483 } catch (Exception e) {
1484 // never crash - catch them all
1485 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001486 return false;
1487 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001488 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001491 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1492 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001493 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001494 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001495 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001496 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001497 }
1498
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001499 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001500 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001501 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001502 if (oldRules == uidRules) return;
1503
Felipe Leme781ba142016-05-09 16:24:48 -07001504 if (uidRules == RULE_NONE) {
1505 mUidRules.delete(uid);
1506 } else {
1507 mUidRules.put(uid, uidRules);
1508 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001509 }
1510
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001511 // TODO: notify UID when it has requested targeted updates
1512 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001513
1514 @Override
1515 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001516 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001517 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001518 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001519 }
1520
1521 synchronized (mRulesLock) {
1522 mMeteredIfaces.clear();
1523 for (String iface : meteredIfaces) {
1524 mMeteredIfaces.add(iface);
1525 }
1526 }
1527 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001528
1529 @Override
1530 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1531 // caller is NPMS, since we only register with them
1532 if (LOGD_RULES) {
1533 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1534 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001535
1536 synchronized (mRulesLock) {
1537 mRestrictBackground = restrictBackground;
1538 }
1539
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001540 if (restrictBackground) {
1541 log("onRestrictBackgroundChanged(true): disabling tethering");
1542 mTethering.untetherAll();
1543 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001544 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001545
1546 @Override
1547 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1548 if (LOGD_RULES) {
1549 // caller is NPMS, since we only register with them
1550 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1551 + whitelisted + ")");
1552 }
1553 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001554 @Override
1555 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1556 if (LOGD_RULES) {
1557 // caller is NPMS, since we only register with them
1558 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1559 + blacklisted + ")");
1560 }
1561 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001562 };
1563
Robin Lee3b3dd942015-05-12 18:14:58 +01001564 /**
1565 * Require that the caller is either in the same user or has appropriate permission to interact
1566 * across users.
1567 *
1568 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1569 */
1570 private void enforceCrossUserPermission(int userId) {
1571 if (userId == UserHandle.getCallingUserId()) {
1572 // Not a cross-user call.
1573 return;
1574 }
1575 mContext.enforceCallingOrSelfPermission(
1576 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1577 "ConnectivityService");
1578 }
1579
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001580 private void enforceInternetPermission() {
1581 mContext.enforceCallingOrSelfPermission(
1582 android.Manifest.permission.INTERNET,
1583 "ConnectivityService");
1584 }
1585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001587 mContext.enforceCallingOrSelfPermission(
1588 android.Manifest.permission.ACCESS_NETWORK_STATE,
1589 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 }
1591
1592 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001593 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
1595
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001596 private void enforceTetherAccessPermission() {
1597 mContext.enforceCallingOrSelfPermission(
1598 android.Manifest.permission.ACCESS_NETWORK_STATE,
1599 "ConnectivityService");
1600 }
1601
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001602 private void enforceConnectivityInternalPermission() {
1603 mContext.enforceCallingOrSelfPermission(
1604 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1605 "ConnectivityService");
1606 }
1607
Hugo Benichi514da602016-07-19 15:59:27 +09001608 private void enforceConnectivityRestrictedNetworksPermission() {
1609 try {
1610 mContext.enforceCallingOrSelfPermission(
1611 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1612 "ConnectivityService");
1613 return;
1614 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1615 enforceConnectivityInternalPermission();
1616 }
1617
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001618 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001619 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001620 }
1621
Lorenzo Colitti18660282016-07-04 12:55:44 +09001622 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001623 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001624 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001625 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001626 }
1627
1628 private void sendInetConditionBroadcast(NetworkInfo info) {
1629 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1630 }
1631
Wink Saville628b0852011-08-04 15:01:58 -07001632 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001633 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001634 info = new NetworkInfo(info);
1635 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001636 }
1637
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001638 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001639 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001640 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 if (info.isFailover()) {
1642 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1643 info.setFailover(false);
1644 }
1645 if (info.getReason() != null) {
1646 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1647 }
1648 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001649 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1650 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001652 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001653 return intent;
1654 }
1655
1656 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1657 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1658 }
1659
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001660 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001661 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1662 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1663 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001664 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001665 final long ident = Binder.clearCallingIdentity();
1666 try {
1667 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1668 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1669 } finally {
1670 Binder.restoreCallingIdentity(ident);
1671 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001672 }
1673
Mike Lockwood0f79b542009-08-14 14:18:49 -04001674 private void sendStickyBroadcast(Intent intent) {
1675 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001676 if (!mSystemReady) {
1677 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001678 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001679 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001680 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001681 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001682 }
1683
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001684 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001685 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001686 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001687 final NetworkInfo ni = intent.getParcelableExtra(
1688 ConnectivityManager.EXTRA_NETWORK_INFO);
1689 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1690 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1691 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001692 } else {
1693 BroadcastOptions opts = BroadcastOptions.makeBasic();
1694 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1695 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001696 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001697 final IBatteryStats bs = BatteryStatsService.getService();
1698 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001699 bs.noteConnectivityChanged(intent.getIntExtra(
1700 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1701 ni != null ? ni.getState().toString() : "?");
1702 } catch (RemoteException e) {
1703 }
1704 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001705 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001706 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001707 } finally {
1708 Binder.restoreCallingIdentity(ident);
1709 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001710 }
1711 }
1712
1713 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001714 loadGlobalProxy();
1715
Mike Lockwood0f79b542009-08-14 14:18:49 -04001716 synchronized(this) {
1717 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001718 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001719 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001720 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001721 }
1722 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001723 // load the global proxy at startup
1724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001725
Robin Lee244ce8e2016-01-05 18:03:46 +00001726 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1727 // for user to unlock device too.
1728 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001729
Erik Klineda4bfa82015-04-30 12:58:40 +09001730 // Configure whether mobile data is always on.
1731 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1732
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001733 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001734
1735 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 }
1737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001739 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001740 *
1741 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001742 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001743 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001744 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1745 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001746
1747 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001748 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001749
Robert Greenwalt7b816022014-04-18 15:25:25 -07001750 if (networkAgent.networkCapabilities.hasTransport(
1751 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001752 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1753 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001754 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001755 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001756 } else if (networkAgent.networkCapabilities.hasTransport(
1757 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001758 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1759 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001760 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001761 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001762 } else {
1763 // do not track any other networks
1764 timeout = 0;
1765 }
1766
Robert Greenwalt7b816022014-04-18 15:25:25 -07001767 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001768 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001769 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001770 } catch (Exception e) {
1771 // You shall not crash!
1772 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001773 }
1774 }
1775 }
1776
1777 /**
1778 * Remove data activity tracking when network disconnects.
1779 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001780 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1781 final String iface = networkAgent.linkProperties.getInterfaceName();
1782 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001783
Robert Greenwalt7b816022014-04-18 15:25:25 -07001784 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1785 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001786 try {
1787 // the call fails silently if no idletimer setup for this interface
1788 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001789 } catch (Exception e) {
1790 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001791 }
1792 }
1793 }
1794
1795 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001796 * Reads the network specific MTU size from reources.
1797 * and set it on it's iface.
1798 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001799 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1800 final String iface = newLp.getInterfaceName();
1801 final int mtu = newLp.getMtu();
1802 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1803 if (VDBG) log("identical MTU - not setting");
1804 return;
1805 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001806
Robert Greenwalt43074032014-08-15 17:53:05 -07001807 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001808 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001809 return;
1810 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001811
w1997615afd812014-08-05 15:18:11 -07001812 // Cannot set MTU without interface name
1813 if (TextUtils.isEmpty(iface)) {
1814 loge("Setting MTU size with null iface.");
1815 return;
1816 }
1817
Robert Greenwalt7b816022014-04-18 15:25:25 -07001818 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001819 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001820 mNetd.setMtu(iface, mtu);
1821 } catch (Exception e) {
1822 Slog.e(TAG, "exception in setMtu()" + e);
1823 }
1824 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001825
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001826 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001827 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1828
1829 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001830 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001831 protected int getDefaultTcpRwnd() {
1832 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1833 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001834
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001835 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1836 if (isDefaultNetwork(nai) == false) {
1837 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001838 }
1839
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001840 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1841 String[] values = null;
1842 if (tcpBufferSizes != null) {
1843 values = tcpBufferSizes.split(",");
1844 }
1845
1846 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001847 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001848 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1849 values = tcpBufferSizes.split(",");
1850 }
1851
1852 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1853
1854 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001855 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001856
1857 final String prefix = "/sys/kernel/ipv4/tcp_";
1858 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1859 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1860 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1861 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1862 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1863 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1864 mCurrentTcpBufferSizes = tcpBufferSizes;
1865 } catch (IOException e) {
1866 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001867 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001868
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001869 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001870 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001871 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1872 if (rwndValue != 0) {
1873 SystemProperties.set(sysctlKey, rwndValue.toString());
1874 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001875 }
1876
Mattias Falk8b47b362011-08-23 14:15:13 +02001877 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001878 /*
1879 * Tell the VMs to toss their DNS caches
1880 */
1881 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1882 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001883 /*
1884 * Connectivity events can happen before boot has completed ...
1885 */
1886 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001887 final long ident = Binder.clearCallingIdentity();
1888 try {
1889 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1890 } finally {
1891 Binder.restoreCallingIdentity(ident);
1892 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001893 }
1894
Robert Greenwalt562cc542014-05-15 18:07:26 -07001895 @Override
1896 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001897 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1898 NETWORK_RESTORE_DELAY_PROP_NAME);
1899 if(restoreDefaultNetworkDelayStr != null &&
1900 restoreDefaultNetworkDelayStr.length() != 0) {
1901 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001902 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001903 } catch (NumberFormatException e) {
1904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001906 // if the system property isn't set, use the value for the apn type
1907 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1908
1909 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1910 (mNetConfigs[networkType] != null)) {
1911 ret = mNetConfigs[networkType].restoreTime;
1912 }
1913 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 }
1915
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001916 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001917 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001918 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001919 }
1920 return false;
1921 }
1922
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001923 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1924 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1925 final long DIAG_TIME_MS = 5000;
1926 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1927 // Start gathering diagnostic information.
1928 netDiags.add(new NetworkDiagnostics(
1929 nai.network,
1930 new LinkProperties(nai.linkProperties), // Must be a copy.
1931 DIAG_TIME_MS));
1932 }
1933
1934 for (NetworkDiagnostics netDiag : netDiags) {
1935 pw.println();
1936 netDiag.waitForMeasurements();
1937 netDiag.dump(pw);
1938 }
1939 }
1940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001942 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1943 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001944 if (mContext.checkCallingOrSelfPermission(
1945 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001947 pw.println("Permission Denial: can't dump ConnectivityService " +
1948 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1949 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 return;
1951 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001952
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001953 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001954 dumpNetworkDiagnostics(pw);
1955 return;
1956 }
Erik Kline379747a2015-06-05 17:47:34 +09001957
Lorenzo Colittie3805462015-06-03 11:18:24 +09001958 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001959 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001960 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001961 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001962 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001963 pw.println();
1964
Paul Jensen85cf78e2015-06-25 13:25:07 -04001965 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001966 pw.print("Active default network: ");
1967 if (defaultNai == null) {
1968 pw.println("none");
1969 } else {
1970 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001972 pw.println();
1973
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001974 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001975 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001976 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1977 pw.println(nai.toString());
1978 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001979 pw.println(String.format(
1980 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1981 nai.numForegroundNetworkRequests(),
1982 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1983 nai.numBackgroundNetworkRequests(),
1984 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001985 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001986 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1987 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001988 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001989 pw.decreaseIndent();
1990 pw.println("Lingered:");
1991 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001992 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001993 pw.decreaseIndent();
1994 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001995 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001996 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001997 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001998
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001999 pw.println("Metered Interfaces:");
2000 pw.increaseIndent();
2001 for (String value : mMeteredIfaces) {
2002 pw.println(value);
2003 }
2004 pw.decreaseIndent();
2005 pw.println();
2006
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002007 pw.print("Restrict background: ");
2008 pw.println(mRestrictBackground);
2009 pw.println();
2010
Felipe Leme46c4fc32016-05-04 09:21:43 -07002011 pw.println("Status for known UIDs:");
2012 pw.increaseIndent();
2013 final int size = mUidRules.size();
2014 for (int i = 0; i < size; i++) {
2015 final int uid = mUidRules.keyAt(i);
2016 pw.print("UID=");
2017 pw.print(uid);
2018 final int uidRules = mUidRules.get(uid, RULE_NONE);
2019 pw.print(" rules=");
2020 pw.print(uidRulesToString(uidRules));
2021 pw.println();
2022 }
2023 pw.println();
2024 pw.decreaseIndent();
2025
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002026 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002027 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002028 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2029 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002030 }
2031 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002032 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002033
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002034 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002035
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002036 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002037 pw.print("mNetTransitionWakeLock: currently " +
2038 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2039 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2040 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2041 } else {
2042 pw.println(", last requested never");
2043 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002044 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002045
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002046 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002047 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002048
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002049 pw.println();
2050 mKeepaliveTracker.dump(pw);
2051
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002052 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002053
Lorenzo Colittie3805462015-06-03 11:18:24 +09002054 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002055 pw.println();
2056 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002057 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002058 for(int i = 0; i < mInetLog.size(); i++) {
2059 pw.println(mInetLog.get(i));
2060 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002061 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002062 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002063
2064 if (argsContain(args, "--short") == false) {
2065 pw.println();
2066 synchronized (mValidationLogs) {
2067 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002068 for (ValidationLog p : mValidationLogs) {
2069 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002070 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002071 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002072 pw.decreaseIndent();
2073 }
2074 }
Erik Kline7523eb32015-07-09 18:24:03 +09002075
2076 pw.println();
2077 pw.println("mNetworkRequestInfoLogs (most recent first):");
2078 pw.increaseIndent();
2079 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2080 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002081
2082 pw.println();
2083 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2084 pw.increaseIndent();
2085 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2086 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002090 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002091 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002092 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002093 if (officialNai != null && officialNai.equals(nai)) return true;
2094 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002095 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002096 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002097 " - " + nai);
2098 }
2099 return false;
2100 }
2101
Robert Greenwalt42acef32009-08-12 16:08:25 -07002102 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002103 private class NetworkStateTrackerHandler extends Handler {
2104 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002105 super(looper);
2106 }
2107
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002108 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002110 default:
2111 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002112 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002113 handleAsyncChannelHalfConnect(msg);
2114 break;
2115 }
2116 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2117 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2118 if (nai != null) nai.asyncChannel.disconnect();
2119 break;
2120 }
2121 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2122 handleAsyncChannelDisconnected(msg);
2123 break;
2124 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002125 }
2126 return true;
2127 }
2128
2129 private void maybeHandleNetworkAgentMessage(Message msg) {
2130 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2131 if (nai == null) {
2132 if (VDBG) {
2133 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2134 log(String.format("%s from unknown NetworkAgent", what));
2135 }
2136 return;
2137 }
2138
2139 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002140 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002141 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2142 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002143 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2144 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002145 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002146 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002147 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002148 break;
2149 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002151 if (VDBG) {
2152 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002153 "; created=" + nai.created +
2154 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002155 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002156 LinkProperties oldLp = nai.linkProperties;
2157 synchronized (nai) {
2158 nai.linkProperties = (LinkProperties)msg.obj;
2159 }
Robin Lee585e2482016-05-01 23:00:00 +01002160 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002161 break;
2162 }
2163 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002164 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002165 updateNetworkInfo(nai, info);
2166 break;
2167 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002168 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002169 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002170 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002171 break;
2172 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002173 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002174 try {
2175 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002176 } catch (Exception e) {
2177 // Never crash!
2178 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002179 }
2180 break;
2181 }
2182 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002183 try {
2184 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002185 } catch (Exception e) {
2186 // Never crash!
2187 loge("Exception in removeVpnUidRanges: " + e);
2188 }
2189 break;
2190 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002191 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002192 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2193 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002194 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002195 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002196 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002197 break;
2198 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002199 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002200 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2201 break;
2202 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002203 }
2204 }
2205
2206 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2207 switch (msg.what) {
2208 default:
2209 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002210 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002211 final NetworkAgentInfo nai;
2212 synchronized (mNetworkForNetId) {
2213 nai = mNetworkForNetId.get(msg.arg2);
2214 }
2215 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002216 final boolean valid =
2217 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002218 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2219 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002220 if (valid != nai.lastValidated) {
2221 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002222 nai.lastValidated = valid;
2223 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002224 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002225 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2226 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002227 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002228 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002229 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002230 Bundle redirectUrlBundle = new Bundle();
2231 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002232 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002233 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002234 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002235 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002236 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002237 break;
2238 }
Paul Jensen869868be2014-05-15 10:33:05 -04002239 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002240 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002241 final boolean visible = (msg.arg1 != 0);
2242 final NetworkAgentInfo nai;
2243 synchronized (mNetworkForNetId) {
2244 nai = mNetworkForNetId.get(netId);
2245 }
2246 // If captive portal status has changed, update capabilities.
2247 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002248 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002249 nai.lastCaptivePortalDetected = visible;
2250 nai.everCaptivePortalDetected |= visible;
Hugo Benichif15b2822016-09-15 18:18:48 +09002251 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002252 }
2253 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002254 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002255 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002256 if (nai == null) {
2257 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2258 break;
2259 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002260 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002261 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002262 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002263 }
Paul Jensen869868be2014-05-15 10:33:05 -04002264 }
Paul Jensen869868be2014-05-15 10:33:05 -04002265 break;
2266 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002267 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002268 return true;
2269 }
2270
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002271 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2272 switch (msg.what) {
2273 default:
2274 return false;
2275 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2276 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2277 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2278 handleLingerComplete(nai);
2279 }
2280 break;
2281 }
2282 }
2283 return true;
2284 }
2285
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002286 @Override
2287 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002288 if (!maybeHandleAsyncChannelMessage(msg) &&
2289 !maybeHandleNetworkMonitorMessage(msg) &&
2290 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002291 maybeHandleNetworkAgentMessage(msg);
2292 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002293 }
2294 }
2295
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002296 private void updateLingerState(NetworkAgentInfo nai, long now) {
2297 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2298 // 2. If the network was lingering and there are now requests, unlinger it.
2299 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2300 // one lingered request, start lingering.
2301 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002302 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002303 if (DBG) log("Unlingering " + nai.name());
2304 nai.unlinger();
2305 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002306 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002307 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002308 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002309 nai.linger();
2310 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2311 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2312 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002313 }
2314
Robert Greenwalt7b816022014-04-18 15:25:25 -07002315 private void handleAsyncChannelHalfConnect(Message msg) {
2316 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002317 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002318 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2319 if (VDBG) log("NetworkFactory connected");
2320 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002321 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002322 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002323 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002324 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002325 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002326 }
2327 } else {
2328 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002329 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002330 }
2331 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2332 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2333 if (VDBG) log("NetworkAgent connected");
2334 // A network agent has requested a connection. Establish the connection.
2335 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2336 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2337 } else {
2338 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002339 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002340 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002341 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002342 synchronized (mNetworkForNetId) {
2343 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002344 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002345 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002346 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002347 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002348 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349 }
2350 }
2351 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002352
Robert Greenwalt7b816022014-04-18 15:25:25 -07002353 private void handleAsyncChannelDisconnected(Message msg) {
2354 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2355 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002356 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002357 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002358 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002359 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002360 // TODO - if we move the logic to the network agent (have them disconnect
2361 // because they lost all their requests or because their score isn't good)
2362 // then they would disconnect organically, report their new state and then
2363 // disconnect the channel.
2364 if (nai.networkInfo.isConnected()) {
2365 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2366 null, null);
2367 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002368 final boolean wasDefault = isDefaultNetwork(nai);
2369 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002370 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002371 // Log default network disconnection before required book-keeping.
2372 // Let rematchAllNetworksAndRequests() below record a new default network event
2373 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2374 // whose timestamps tell how long it takes to recover a default network.
2375 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002376 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002377 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002378 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2379 // by other networks that are already connected. Perhaps that can be done by
2380 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2381 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002382 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002383 mKeepaliveTracker.handleStopAllKeepalives(nai,
2384 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002385 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002386 mNetworkAgentInfos.remove(msg.replyTo);
2387 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002388 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002389 // Remove the NetworkAgent, but don't mark the netId as
2390 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002391 mNetworkForNetId.remove(nai.network.netId);
2392 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002393 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002394 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2395 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002396 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2397 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2398 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002399 sendUpdatedScoreToFactories(request, 0);
2400 }
2401 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002402 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002403 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002404 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002405 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002406 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002407 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002408 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002409 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002410 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002411 if (nai.created) {
2412 // Tell netd to clean up the configuration for this network
2413 // (routing rules, DNS, etc).
2414 // This may be slow as it requires a lot of netd shelling out to ip and
2415 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2416 // after we've rematched networks with requests which should make a potential
2417 // fallback network the default or requested a new network from the
2418 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2419 // long time.
2420 try {
2421 mNetd.removeNetwork(nai.network.netId);
2422 } catch (Exception e) {
2423 loge("Exception removing network: " + e);
2424 }
2425 }
2426 synchronized (mNetworkForNetId) {
2427 mNetIdInUse.delete(nai.network.netId);
2428 }
2429 } else {
2430 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2431 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002432 }
2433 }
2434
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002435 // If this method proves to be too slow then we can maintain a separate
2436 // pendingIntent => NetworkRequestInfo map.
2437 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2438 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2439 Intent intent = pendingIntent.getIntent();
2440 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2441 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2442 if (existingPendingIntent != null &&
2443 existingPendingIntent.getIntent().filterEquals(intent)) {
2444 return entry.getValue();
2445 }
2446 }
2447 return null;
2448 }
2449
2450 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2451 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2452
2453 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2454 if (existingRequest != null) { // remove the existing request.
2455 if (DBG) log("Replacing " + existingRequest.request + " with "
2456 + nri.request + " because their intents matched.");
2457 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2458 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002459 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002460 }
2461
Erik Klineda4bfa82015-04-30 12:58:40 +09002462 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002463 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002464 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002465 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002466 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002467 if (nri.request.networkCapabilities.hasSignalStrength() &&
2468 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2469 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002470 }
2471 }
2472 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002473 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002474 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002475 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002476 }
2477 }
2478
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002479 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2480 int callingUid) {
2481 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2482 if (nri != null) {
2483 handleReleaseNetworkRequest(nri.request, callingUid);
2484 }
2485 }
2486
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002487 // Determines whether the network is the best (or could become the best, if it validated), for
2488 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2489 // on the value of reason:
2490 //
2491 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2492 // then it should be torn down.
2493 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2494 // then it should be lingered.
2495 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2496 final int numRequests;
2497 switch (reason) {
2498 case TEARDOWN:
2499 numRequests = nai.numRequestNetworkRequests();
2500 break;
2501 case LINGER:
2502 numRequests = nai.numForegroundNetworkRequests();
2503 break;
2504 default:
2505 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2506 return true;
2507 }
2508
2509 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002510 return false;
2511 }
Paul Jensene0988542015-06-25 15:30:08 -04002512 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002513 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2514 // Background requests don't affect lingering.
2515 continue;
2516 }
2517
Paul Jensene0988542015-06-25 15:30:08 -04002518 // If this Network is already the highest scoring Network for a request, or if
2519 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002520 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002521 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002522 // Note that this catches two important cases:
2523 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2524 // is currently satisfying the request. This is desirable when
2525 // cellular ends up validating but WiFi does not.
2526 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002527 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002528 // WiFi ends up validating and out scoring cellular.
2529 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2530 nai.getCurrentScoreAsValidated())) {
2531 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002532 }
2533 }
Paul Jensene0988542015-06-25 15:30:08 -04002534 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002535 }
2536
Erik Klineacdd6392016-07-07 16:50:58 +09002537 private NetworkRequestInfo getNriForAppRequest(
2538 NetworkRequest request, int callingUid, String requestedOperation) {
2539 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2540
Robert Greenwalt9258c642014-03-26 16:47:06 -07002541 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002542 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002543 log(String.format("UID %d attempted to %s for unowned request %s",
2544 callingUid, requestedOperation, nri));
2545 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002546 }
Erik Klineacdd6392016-07-07 16:50:58 +09002547 }
2548
2549 return nri;
2550 }
2551
2552 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2553 String description, int callbackType) {
2554 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2555 if (nri == null) return;
2556
2557 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2558 // The network that is satisfying this request may have changed since
2559 // the application requested the update.
2560 //
2561 // - If the request is no longer satisfied, don't send any updates.
2562 // - If the request is satisfied by a different network, it is the
2563 // caller's responsibility to check that the Network object in the
2564 // callback matches the network that was returned in the last
2565 // onAvailable() callback for this request.
2566 if (nai == null) return;
2567 callCallbackForRequest(nri, nai, callbackType, 0);
2568 }
2569
2570 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2571 handleRequestCallbackUpdate(request, callingUid,
2572 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2573 }
2574
2575 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2576 handleRequestCallbackUpdate(request, callingUid,
2577 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2578 }
2579
2580 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2581 final NetworkRequestInfo nri = getNriForAppRequest(
2582 request, callingUid, "release NetworkRequest");
2583 if (nri == null) return;
2584
2585 if (VDBG || (DBG && nri.request.isRequest())) log("releasing " + request);
2586 nri.unlinkDeathRecipient();
2587 mNetworkRequests.remove(request);
2588 synchronized (mUidToNetworkRequestCount) {
2589 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2590 if (requests < 1) {
2591 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2592 nri.mUid);
2593 } else if (requests == 1) {
2594 mUidToNetworkRequestCount.removeAt(
2595 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2596 } else {
2597 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2598 }
2599 }
2600 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2601 if (nri.request.isRequest()) {
2602 boolean wasKept = false;
2603 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2604 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002605 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002606 nai.removeRequest(nri.request.requestId);
2607 if (VDBG) {
2608 log(" Removing from current network " + nai.name() +
2609 ", leaving " + nai.numNetworkRequests() + " requests.");
2610 }
2611 // If there are still lingered requests on this network, don't tear it down,
2612 // but resume lingering instead.
2613 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002614 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002615 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2616 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002617 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002618 wasKept = true;
2619 }
2620 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002621 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2622 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002623 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002624 }
Erik Klineacdd6392016-07-07 16:50:58 +09002625 }
2626
2627 // TODO: remove this code once we know that the Slog.wtf is never hit.
2628 //
2629 // Find all networks that are satisfying this request and remove the request
2630 // from their request lists.
2631 // TODO - it's my understanding that for a request there is only a single
2632 // network satisfying it, so this loop is wasteful
2633 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2634 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2635 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2636 otherNai.name() + ", but mNetworkAgentInfos says " +
2637 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002638 }
2639 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002640
Erik Klineacdd6392016-07-07 16:50:58 +09002641 // Maintain the illusion. When this request arrived, we might have pretended
2642 // that a network connected to serve it, even though the network was already
2643 // connected. Now that this request has gone away, we might have to pretend
2644 // that the network disconnected. LegacyTypeTracker will generate that
2645 // phantom disconnect for this type.
2646 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2647 boolean doRemove = true;
2648 if (wasKept) {
2649 // check if any of the remaining requests for this network are for the
2650 // same legacy type - if so, don't remove the nai
2651 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2652 NetworkRequest otherRequest = nai.requestAt(i);
2653 if (otherRequest.legacyType == nri.request.legacyType &&
2654 otherRequest.isRequest()) {
2655 if (DBG) log(" still have other legacy request - leaving");
2656 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002657 }
2658 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002659 }
2660
Erik Klineacdd6392016-07-07 16:50:58 +09002661 if (doRemove) {
2662 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002663 }
2664 }
Erik Klineacdd6392016-07-07 16:50:58 +09002665
2666 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2667 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2668 nri.request);
2669 }
2670 } else {
2671 // listens don't have a singular affectedNetwork. Check all networks to see
2672 // if this listen request applies and remove it.
2673 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2674 nai.removeRequest(nri.request.requestId);
2675 if (nri.request.networkCapabilities.hasSignalStrength() &&
2676 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2677 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2678 }
2679 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002680 }
Erik Klineacdd6392016-07-07 16:50:58 +09002681 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002682 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002683
Lorenzo Colitti18660282016-07-04 12:55:44 +09002684 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002685 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2686 enforceConnectivityInternalPermission();
2687 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2688 accept ? 1 : 0, always ? 1: 0, network));
2689 }
2690
2691 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2692 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2693 " accept=" + accept + " always=" + always);
2694
2695 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2696 if (nai == null) {
2697 // Nothing to do.
2698 return;
2699 }
2700
2701 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002702 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002703 return;
2704 }
2705
2706 if (!nai.networkMisc.explicitlySelected) {
2707 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2708 }
2709
2710 if (accept != nai.networkMisc.acceptUnvalidated) {
2711 int oldScore = nai.getCurrentScore();
2712 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002713 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002714 sendUpdatedScoreToFactories(nai);
2715 }
2716
2717 if (always) {
2718 nai.asyncChannel.sendMessage(
2719 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2720 }
2721
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002722 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002723 // Tell the NetworkAgent to not automatically reconnect to the network.
2724 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2725 // Teardown the nework.
2726 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002727 }
2728
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002729 }
2730
2731 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002732 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002733 mHandler.sendMessageDelayed(
2734 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2735 PROMPT_UNVALIDATED_DELAY_MS);
2736 }
2737
2738 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002739 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002740 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2741
2742 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2743 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002744 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002745 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002746 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2747 return;
2748 }
2749
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002750 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002751 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002752 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2753 intent.setClassName("com.android.settings",
2754 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002755
2756 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2757 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
fionaxu1bf6ec22016-05-23 16:33:16 -07002758
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002759 mNotifier.showNotification(nai.network.netId, NotificationType.NO_INTERNET, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002760 pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002761 }
2762
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002763 private class InternalHandler extends Handler {
2764 public InternalHandler(Looper looper) {
2765 super(looper);
2766 }
2767
2768 @Override
2769 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002770 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002771 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002772 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002773 String causedBy = null;
2774 synchronized (ConnectivityService.this) {
2775 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2776 mNetTransitionWakeLock.isHeld()) {
2777 mNetTransitionWakeLock.release();
2778 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002779 } else {
2780 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002781 }
2782 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002783 if (VDBG) {
2784 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2785 log("Failed to find a new network - expiring NetTransition Wakelock");
2786 } else {
2787 log("NetTransition Wakelock (" +
2788 (causedBy == null ? "unknown" : causedBy) +
2789 " cleared because we found a replacement network");
2790 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002791 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002792 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002793 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002794 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002795 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002796 break;
2797 }
Jason Monkdecd2952013-10-10 14:02:51 -04002798 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002799 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002800 break;
2801 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002802 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002803 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2804 break;
2805 }
2806 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2807 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002808 break;
2809 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002810 case EVENT_REGISTER_NETWORK_AGENT: {
2811 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2812 break;
2813 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002814 case EVENT_REGISTER_NETWORK_REQUEST:
2815 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002816 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002817 break;
2818 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002819 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2820 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002821 handleRegisterNetworkRequestWithIntent(msg);
2822 break;
2823 }
2824 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2825 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2826 break;
2827 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002828 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002829 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002830 break;
2831 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002832 case EVENT_SET_ACCEPT_UNVALIDATED: {
2833 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2834 break;
2835 }
2836 case EVENT_PROMPT_UNVALIDATED: {
2837 handlePromptUnvalidated((Network) msg.obj);
2838 break;
2839 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002840 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2841 handleMobileDataAlwaysOn();
2842 break;
2843 }
Erik Klineacdd6392016-07-07 16:50:58 +09002844 case EVENT_REQUEST_LINKPROPERTIES:
2845 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2846 break;
2847 case EVENT_REQUEST_NETCAPABILITIES:
2848 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2849 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002850 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2851 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2852 mKeepaliveTracker.handleStartKeepalive(msg);
2853 break;
2854 }
2855 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2856 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2857 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2858 int slot = msg.arg1;
2859 int reason = msg.arg2;
2860 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2861 break;
2862 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002863 case EVENT_SYSTEM_READY: {
2864 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2865 nai.networkMonitor.systemReady = true;
2866 }
2867 break;
2868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 }
2870 }
2871 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002872
2873 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002874 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002875 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002876 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002877 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002878 final int status = mTethering.tether(iface);
2879 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2880 try {
2881 mPolicyManager.onTetheringChanged(iface, true);
2882 } catch (RemoteException e) {
2883 }
2884 }
2885 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002886 } else {
2887 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2888 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002889 }
2890
2891 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002892 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002893 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002894 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002895
2896 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002897 final int status = mTethering.untether(iface);
2898 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2899 try {
2900 mPolicyManager.onTetheringChanged(iface, false);
2901 } catch (RemoteException e) {
2902 }
2903 }
2904 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002905 } else {
2906 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2907 }
2908 }
2909
2910 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002911 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002912 public int getLastTetherError(String iface) {
2913 enforceTetherAccessPermission();
2914
2915 if (isTetheringSupported()) {
2916 return mTethering.getLastTetherError(iface);
2917 } else {
2918 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2919 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002920 }
2921
2922 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002923 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002924 public String[] getTetherableUsbRegexs() {
2925 enforceTetherAccessPermission();
2926 if (isTetheringSupported()) {
2927 return mTethering.getTetherableUsbRegexs();
2928 } else {
2929 return new String[0];
2930 }
2931 }
2932
Lorenzo Colitti18660282016-07-04 12:55:44 +09002933 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002934 public String[] getTetherableWifiRegexs() {
2935 enforceTetherAccessPermission();
2936 if (isTetheringSupported()) {
2937 return mTethering.getTetherableWifiRegexs();
2938 } else {
2939 return new String[0];
2940 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002941 }
2942
Lorenzo Colitti18660282016-07-04 12:55:44 +09002943 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002944 public String[] getTetherableBluetoothRegexs() {
2945 enforceTetherAccessPermission();
2946 if (isTetheringSupported()) {
2947 return mTethering.getTetherableBluetoothRegexs();
2948 } else {
2949 return new String[0];
2950 }
2951 }
2952
Lorenzo Colitti18660282016-07-04 12:55:44 +09002953 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002954 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002955 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002956 if (isTetheringSupported()) {
2957 return mTethering.setUsbTethering(enable);
2958 } else {
2959 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2960 }
2961 }
2962
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002963 // TODO - move iface listing, queries, etc to new module
2964 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002965 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002966 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002967 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002968 return mTethering.getTetherableIfaces();
2969 }
2970
Lorenzo Colitti18660282016-07-04 12:55:44 +09002971 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002972 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002973 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002974 return mTethering.getTetheredIfaces();
2975 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002976
Lorenzo Colitti18660282016-07-04 12:55:44 +09002977 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002978 public String[] getTetheringErroredIfaces() {
2979 enforceTetherAccessPermission();
2980 return mTethering.getErroredIfaces();
2981 }
2982
Lorenzo Colitti18660282016-07-04 12:55:44 +09002983 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002984 public String[] getTetheredDhcpRanges() {
2985 enforceConnectivityInternalPermission();
2986 return mTethering.getTetheredDhcpRanges();
2987 }
2988
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002989 // if ro.tether.denied = true we default to no tethering
2990 // gservices could set the secure setting to 1 though to enable it on a build where it
2991 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002992 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002993 public boolean isTetheringSupported() {
2994 enforceTetherAccessPermission();
2995 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002996 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002997 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2998 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002999 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
3000 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003001 mTethering.getTetherableWifiRegexs().length != 0 ||
3002 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3003 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003004 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003005
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003006 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003007 public void startTethering(int type, ResultReceiver receiver,
3008 boolean showProvisioningUi) {
3009 ConnectivityManager.enforceTetherChangePermission(mContext);
3010 if (!isTetheringSupported()) {
3011 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3012 return;
3013 }
3014 mTethering.startTethering(type, receiver, showProvisioningUi);
3015 }
3016
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003017 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003018 public void stopTethering(int type) {
3019 ConnectivityManager.enforceTetherChangePermission(mContext);
3020 mTethering.stopTethering(type);
3021 }
3022
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003023 // Called when we lose the default network and have no replacement yet.
3024 // This will automatically be cleared after X seconds or a new default network
3025 // becomes CONNECTED, whichever happens first. The timer is started by the
3026 // first caller and not restarted by subsequent callers.
3027 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003028 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003029 synchronized (this) {
3030 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003031 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003032 mNetTransitionWakeLock.acquire();
3033 mNetTransitionWakeLockCausedBy = forWhom;
3034 }
3035 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003036 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003037 mNetTransitionWakeLockTimeout);
3038 return;
3039 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003040
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003041 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003042 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003043 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003044 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003045 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003046 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003047 }
3048
Lorenzo Colitti18660282016-07-04 12:55:44 +09003049 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003050 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003051 enforceAccessPermission();
3052 enforceInternetPermission();
3053
Paul Jensenbfd17b72015-04-07 12:43:13 -04003054 NetworkAgentInfo nai;
3055 if (network == null) {
3056 nai = getDefaultNetwork();
3057 } else {
3058 nai = getNetworkAgentInfoForNetwork(network);
3059 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003060 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3061 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3062 return;
3063 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003064 // Revalidate if the app report does not match our current validated state.
3065 if (hasConnectivity == nai.lastValidated) return;
3066 final int uid = Binder.getCallingUid();
3067 if (DBG) {
3068 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3069 ") by " + uid);
3070 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003071 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003072 // Validating a network that has not yet connected could result in a call to
3073 // rematchNetworkAndRequests() which is not meant to work on such networks.
3074 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003075
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003076 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003077
3078 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3079 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003080 }
3081
Paul Jensencee9b512015-05-06 07:32:40 -04003082 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003083 // this information is already available as a world read/writable jvm property
3084 // so this API change wouldn't have a benifit. It also breaks the passing
3085 // of proxy info to all the JVMs.
3086 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003087 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003088 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003089 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3090 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003091 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003092 }
3093
Lorenzo Colitti18660282016-07-04 12:55:44 +09003094 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003095 public ProxyInfo getProxyForNetwork(Network network) {
3096 if (network == null) return getDefaultProxy();
3097 final ProxyInfo globalProxy = getGlobalProxy();
3098 if (globalProxy != null) return globalProxy;
3099 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3100 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3101 // caller may not have.
3102 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3103 if (nai == null) return null;
3104 synchronized (nai) {
3105 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3106 if (proxyInfo == null) return null;
3107 return new ProxyInfo(proxyInfo);
3108 }
3109 }
3110
Paul Jensene0bef712014-12-10 15:12:18 -05003111 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3112 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3113 // proxy is null then there is no proxy in place).
3114 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3115 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3116 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3117 proxy = null;
3118 }
3119 return proxy;
3120 }
3121
3122 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3123 // better for determining if a new proxy broadcast is necessary:
3124 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3125 // avoid unnecessary broadcasts.
3126 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3127 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3128 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3129 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3130 // all set.
3131 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3132 a = canonicalizeProxyInfo(a);
3133 b = canonicalizeProxyInfo(b);
3134 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3135 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3136 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3137 }
3138
Jason Monk207900c2014-04-25 15:00:09 -04003139 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003140 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003141
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003142 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003143 if (proxyProperties == mGlobalProxy) return;
3144 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3145 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3146
3147 String host = "";
3148 int port = 0;
3149 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003150 String pacFileUrl = "";
3151 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003152 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003153 if (!proxyProperties.isValid()) {
3154 if (DBG)
3155 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3156 return;
3157 }
Jason Monk207900c2014-04-25 15:00:09 -04003158 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003159 host = mGlobalProxy.getHost();
3160 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003161 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003162 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003163 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003164 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003165 } else {
3166 mGlobalProxy = null;
3167 }
3168 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003169 final long token = Binder.clearCallingIdentity();
3170 try {
3171 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3172 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3173 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3174 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003175 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003176 } finally {
3177 Binder.restoreCallingIdentity(token);
3178 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003179
Jason Monkcf0f97a2014-10-02 15:39:38 -04003180 if (mGlobalProxy == null) {
3181 proxyProperties = mDefaultProxy;
3182 }
3183 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003184 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003185 }
3186
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003187 private void loadGlobalProxy() {
3188 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003189 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3190 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3191 String exclList = Settings.Global.getString(res,
3192 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003193 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3194 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003195 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003196 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003197 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003198 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003199 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003200 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003201 if (!proxyProperties.isValid()) {
3202 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3203 return;
3204 }
3205
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003206 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003207 mGlobalProxy = proxyProperties;
3208 }
3209 }
3210 }
3211
Jason Monk207900c2014-04-25 15:00:09 -04003212 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003213 // this information is already available as a world read/writable jvm property
3214 // so this API change wouldn't have a benifit. It also breaks the passing
3215 // of proxy info to all the JVMs.
3216 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003217 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003218 return mGlobalProxy;
3219 }
3220 }
3221
Jason Monk207900c2014-04-25 15:00:09 -04003222 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003223 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003224 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003225 proxy = null;
3226 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003227 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003228 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003229 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003230 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003231 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3232 return;
3233 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003234
3235 // This call could be coming from the PacManager, containing the port of the local
3236 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3237 // global (to get the correct local port), and send a broadcast.
3238 // TODO: Switch PacManager to have its own message to send back rather than
3239 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003240 if ((mGlobalProxy != null) && (proxy != null)
3241 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003242 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3243 mGlobalProxy = proxy;
3244 sendProxyBroadcast(mGlobalProxy);
3245 return;
3246 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003247 mDefaultProxy = proxy;
3248
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003249 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003250 if (!mDefaultProxyDisabled) {
3251 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003252 }
3253 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003254 }
3255
Paul Jensene0bef712014-12-10 15:12:18 -05003256 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3257 // This method gets called when any network changes proxy, but the broadcast only ever contains
3258 // the default proxy (even if it hasn't changed).
3259 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3260 // world where an app might be bound to a non-default network.
3261 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3262 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3263 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3264
3265 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3266 sendProxyBroadcast(getDefaultProxy());
3267 }
3268 }
3269
Robert Greenwalt434203a2010-10-11 16:00:27 -07003270 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003271 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3272 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003273 if (!TextUtils.isEmpty(proxy)) {
3274 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003275 if (data.length == 0) {
3276 return;
3277 }
3278
Robert Greenwalt434203a2010-10-11 16:00:27 -07003279 String proxyHost = data[0];
3280 int proxyPort = 8080;
3281 if (data.length > 1) {
3282 try {
3283 proxyPort = Integer.parseInt(data[1]);
3284 } catch (NumberFormatException e) {
3285 return;
3286 }
3287 }
Jason Monk207900c2014-04-25 15:00:09 -04003288 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003289 setGlobalProxy(p);
3290 }
3291 }
3292
Jason Monk207900c2014-04-25 15:00:09 -04003293 private void sendProxyBroadcast(ProxyInfo proxy) {
3294 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003295 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003296 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003297 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003298 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3299 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003300 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003301 final long ident = Binder.clearCallingIdentity();
3302 try {
3303 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3304 } finally {
3305 Binder.restoreCallingIdentity(ident);
3306 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003307 }
3308
3309 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003310 final private HashMap<Uri, Integer> mUriEventMap;
3311 final private Context mContext;
3312 final private Handler mHandler;
3313
3314 SettingsObserver(Context context, Handler handler) {
3315 super(null);
3316 mUriEventMap = new HashMap<Uri, Integer>();
3317 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003318 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003319 }
3320
Erik Klineda4bfa82015-04-30 12:58:40 +09003321 void observe(Uri uri, int what) {
3322 mUriEventMap.put(uri, what);
3323 final ContentResolver resolver = mContext.getContentResolver();
3324 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003325 }
3326
3327 @Override
3328 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003329 Slog.wtf(TAG, "Should never be reached.");
3330 }
3331
3332 @Override
3333 public void onChange(boolean selfChange, Uri uri) {
3334 final Integer what = mUriEventMap.get(uri);
3335 if (what != null) {
3336 mHandler.obtainMessage(what.intValue()).sendToTarget();
3337 } else {
3338 loge("No matching event to send for URI=" + uri);
3339 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003340 }
3341 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003342
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003343 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003344 Slog.d(TAG, s);
3345 }
3346
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003347 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003348 Slog.e(TAG, s);
3349 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003350
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003351 private static <T> T checkNotNull(T value, String message) {
3352 if (value == null) {
3353 throw new NullPointerException(message);
3354 }
3355 return value;
3356 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003357
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003358 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003359 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003360 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3361 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3362 *
3363 * @param oldPackage Package name of the application which currently controls VPN, which will
3364 * be replaced. If there is no such application, this should should either be
3365 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3366 * @param newPackage Package name of the application which should gain control of VPN, or
3367 * {@code null} to disable.
3368 * @param userId User for whom to prepare the new VPN.
3369 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003370 * @hide
3371 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003372 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003373 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3374 int userId) {
3375 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003376 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003377
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003378 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003379 Vpn vpn = mVpns.get(userId);
3380 if (vpn != null) {
3381 return vpn.prepare(oldPackage, newPackage);
3382 } else {
3383 return false;
3384 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003385 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003386 }
3387
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003388 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003389 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3390 * This method is used by system-privileged apps.
3391 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3392 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3393 *
3394 * @param packageName The package for which authorization state should change.
3395 * @param userId User for whom {@code packageName} is installed.
3396 * @param authorized {@code true} if this app should be able to start a VPN connection without
3397 * explicit user approval, {@code false} if not.
3398 *
Jeff Davidson05542602014-08-11 14:07:27 -07003399 * @hide
3400 */
3401 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003402 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3403 enforceCrossUserPermission(userId);
3404
Jeff Davidson05542602014-08-11 14:07:27 -07003405 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003406 Vpn vpn = mVpns.get(userId);
3407 if (vpn != null) {
3408 vpn.setPackageAuthorization(packageName, authorized);
3409 }
Jeff Davidson05542602014-08-11 14:07:27 -07003410 }
3411 }
3412
3413 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003414 * Configure a TUN interface and return its file descriptor. Parameters
3415 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003416 * and not available in ConnectivityManager. Permissions are checked in
3417 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003418 * @hide
3419 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003420 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003421 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003422 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003423 int user = UserHandle.getUserId(Binder.getCallingUid());
3424 synchronized(mVpns) {
3425 return mVpns.get(user).establish(config);
3426 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003427 }
3428
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003429 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003430 * Start legacy VPN, controlling native daemons as needed. Creates a
3431 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003432 */
3433 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003434 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003435 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003436 final LinkProperties egress = getActiveLinkProperties();
3437 if (egress == null) {
3438 throw new IllegalStateException("Missing active network connection");
3439 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003440 int user = UserHandle.getUserId(Binder.getCallingUid());
3441 synchronized(mVpns) {
3442 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3443 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003444 }
3445
3446 /**
3447 * Return the information of the ongoing legacy VPN. This method is used
3448 * by VpnSettings and not available in ConnectivityManager. Permissions
3449 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003450 */
3451 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003452 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3453 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003454
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003455 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003456 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003457 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003458 }
3459
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003460 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003461 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3462 * and not available in ConnectivityManager.
3463 */
3464 @Override
3465 public VpnInfo[] getAllVpnInfo() {
3466 enforceConnectivityInternalPermission();
3467 if (mLockdownEnabled) {
3468 return new VpnInfo[0];
3469 }
3470
3471 synchronized(mVpns) {
3472 List<VpnInfo> infoList = new ArrayList<>();
3473 for (int i = 0; i < mVpns.size(); i++) {
3474 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3475 if (info != null) {
3476 infoList.add(info);
3477 }
3478 }
3479 return infoList.toArray(new VpnInfo[infoList.size()]);
3480 }
3481 }
3482
3483 /**
3484 * @return VPN information for accounting, or null if we can't retrieve all required
3485 * information, e.g primary underlying iface.
3486 */
3487 @Nullable
3488 private VpnInfo createVpnInfo(Vpn vpn) {
3489 VpnInfo info = vpn.getVpnInfo();
3490 if (info == null) {
3491 return null;
3492 }
3493 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3494 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3495 // the underlyingNetworks list.
3496 if (underlyingNetworks == null) {
3497 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3498 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3499 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3500 }
3501 } else if (underlyingNetworks.length > 0) {
3502 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3503 if (linkProperties != null) {
3504 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3505 }
3506 }
3507 return info.primaryUnderlyingIface == null ? null : info;
3508 }
3509
3510 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003511 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3512 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003513 * Permissions are checked in Vpn class.
3514 * @hide
3515 */
3516 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003517 public VpnConfig getVpnConfig(int userId) {
3518 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003519 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003520 Vpn vpn = mVpns.get(userId);
3521 if (vpn != null) {
3522 return vpn.getVpnConfig();
3523 } else {
3524 return null;
3525 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003526 }
3527 }
3528
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003529 @Override
3530 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003531 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3532 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3533 return false;
3534 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003535
3536 // Tear down existing lockdown if profile was removed
3537 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3538 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003539 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3540 final VpnProfile profile = VpnProfile.decode(
3541 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003542 if (profile == null) {
3543 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3544 setLockdownTracker(null);
3545 return true;
3546 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003547 int user = UserHandle.getUserId(Binder.getCallingUid());
3548 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003549 Vpn vpn = mVpns.get(user);
3550 if (vpn == null) {
3551 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3552 return false;
3553 }
3554 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003555 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003556 } else {
3557 setLockdownTracker(null);
3558 }
3559
3560 return true;
3561 }
3562
3563 /**
3564 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3565 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3566 */
3567 private void setLockdownTracker(LockdownVpnTracker tracker) {
3568 // Shutdown any existing tracker
3569 final LockdownVpnTracker existing = mLockdownTracker;
3570 mLockdownTracker = null;
3571 if (existing != null) {
3572 existing.shutdown();
3573 }
3574
3575 try {
3576 if (tracker != null) {
3577 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003578 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003579 mLockdownTracker = tracker;
3580 mLockdownTracker.init();
3581 } else {
3582 mNetd.setFirewallEnabled(false);
3583 }
3584 } catch (RemoteException e) {
3585 // ignored; NMS lives inside system_server
3586 }
3587 }
3588
3589 private void throwIfLockdownEnabled() {
3590 if (mLockdownEnabled) {
3591 throw new IllegalStateException("Unavailable in lockdown mode");
3592 }
3593 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003594
Robin Lee244ce8e2016-01-05 18:03:46 +00003595 /**
Robin Lee17e61832016-05-09 13:46:28 +01003596 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3597 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003598 *
Robin Lee17e61832016-05-09 13:46:28 +01003599 * @return {@code true} if the service was started, the service was already connected, or there
3600 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003601 */
Robin Lee17e61832016-05-09 13:46:28 +01003602 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003603 synchronized (mVpns) {
3604 Vpn vpn = mVpns.get(userId);
3605 if (vpn == null) {
3606 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3607 // exists already.
3608 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3609 return false;
3610 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003611
Robin Lee812800c2016-05-13 15:38:08 +01003612 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003613 }
3614 }
3615
3616 @Override
Robin Leedc679712016-05-03 13:23:03 +01003617 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003618 enforceConnectivityInternalPermission();
3619 enforceCrossUserPermission(userId);
3620
3621 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3622 if (LockdownVpnTracker.isEnabled()) {
3623 return false;
3624 }
3625
Robin Lee244ce8e2016-01-05 18:03:46 +00003626 synchronized (mVpns) {
3627 Vpn vpn = mVpns.get(userId);
3628 if (vpn == null) {
3629 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3630 return false;
3631 }
Robin Lee17e61832016-05-09 13:46:28 +01003632 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003633 return false;
3634 }
Robin Lee17e61832016-05-09 13:46:28 +01003635 if (!startAlwaysOnVpn(userId)) {
3636 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003637 return false;
3638 }
Robin Lee17e61832016-05-09 13:46:28 +01003639
Robin Lee812800c2016-05-13 15:38:08 +01003640 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003641 }
3642 return true;
3643 }
3644
3645 @Override
3646 public String getAlwaysOnVpnPackage(int userId) {
3647 enforceConnectivityInternalPermission();
3648 enforceCrossUserPermission(userId);
3649
3650 synchronized (mVpns) {
3651 Vpn vpn = mVpns.get(userId);
3652 if (vpn == null) {
3653 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3654 return null;
3655 }
3656 return vpn.getAlwaysOnPackage();
3657 }
3658 }
3659
Wink Savilleab9321d2013-06-29 21:10:57 -07003660 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003661 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003662 // TODO: Remove? Any reason to trigger a provisioning check?
3663 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003664 }
3665
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003666 /** Location to an updatable file listing carrier provisioning urls.
3667 * An example:
3668 *
3669 * <?xml version="1.0" encoding="utf-8"?>
3670 * <provisioningUrls>
3671 * <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 -07003672 * </provisioningUrls>
3673 */
3674 private static final String PROVISIONING_URL_PATH =
3675 "/data/misc/radio/provisioning_urls.xml";
3676 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003677
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003678 /** XML tag for root element. */
3679 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3680 /** XML tag for individual url */
3681 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003682 /** XML attribute for mcc */
3683 private static final String ATTR_MCC = "mcc";
3684 /** XML attribute for mnc */
3685 private static final String ATTR_MNC = "mnc";
3686
Paul Jensen434dde82015-06-11 09:43:30 -04003687 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003688 FileReader fileReader = null;
3689 XmlPullParser parser = null;
3690 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003691
3692 try {
3693 fileReader = new FileReader(mProvisioningUrlFile);
3694 parser = Xml.newPullParser();
3695 parser.setInput(fileReader);
3696 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3697
3698 while (true) {
3699 XmlUtils.nextElement(parser);
3700
3701 String element = parser.getName();
3702 if (element == null) break;
3703
Paul Jensen434dde82015-06-11 09:43:30 -04003704 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003705 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3706 try {
3707 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3708 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3709 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3710 parser.next();
3711 if (parser.getEventType() == XmlPullParser.TEXT) {
3712 return parser.getText();
3713 }
3714 }
3715 }
3716 } catch (NumberFormatException e) {
3717 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3718 }
3719 }
3720 }
3721 return null;
3722 } catch (FileNotFoundException e) {
3723 loge("Carrier Provisioning Urls file not found");
3724 } catch (XmlPullParserException e) {
3725 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3726 } catch (IOException e) {
3727 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3728 } finally {
3729 if (fileReader != null) {
3730 try {
3731 fileReader.close();
3732 } catch (IOException e) {}
3733 }
3734 }
3735 return null;
3736 }
3737
Wink Saville42d4f082013-07-20 20:31:59 -07003738 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003739 public String getMobileProvisioningUrl() {
3740 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003741 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003742 if (TextUtils.isEmpty(url)) {
3743 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003744 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003745 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003746 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003747 }
Wink Saville8cf35602013-07-10 23:00:07 -07003748 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003749 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003750 String phoneNumber = mTelephonyManager.getLine1Number();
3751 if (TextUtils.isEmpty(phoneNumber)) {
3752 phoneNumber = "0000000000";
3753 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003754 url = String.format(url,
3755 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3756 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003757 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003758 }
3759
Wink Savilleab9321d2013-06-29 21:10:57 -07003760 return url;
3761 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003762
Wink Saville948282b2013-08-29 08:55:16 -07003763 @Override
3764 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003765 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003766 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003767 final long ident = Binder.clearCallingIdentity();
3768 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003769 // Concatenate the range of types onto the range of NetIDs.
3770 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3771 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003772 } finally {
3773 Binder.restoreCallingIdentity(ident);
3774 }
Wink Saville948282b2013-08-29 08:55:16 -07003775 }
Wink Saville7788c612013-08-29 14:57:08 -07003776
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003777 @Override
3778 public void setAirplaneMode(boolean enable) {
3779 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003780 final long ident = Binder.clearCallingIdentity();
3781 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003782 final ContentResolver cr = mContext.getContentResolver();
3783 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3784 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3785 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003786 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003787 } finally {
3788 Binder.restoreCallingIdentity(ident);
3789 }
3790 }
3791
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003792 private void onUserStart(int userId) {
3793 synchronized(mVpns) {
3794 Vpn userVpn = mVpns.get(userId);
3795 if (userVpn != null) {
3796 loge("Starting user already has a VPN");
3797 return;
3798 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003799 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003800 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003801
3802 final ContentResolver cr = mContext.getContentResolver();
3803 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3804 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3805 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3806 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3807 if (alwaysOnPackage != null) {
3808 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3809 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003810 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003811 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3812 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003813 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003814 }
3815
3816 private void onUserStop(int userId) {
3817 synchronized(mVpns) {
3818 Vpn userVpn = mVpns.get(userId);
3819 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003820 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003821 return;
3822 }
Robin Lee17e61832016-05-09 13:46:28 +01003823 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003824 mVpns.delete(userId);
3825 }
3826 }
3827
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003828 private void onUserAdded(int userId) {
3829 synchronized(mVpns) {
3830 final int vpnsSize = mVpns.size();
3831 for (int i = 0; i < vpnsSize; i++) {
3832 Vpn vpn = mVpns.valueAt(i);
3833 vpn.onUserAdded(userId);
3834 }
3835 }
3836 }
3837
3838 private void onUserRemoved(int userId) {
3839 synchronized(mVpns) {
3840 final int vpnsSize = mVpns.size();
3841 for (int i = 0; i < vpnsSize; i++) {
3842 Vpn vpn = mVpns.valueAt(i);
3843 vpn.onUserRemoved(userId);
3844 }
3845 }
3846 }
3847
Robin Lee89e7a692016-02-29 14:38:17 +00003848 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003849 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3850 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3851 updateLockdownVpn();
3852 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003853 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003854 }
3855 }
3856
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003857 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3858 @Override
3859 public void onReceive(Context context, Intent intent) {
3860 final String action = intent.getAction();
3861 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3862 if (userId == UserHandle.USER_NULL) return;
3863
Robin Lee323f29d2016-05-04 16:38:06 +01003864 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003865 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003866 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003867 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003868 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3869 onUserAdded(userId);
3870 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3871 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003872 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3873 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003874 }
3875 }
3876 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003877
Robert Greenwalta67be032014-05-16 15:49:14 -07003878 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3879 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003880 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3881 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003882
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003883 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3884 // Map from UID to number of NetworkRequests that UID has filed.
3885 @GuardedBy("mUidToNetworkRequestCount")
3886 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3887
Robert Greenwalta67be032014-05-16 15:49:14 -07003888 private static class NetworkFactoryInfo {
3889 public final String name;
3890 public final Messenger messenger;
3891 public final AsyncChannel asyncChannel;
3892
3893 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3894 this.name = name;
3895 this.messenger = messenger;
3896 this.asyncChannel = asyncChannel;
3897 }
3898 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003899
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003900 private void ensureNetworkRequestHasType(NetworkRequest request) {
3901 if (request.type == NetworkRequest.Type.NONE) {
3902 throw new IllegalArgumentException(
3903 "All NetworkRequests in ConnectivityService must have a type");
3904 }
3905 }
3906
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003907 /**
3908 * Tracks info about the requester.
3909 * Also used to notice when the calling process dies so we can self-expire
3910 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003911 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003912 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003913 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003914 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003915 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003916 final int mPid;
3917 final int mUid;
3918 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003919
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003920 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003921 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003922 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003923 mPendingIntent = pi;
3924 messenger = null;
3925 mBinder = null;
3926 mPid = getCallingPid();
3927 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003928 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003929 }
3930
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003931 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003932 super();
3933 messenger = m;
3934 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003935 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003936 mBinder = binder;
3937 mPid = getCallingPid();
3938 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003939 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003940 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003941
3942 try {
3943 mBinder.linkToDeath(this, 0);
3944 } catch (RemoteException e) {
3945 binderDied();
3946 }
3947 }
3948
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003949 private void enforceRequestCountLimit() {
3950 synchronized (mUidToNetworkRequestCount) {
3951 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3952 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3953 throw new IllegalArgumentException("Too many NetworkRequests filed");
3954 }
3955 mUidToNetworkRequestCount.put(mUid, networkRequests);
3956 }
3957 }
3958
Robert Greenwalt9258c642014-03-26 16:47:06 -07003959 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003960 if (mBinder != null) {
3961 mBinder.unlinkToDeath(this, 0);
3962 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003963 }
3964
3965 public void binderDied() {
3966 log("ConnectivityService NetworkRequestInfo binderDied(" +
3967 request + ", " + mBinder + ")");
3968 releaseNetworkRequest(request);
3969 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003970
3971 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003972 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003973 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003974 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003975 }
3976
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003977 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3978 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3979 if (badCapability != null) {
3980 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003981 }
3982 }
3983
Erik Kline9d598e12015-07-13 16:37:51 +09003984 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003985 final SortedSet<Integer> thresholds = new TreeSet();
3986 synchronized (nai) {
3987 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3988 if (nri.request.networkCapabilities.hasSignalStrength() &&
3989 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3990 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3991 }
3992 }
3993 }
Erik Kline9d598e12015-07-13 16:37:51 +09003994 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003995 }
3996
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003997 private void updateSignalStrengthThresholds(
3998 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3999 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004000 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004001 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4002
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004003 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004004 String detail;
4005 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4006 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4007 } else {
4008 detail = reason;
4009 }
4010 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4011 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4012 }
4013
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004014 nai.asyncChannel.sendMessage(
4015 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004016 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004017 }
4018
Robert Greenwalt9258c642014-03-26 16:47:06 -07004019 @Override
4020 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004021 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004022 final NetworkRequest.Type type = (networkCapabilities == null)
4023 ? NetworkRequest.Type.TRACK_DEFAULT
4024 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004025 // If the requested networkCapabilities is null, take them instead from
4026 // the default network request. This allows callers to keep track of
4027 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004028 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004029 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4030 enforceAccessPermission();
4031 } else {
4032 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4033 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004034 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4035 // of the app when the request is filed, but we never change the request if the app
4036 // changes network state. http://b/29964605
4037 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004038 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004039 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004040
Robert Greenwalt6078b502014-06-11 16:05:07 -07004041 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004042 throw new IllegalArgumentException("Bad timeout specified");
4043 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004044
Etan Cohenddb9ef02015-11-18 10:56:15 -08004045 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4046 .equals(networkCapabilities.getNetworkSpecifier())) {
4047 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4048 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4049 }
4050
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004051 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004052 nextNetworkRequestId(), type);
4053 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004054 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004055
4056 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004057 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004058 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004059 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004060 }
4061 return networkRequest;
4062 }
4063
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004064 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004065 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004066 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004067 } else {
4068 enforceChangePermission();
4069 }
4070 }
4071
fenglub15e72b2015-03-20 11:29:56 -07004072 @Override
fengludb571472015-04-21 17:12:05 -07004073 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004074 enforceAccessPermission();
4075 NetworkAgentInfo nai = null;
4076 if (network == null) {
4077 return false;
4078 }
4079 synchronized (mNetworkForNetId) {
4080 nai = mNetworkForNetId.get(network.netId);
4081 }
4082 if (nai != null) {
4083 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4084 return true;
4085 }
4086 return false;
4087 }
4088
Felipe Lemeee27cab2016-06-20 16:36:29 -07004089 private boolean isSystem(int uid) {
4090 return uid < Process.FIRST_APPLICATION_UID;
4091 }
fenglub15e72b2015-03-20 11:29:56 -07004092
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004093 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004094 final int uid = Binder.getCallingUid();
4095 if (isSystem(uid)) {
4096 return;
4097 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004098 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004099 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004100 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004101 synchronized(mRulesLock) {
4102 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4103 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004104 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4105 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004106 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004107 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004108 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004109 }
4110 }
4111 }
4112
Robert Greenwalt9258c642014-03-26 16:47:06 -07004113 @Override
4114 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4115 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004116 checkNotNull(operation, "PendingIntent cannot be null.");
4117 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4118 enforceNetworkRequestPermissions(networkCapabilities);
4119 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004120 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004121
4122 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004123 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4124 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004125 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004126 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4127 nri));
4128 return networkRequest;
4129 }
4130
Jeremy Joslin79294842014-12-03 17:15:28 -08004131 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4132 mHandler.sendMessageDelayed(
4133 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4134 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4135 }
4136
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004137 @Override
4138 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004139 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004140 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4141 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004142 }
4143
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004144 // In order to implement the compatibility measure for pre-M apps that call
4145 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4146 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4147 // This ensures it has permission to do so.
4148 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4149 if (nc == null) {
4150 return false;
4151 }
4152 int[] transportTypes = nc.getTransportTypes();
4153 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4154 return false;
4155 }
4156 try {
4157 mContext.enforceCallingOrSelfPermission(
4158 android.Manifest.permission.ACCESS_WIFI_STATE,
4159 "ConnectivityService");
4160 } catch (SecurityException e) {
4161 return false;
4162 }
4163 return true;
4164 }
4165
Robert Greenwalt9258c642014-03-26 16:47:06 -07004166 @Override
4167 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4168 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004169 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4170 enforceAccessPermission();
4171 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004172
Erik Kline7523eb32015-07-09 18:24:03 +09004173 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004174 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4175 NetworkRequest.Type.LISTEN);
4176 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004177 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004178
4179 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4180 return networkRequest;
4181 }
4182
4183 @Override
4184 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4185 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004186 checkNotNull(operation, "PendingIntent cannot be null.");
4187 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4188 enforceAccessPermission();
4189 }
4190
Erik Kline7523eb32015-07-09 18:24:03 +09004191 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004192 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4193 NetworkRequest.Type.LISTEN);
4194 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004195 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004196
4197 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004198 }
4199
4200 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004201 public void requestLinkProperties(NetworkRequest networkRequest) {
4202 ensureNetworkRequestHasType(networkRequest);
4203 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4204 mHandler.sendMessage(mHandler.obtainMessage(
4205 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4206 }
4207
4208 @Override
4209 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4210 ensureNetworkRequestHasType(networkRequest);
4211 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4212 mHandler.sendMessage(mHandler.obtainMessage(
4213 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4214 }
4215
4216 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004217 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004218 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004219 mHandler.sendMessage(mHandler.obtainMessage(
4220 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004221 }
4222
4223 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004224 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004225 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004226 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4227 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004228 }
4229
Robert Greenwalta67be032014-05-16 15:49:14 -07004230 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004231 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004232 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4233 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4234 }
4235
4236 @Override
4237 public void unregisterNetworkFactory(Messenger messenger) {
4238 enforceConnectivityInternalPermission();
4239 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4240 }
4241
4242 private void handleUnregisterNetworkFactory(Messenger messenger) {
4243 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4244 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004245 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004246 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004247 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004248 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004249 }
4250
Robert Greenwalt7b816022014-04-18 15:25:25 -07004251 /**
4252 * NetworkAgentInfo supporting a request by requestId.
4253 * These have already been vetted (their Capabilities satisfy the request)
4254 * and the are the highest scored network available.
4255 * the are keyed off the Requests requestId.
4256 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004257 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004258 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4259 new SparseArray<NetworkAgentInfo>();
4260
Paul Jensen31a94f42015-02-13 14:18:39 -05004261 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4262 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004263 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4264 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004265 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4266 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4267 // there may not be a strict 1:1 correlation between the two.
4268 @GuardedBy("mNetworkForNetId")
4269 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004270
Robert Greenwalt7b816022014-04-18 15:25:25 -07004271 // NetworkAgentInfo keyed off its connecting messenger
4272 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004273 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004274 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4275 new HashMap<Messenger, NetworkAgentInfo>();
4276
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004277 @GuardedBy("mBlockedAppUids")
4278 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4279
Paul Jensen2c311d62014-11-17 12:34:51 -05004280 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004281 private final NetworkRequest mDefaultRequest;
4282
Erik Klineda4bfa82015-04-30 12:58:40 +09004283 // Request used to optionally keep mobile data active even when higher
4284 // priority networks like Wi-Fi are active.
4285 private final NetworkRequest mDefaultMobileDataRequest;
4286
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004287 private NetworkAgentInfo getDefaultNetwork() {
4288 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4289 }
4290
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004291 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004292 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004293 }
4294
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004295 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4296 return nri.request.requestId == mDefaultRequest.requestId;
4297 }
4298
Paul Jensen31a94f42015-02-13 14:18:39 -05004299 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004300 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004301 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004302 enforceConnectivityInternalPermission();
4303
Paul Jensen2c311d62014-11-17 12:34:51 -05004304 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4305 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004306 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004307 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4308 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004309 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004310 synchronized (this) {
4311 nai.networkMonitor.systemReady = mSystemReady;
4312 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004313 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4314 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004315 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004316 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004317 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004318 }
4319
4320 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4321 if (VDBG) log("Got NetworkAgent Messenger");
4322 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004323 synchronized (mNetworkForNetId) {
4324 mNetworkForNetId.put(na.network.netId, na);
4325 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004326 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4327 NetworkInfo networkInfo = na.networkInfo;
4328 na.networkInfo = null;
4329 updateNetworkInfo(na, networkInfo);
4330 }
4331
4332 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4333 LinkProperties newLp = networkAgent.linkProperties;
4334 int netId = networkAgent.network.netId;
4335
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004336 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4337 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004338 if (networkAgent.clatd != null) {
4339 networkAgent.clatd.fixupLinkProperties(oldLp);
4340 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004341
Paul Jensen992f2522014-04-28 10:33:11 -04004342 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004343 updateMtu(newLp, oldLp);
4344 // TODO - figure out what to do for clat
4345// for (LinkProperties lp : newLp.getStackedLinks()) {
4346// updateMtu(lp, null);
4347// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004348 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004349
Erik Kline94887872016-04-05 13:30:49 +09004350 updateRoutes(newLp, oldLp, netId);
4351 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004352
Paul Jensen3b759822014-05-13 11:44:01 -04004353 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004354 if (isDefaultNetwork(networkAgent)) {
4355 handleApplyDefaultProxy(newLp.getHttpProxy());
4356 } else {
4357 updateProxy(newLp, oldLp, networkAgent);
4358 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004359 // TODO - move this check to cover the whole function
4360 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004361 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004362 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4363 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004364
4365 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004366 }
4367
Lorenzo Colitti95439462014-10-09 13:44:48 +09004368 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4369 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4370 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004371
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004372 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004373 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4374 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004375 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004376 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004377 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004378 }
Paul Jensen992f2522014-04-28 10:33:11 -04004379
4380 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4381 CompareResult<String> interfaceDiff = new CompareResult<String>();
4382 if (oldLp != null) {
4383 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4384 } else if (newLp != null) {
4385 interfaceDiff.added = newLp.getAllInterfaceNames();
4386 }
4387 for (String iface : interfaceDiff.added) {
4388 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004389 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004390 mNetd.addInterfaceToNetwork(iface, netId);
4391 } catch (Exception e) {
4392 loge("Exception adding interface: " + e);
4393 }
4394 }
4395 for (String iface : interfaceDiff.removed) {
4396 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004397 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004398 mNetd.removeInterfaceFromNetwork(iface, netId);
4399 } catch (Exception e) {
4400 loge("Exception removing interface: " + e);
4401 }
4402 }
4403 }
4404
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004405 /**
4406 * Have netd update routes from oldLp to newLp.
4407 * @return true if routes changed between oldLp and newLp
4408 */
4409 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004410 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4411 if (oldLp != null) {
4412 routeDiff = oldLp.compareAllRoutes(newLp);
4413 } else if (newLp != null) {
4414 routeDiff.added = newLp.getAllRoutes();
4415 }
4416
4417 // add routes before removing old in case it helps with continuous connectivity
4418
4419 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4420 for (RouteInfo route : routeDiff.added) {
4421 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004422 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004423 try {
4424 mNetd.addRoute(netId, route);
4425 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004426 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4427 loge("Exception in addRoute for non-gateway: " + e);
4428 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004429 }
4430 }
4431 for (RouteInfo route : routeDiff.added) {
4432 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004433 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004434 try {
4435 mNetd.addRoute(netId, route);
4436 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004437 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4438 loge("Exception in addRoute for gateway: " + e);
4439 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004440 }
4441 }
4442
4443 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004444 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004445 try {
4446 mNetd.removeRoute(netId, route);
4447 } catch (Exception e) {
4448 loge("Exception in removeRoute: " + e);
4449 }
4450 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004451 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004452 }
Erik Kline41368502015-06-17 13:19:54 +09004453
Erik Kline94887872016-04-05 13:30:49 +09004454 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4455 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4456 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004457 }
Erik Kline94887872016-04-05 13:30:49 +09004458
4459 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004460 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004461 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004462 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004463 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4464 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004465 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004466 }
4467 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4468 if (defaultNai != null && defaultNai.network.netId == netId) {
4469 setDefaultDnsSystemProperties(dnses);
4470 }
4471 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004472 }
4473
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004474 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4475 int last = 0;
4476 for (InetAddress dns : dnses) {
4477 ++last;
4478 String key = "net.dns" + last;
4479 String value = dns.getHostAddress();
4480 SystemProperties.set(key, value);
4481 }
4482 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4483 String key = "net.dns" + i;
4484 SystemProperties.set(key, "");
4485 }
4486 mNumDnsEntries = last;
4487 }
4488
Paul Jensen3d194ea2015-06-16 14:27:36 -04004489 /**
4490 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4491 * augmented with any stateful capabilities implied from {@code networkAgent}
4492 * (e.g., validated status and captive portal status).
4493 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004494 * @param oldScore score of the network before any of the changes that prompted us
4495 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004496 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004497 * @param networkCapabilities the new network capabilities.
4498 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004499 private void updateCapabilities(
4500 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004501 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4502 networkCapabilities)) {
4503 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4504 + nai.networkCapabilities + " -> " + networkCapabilities);
4505 }
4506
Paul Jensen3d194ea2015-06-16 14:27:36 -04004507 // Don't modify caller's NetworkCapabilities.
4508 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004509 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004510 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4511 } else {
4512 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4513 }
Paul Jensene0988542015-06-25 15:30:08 -04004514 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004515 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4516 } else {
4517 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4518 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004519 if (nai.isBackgroundNetwork()) {
4520 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4521 } else {
4522 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4523 }
4524
4525 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4526
4527 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4528 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4529 try {
4530 mNetd.setNetworkPermission(nai.network.netId,
4531 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4532 null : NetworkManagementService.PERMISSION_SYSTEM);
4533 } catch (RemoteException e) {
4534 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004535 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004536 }
4537
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004538 final NetworkCapabilities prevNc = nai.networkCapabilities;
4539 synchronized (nai) {
4540 nai.networkCapabilities = networkCapabilities;
4541 }
4542 if (nai.getCurrentScore() == oldScore &&
4543 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4544 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4545 // the change we're processing can't affect any requests, it can only affect the listens
4546 // on this network. We might have been called by rematchNetworkAndRequests when a
4547 // network changed foreground state.
4548 processListenRequests(nai, true);
4549 } else {
4550 // If the requestable capabilities have changed or the score changed, we can't have been
4551 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004552 rematchAllNetworksAndRequests(nai, oldScore);
4553 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004554 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004555 }
4556
Paul Jensenc8b9a742014-09-30 15:37:41 -04004557 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004558 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4559 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004560 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004561 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004562 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4563 }
4564 }
4565
Robert Greenwalt7b816022014-04-18 15:25:25 -07004566 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4567 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004568 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004569 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4570 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004571 }
4572 }
4573
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004574 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4575 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004576 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004577 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004578 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4579 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004580 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004581 sendIntent(nri.mPendingIntent, intent);
4582 }
4583 // else not handled
4584 }
4585
4586 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4587 mPendingIntentWakeLock.acquire();
4588 try {
4589 if (DBG) log("Sending " + pendingIntent);
4590 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4591 } catch (PendingIntent.CanceledException e) {
4592 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4593 mPendingIntentWakeLock.release();
4594 releasePendingNetworkRequest(pendingIntent);
4595 }
4596 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4597 }
4598
4599 @Override
4600 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4601 String resultData, Bundle resultExtras) {
4602 if (DBG) log("Finished sending " + pendingIntent);
4603 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004604 // Release with a delay so the receiving client has an opportunity to put in its
4605 // own request.
4606 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004607 }
4608
Robert Greenwalt9258c642014-03-26 16:47:06 -07004609 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004610 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004611 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004612 Bundle bundle = new Bundle();
4613 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4614 new NetworkRequest(nri.request));
4615 Message msg = Message.obtain();
4616 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4617 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4618 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4619 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004620 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004621 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004622 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004623 break;
4624 }
4625 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4626 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4627 new NetworkCapabilities(networkAgent.networkCapabilities));
4628 break;
4629 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004630 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004631 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4632 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004633 break;
4634 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004635 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004636 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004637 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004638 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004639 if (VDBG) {
4640 log("sending notification " + notifyTypeToName(notificationType) +
4641 " for " + nri.request);
4642 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004643 nri.messenger.send(msg);
4644 } catch (RemoteException e) {
4645 // may occur naturally in the race of binder death.
4646 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4647 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004648 }
4649
Paul Jensenc8b9a742014-09-30 15:37:41 -04004650 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004651 if (nai.numRequestNetworkRequests() != 0) {
4652 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4653 NetworkRequest nr = nai.requestAt(i);
4654 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004655 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004656 loge("Dead network still had at least " + nr);
4657 break;
4658 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004659 }
4660 nai.asyncChannel.disconnect();
4661 }
4662
Robert Greenwalt7b816022014-04-18 15:25:25 -07004663 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4664 if (oldNetwork == null) {
4665 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4666 return;
4667 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004668 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004669
4670 // If we get here it means that the last linger timeout for this network expired. So there
4671 // must be no other active linger timers, and we must stop lingering.
4672 oldNetwork.clearLingerState();
4673
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004674 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004675 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004676 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004677 } else {
4678 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004679 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4680 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004681 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004682 }
4683
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004684 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004685 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004686 setupDataActivityTracking(newNetwork);
4687 try {
4688 mNetd.setDefaultNetId(newNetwork.network.netId);
4689 } catch (Exception e) {
4690 loge("Exception setting default network :" + e);
4691 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004692 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004693 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004694 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004695 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004696 }
4697
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004698 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004699 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4700 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4701 NetworkRequest nr = nri.request;
4702 if (!nr.isListen()) continue;
4703 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4704 nai.removeRequest(nri.request.requestId);
4705 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4706 }
4707 }
4708
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004709 if (capabilitiesChanged) {
4710 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4711 }
4712
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004713 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4714 NetworkRequest nr = nri.request;
4715 if (!nr.isListen()) continue;
4716 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4717 nai.addRequest(nr);
4718 notifyNetworkCallback(nai, nri);
4719 }
4720 }
4721 }
4722
Paul Jensen2161a8e2014-09-11 11:00:39 -04004723 // Handles a network appearing or improving its score.
4724 //
4725 // - Evaluates all current NetworkRequests that can be
4726 // satisfied by newNetwork, and reassigns to newNetwork
4727 // any such requests for which newNetwork is the best.
4728 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004729 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004730 // needed. A network is needed if it is the best network for
4731 // one or more NetworkRequests, or if it is a VPN.
4732 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004733 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004734 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004735 //
4736 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4737 // networks that have no chance (i.e. even if validated)
4738 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004739 //
4740 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4741 // it does not remove NetworkRequests that other Networks could better satisfy.
4742 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4743 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4744 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004745 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004746 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004747 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4748 // performed to tear down unvalidated networks that have no chance (i.e. even if
4749 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004750 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004751 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004752 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004753 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004754 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004755 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004756
4757 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4758 final int score = newNetwork.getCurrentScore();
4759
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004760 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004761
Paul Jensen2161a8e2014-09-11 11:00:39 -04004762 // Find and migrate to this Network any NetworkRequests for
4763 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004764 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004765 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004766 NetworkCapabilities nc = newNetwork.networkCapabilities;
4767 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004768 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004769 // Process requests in the first pass and listens in the second pass. This allows us to
4770 // change a network's capabilities depending on which requests it has. This is only
4771 // correct if the change in capabilities doesn't affect whether the network satisfies
4772 // requests or not, and doesn't affect the network's score.
4773 if (nri.request.isListen()) continue;
4774
Paul Jensencf4c2c62015-07-01 14:16:32 -04004775 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4776 final boolean satisfies = newNetwork.satisfies(nri.request);
4777 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004778 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004779 log("Network " + newNetwork.name() + " was already satisfying" +
4780 " request " + nri.request.requestId + ". No change.");
4781 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004782 keep = true;
4783 continue;
4784 }
4785
4786 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004787 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004788 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004789 // next check if it's better than any current network we're using for
4790 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004791 if (VDBG) {
4792 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004793 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004794 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004795 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004796 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004797 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004798 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004799 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004800 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004801 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004802 affectedNetworks.add(currentNetwork);
4803 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004804 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004805 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004806 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004807 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004808 if (!newNetwork.addRequest(nri.request)) {
4809 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4810 }
4811 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004812 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004813 // Tell NetworkFactories about the new score, so they can stop
4814 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004815 // TODO - this could get expensive if we have alot of requests for this
4816 // network. Think about if there is a way to reduce this. Push
4817 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004818 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004819 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004820 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004821 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004822 if (currentNetwork != null) {
4823 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4824 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004825 }
4826 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004827 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004828 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4829 // mark it as no longer satisfying "nri". Because networks are processed by
4830 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4831 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4832 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4833 // This means this code doesn't have to handle the case where "currentNetwork" no
4834 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4835 if (DBG) {
4836 log("Network " + newNetwork.name() + " stopped satisfying" +
4837 " request " + nri.request.requestId);
4838 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004839 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004840 if (currentNetwork == newNetwork) {
4841 mNetworkForRequestId.remove(nri.request.requestId);
4842 sendUpdatedScoreToFactories(nri.request, 0);
4843 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004844 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4845 newNetwork.name() +
4846 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004847 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004848 // TODO: Technically, sending CALLBACK_LOST here is
4849 // incorrect if there is a replacement network currently
4850 // connected that can satisfy nri, which is a request
4851 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004852 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4853 // so this code is only incorrect for a network that loses
4854 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004855 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004856 }
4857 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004858 if (isNewDefault) {
4859 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004860 makeDefault(newNetwork);
4861 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4862 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004863 synchronized (ConnectivityService.this) {
4864 // have a new default network, release the transition wakelock in
4865 // a second if it's held. The second pause is to allow apps
4866 // to reconnect over the new network
4867 if (mNetTransitionWakeLock.isHeld()) {
4868 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4869 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4870 mNetTransitionWakeLockSerialNumber, 0),
4871 1000);
4872 }
4873 }
4874 }
4875
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004876 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4877 Slog.wtf(TAG, String.format(
4878 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4879 nc, newNetwork.networkCapabilities));
4880 }
4881 if (newNetwork.getCurrentScore() != score) {
4882 Slog.wtf(TAG, String.format(
4883 "BUG: %s changed score during rematch: %d -> %d",
4884 score, newNetwork.getCurrentScore()));
4885 }
4886
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004887 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004888 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4889 // If the network went from background to foreground or vice versa, we need to update
4890 // its foreground state. It is safe to do this after rematching the requests because
4891 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4892 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004893 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004894 } else {
4895 processListenRequests(newNetwork, false);
4896 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004897
Paul Jensencf4c2c62015-07-01 14:16:32 -04004898 // do this after the default net is switched, but
4899 // before LegacyTypeTracker sends legacy broadcasts
4900 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4901
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004902 // Linger any networks that are no longer needed. This should be done after sending the
4903 // available callback for newNetwork.
4904 for (NetworkAgentInfo nai : affectedNetworks) {
4905 updateLingerState(nai, now);
4906 }
4907 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4908 // does not need to be done in any particular order.
4909 updateLingerState(newNetwork, now);
4910
Paul Jensencf4c2c62015-07-01 14:16:32 -04004911 if (isNewDefault) {
4912 // Maintain the illusion: since the legacy API only
4913 // understands one network at a time, we must pretend
4914 // that the current default network disconnected before
4915 // the new one connected.
4916 if (oldDefaultNetwork != null) {
4917 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4918 oldDefaultNetwork, true);
4919 }
4920 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4921 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4922 notifyLockdownVpn(newNetwork);
4923 }
4924
Robert Greenwalt7b816022014-04-18 15:25:25 -07004925 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004926 // Notify battery stats service about this network, both the normal
4927 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004928 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004929 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004930 final IBatteryStats bs = BatteryStatsService.getService();
4931 final int type = newNetwork.networkInfo.getType();
4932
4933 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4934 bs.noteNetworkInterfaceType(baseIface, type);
4935 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4936 final String stackedIface = stacked.getInterfaceName();
4937 bs.noteNetworkInterfaceType(stackedIface, type);
4938 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4939 }
4940 } catch (RemoteException ignored) {
4941 }
4942
Robert Greenwalt152ed372014-12-17 17:19:53 -08004943 // This has to happen after the notifyNetworkCallbacks as that tickles each
4944 // ConnectivityManager instance so that legacy requests correctly bind dns
4945 // requests to this network. The legacy users are listening for this bcast
4946 // and will generally do a dns request so they can ensureRouteToHost and if
4947 // they do that before the callbacks happen they'll use the default network.
4948 //
4949 // TODO: Is there still a race here? We send the broadcast
4950 // after sending the callback, but if the app can receive the
4951 // broadcast before the callback, it might still break.
4952 //
4953 // This *does* introduce a race where if the user uses the new api
4954 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4955 // they may get old info. Reverse this after the old startUsing api is removed.
4956 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004957 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4958 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004959 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004960 // legacy type tracker filters out repeat adds
4961 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4962 }
4963 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004964
4965 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4966 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4967 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4968 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4969 if (newNetwork.isVPN()) {
4970 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4971 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004972 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004973 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4974 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004975 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004976 if (nai.getLingerExpiry() > 0) {
4977 // This network has active linger timers and no requests, but is not
4978 // lingering. Linger it.
4979 //
4980 // One way (the only way?) this can happen if this network is unvalidated
4981 // and became unneeded due to another network improving its score to the
4982 // point where this network will no longer be able to satisfy any requests
4983 // even if it validates.
4984 updateLingerState(nai, now);
4985 } else {
4986 if (DBG) log("Reaping " + nai.name());
4987 teardownUnneededNetwork(nai);
4988 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004989 }
4990 }
4991 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004992 }
4993
Paul Jensen1c7ba022015-06-16 14:27:36 -04004994 /**
4995 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4996 * being disconnected.
4997 * @param changed If only one Network's score or capabilities have been modified since the last
4998 * time this function was called, pass this Network in this argument, otherwise pass
4999 * null.
5000 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5001 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5002 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5003 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5004 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005005 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005006 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005007 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5008 // to avoid the slowness. It is not simply enough to process just "changed", for
5009 // example in the case where "changed"'s score decreases and another network should begin
5010 // satifying a NetworkRequest that "changed" currently satisfies.
5011
5012 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5013 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5014 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005015 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005016 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005017 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005018 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005019 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5020 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5021 // Rematch higher scoring networks first to prevent requests first matching a lower
5022 // scoring network and then a higher scoring network, which could produce multiple
5023 // callbacks and inadvertently unlinger networks.
5024 Arrays.sort(nais);
5025 for (NetworkAgentInfo nai : nais) {
5026 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005027 // Only reap the last time through the loop. Reaping before all rematching
5028 // is complete could incorrectly teardown a network that hasn't yet been
5029 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005030 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005031 : ReapUnvalidatedNetworks.REAP,
5032 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005033 }
5034 }
5035 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005036
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005037 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005038 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005039 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005040 // For now only update icons for default connection.
5041 // TODO: Update WiFi and cellular icons separately. b/17237507
5042 if (!isDefaultNetwork(nai)) return;
5043
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005044 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005045 // Don't repeat publish.
5046 if (newInetCondition == mDefaultInetConditionPublished) return;
5047
5048 mDefaultInetConditionPublished = newInetCondition;
5049 sendInetConditionBroadcast(nai.networkInfo);
5050 }
5051
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005052 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5053 if (mLockdownTracker != null) {
5054 if (nai != null && nai.isVPN()) {
5055 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5056 } else {
5057 mLockdownTracker.onNetworkInfoChanged();
5058 }
5059 }
5060 }
5061
Robert Greenwalt7b816022014-04-18 15:25:25 -07005062 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5063 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005064 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005065 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005066 synchronized (networkAgent) {
5067 oldInfo = networkAgent.networkInfo;
5068 networkAgent.networkInfo = newInfo;
5069 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005070 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005071
5072 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005073 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5074 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5075 notifyIfacesChangedForNetworkStats();
5076 } else if (VDBG) log("ignoring duplicate network state non-change");
5077 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005078 return;
5079 }
5080 if (DBG) {
5081 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5082 (oldInfo == null ? "null" : oldInfo.getState()) +
5083 " to " + state);
5084 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005085
Robin Lee585e2482016-05-01 23:00:00 +01005086 if (!networkAgent.created
5087 && (state == NetworkInfo.State.CONNECTED
5088 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005089
5090 // A network that has just connected has zero requests and is thus a foreground network.
5091 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5092
Robert Greenwalt7b816022014-04-18 15:25:25 -07005093 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005094 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005095 if (networkAgent.isVPN()) {
5096 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005097 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5098 (networkAgent.networkMisc == null ||
5099 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005100 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005101 mNetd.createPhysicalNetwork(networkAgent.network.netId,
5102 networkAgent.networkCapabilities.hasCapability(
5103 NET_CAPABILITY_NOT_RESTRICTED) ?
5104 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005105 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005106 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005107 loge("Error creating network " + networkAgent.network.netId + ": "
5108 + e.getMessage());
5109 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005110 }
Paul Jenseneec75412014-08-04 12:21:19 -04005111 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005112 }
5113
5114 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5115 networkAgent.everConnected = true;
5116
Robert Greenwalt7b816022014-04-18 15:25:25 -07005117 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005118 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005119
Paul Jensenca8f16a2014-05-09 12:47:55 -04005120 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005121 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005122
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005123 if (networkAgent.isVPN()) {
5124 // Temporarily disable the default proxy (not global).
5125 synchronized (mProxyLock) {
5126 if (!mDefaultProxyDisabled) {
5127 mDefaultProxyDisabled = true;
5128 if (mGlobalProxy == null && mDefaultProxy != null) {
5129 sendProxyBroadcast(null);
5130 }
5131 }
5132 }
5133 // TODO: support proxy per network.
5134 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005135
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005136 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5137 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5138 // capabilities, so it only needs to be done once on initial connect, not every time the
5139 // network's capabilities change. Note that we do this before rematching the network,
5140 // so we could decide to tear it down immediately afterwards. That's fine though - on
5141 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5142 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005143 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005144
Paul Jensen2161a8e2014-09-11 11:00:39 -04005145 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005146 final long now = SystemClock.elapsedRealtime();
5147 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005148
5149 // This has to happen after matching the requests, because callbacks are just requests.
5150 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005151 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005152 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005153 if (networkAgent.isVPN()) {
5154 synchronized (mProxyLock) {
5155 if (mDefaultProxyDisabled) {
5156 mDefaultProxyDisabled = false;
5157 if (mGlobalProxy == null && mDefaultProxy != null) {
5158 sendProxyBroadcast(mDefaultProxy);
5159 }
5160 }
5161 }
5162 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005163 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5164 state == NetworkInfo.State.SUSPENDED) {
5165 // going into or coming out of SUSPEND: rescore and notify
5166 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005167 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005168 }
5169 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5170 ConnectivityManager.CALLBACK_SUSPENDED :
5171 ConnectivityManager.CALLBACK_RESUMED));
5172 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005173 }
5174 }
5175
Robert Greenwaltac96c522014-06-03 16:43:57 -07005176 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005177 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005178 if (score < 0) {
5179 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5180 "). Bumping score to min of 0");
5181 score = 0;
5182 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005183
Paul Jensen2161a8e2014-09-11 11:00:39 -04005184 final int oldScore = nai.getCurrentScore();
5185 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005186
Paul Jensen85cf78e2015-06-25 13:25:07 -04005187 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005188
Paul Jensenc8b9a742014-09-30 15:37:41 -04005189 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005190 }
5191
Robert Greenwalt9258c642014-03-26 16:47:06 -07005192 // notify only this one new request of the current state
5193 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5194 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005195 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005196 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005197 } else {
5198 sendPendingIntentForRequest(nri, nai, notifyType);
5199 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005200 }
5201
Robert Greenwalt8d482522015-06-24 13:23:42 -07005202 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005203 // The NetworkInfo we actually send out has no bearing on the real
5204 // state of affairs. For example, if the default connection is mobile,
5205 // and a request for HIPRI has just gone away, we need to pretend that
5206 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5207 // the state to DISCONNECTED, even though the network is of type MOBILE
5208 // and is still connected.
5209 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5210 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005211 if (state != DetailedState.DISCONNECTED) {
5212 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005213 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005214 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005215 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005216 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5217 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5218 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5219 if (info.isFailover()) {
5220 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5221 nai.networkInfo.setFailover(false);
5222 }
5223 if (info.getReason() != null) {
5224 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5225 }
5226 if (info.getExtraInfo() != null) {
5227 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5228 }
5229 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005230 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005231 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005232 if (newDefaultAgent != null) {
5233 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5234 newDefaultAgent.networkInfo);
5235 } else {
5236 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5237 }
5238 }
5239 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5240 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005241 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005242 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005243 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005244 }
5245 }
5246 }
5247
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005248 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005249 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005250 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5251 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005252 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5253 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005254 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5255 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005256 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005257 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005258 } else {
5259 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5260 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005261 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005262 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005263
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005264 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5265 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5266 }
5267
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005268 private String notifyTypeToName(int notifyType) {
5269 switch (notifyType) {
5270 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5271 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5272 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5273 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5274 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5275 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5276 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5277 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5278 }
5279 return "UNKNOWN";
5280 }
5281
Jeff Sharkey69736342014-12-08 14:50:12 -08005282 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005283 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5284 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005285 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005286 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005287 try {
5288 mStatsService.forceUpdateIfaces();
5289 } catch (Exception ignored) {
5290 }
5291 }
5292
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005293 @Override
5294 public boolean addVpnAddress(String address, int prefixLength) {
5295 throwIfLockdownEnabled();
5296 int user = UserHandle.getUserId(Binder.getCallingUid());
5297 synchronized (mVpns) {
5298 return mVpns.get(user).addAddress(address, prefixLength);
5299 }
5300 }
5301
5302 @Override
5303 public boolean removeVpnAddress(String address, int prefixLength) {
5304 throwIfLockdownEnabled();
5305 int user = UserHandle.getUserId(Binder.getCallingUid());
5306 synchronized (mVpns) {
5307 return mVpns.get(user).removeAddress(address, prefixLength);
5308 }
5309 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005310
5311 @Override
5312 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5313 throwIfLockdownEnabled();
5314 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005315 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005316 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005317 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005318 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005319 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005320 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005321 }
5322 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005323 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005324
5325 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005326 public String getCaptivePortalServerUrl() {
5327 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5328 }
5329
5330 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005331 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5332 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5333 enforceKeepalivePermission();
5334 mKeepaliveTracker.startNattKeepalive(
5335 getNetworkAgentInfoForNetwork(network),
5336 intervalSeconds, messenger, binder,
5337 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5338 }
5339
5340 @Override
5341 public void stopKeepalive(Network network, int slot) {
5342 mHandler.sendMessage(mHandler.obtainMessage(
5343 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5344 }
5345
5346 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005347 public void factoryReset() {
5348 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005349
5350 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5351 return;
5352 }
5353
Robin Lee3b3dd942015-05-12 18:14:58 +01005354 final int userId = UserHandle.getCallingUserId();
5355
Stuart Scottf1fb3972015-04-02 18:00:02 -07005356 // Turn airplane mode off
5357 setAirplaneMode(false);
5358
Stuart Scotte3e314d2015-04-20 14:07:45 -07005359 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5360 // Untether
5361 for (String tether : getTetheredIfaces()) {
5362 untether(tether);
5363 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005364 }
5365
Stuart Scotte3e314d2015-04-20 14:07:45 -07005366 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005367 // Remove always-on package
5368 synchronized (mVpns) {
5369 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5370 if (alwaysOnPackage != null) {
5371 setAlwaysOnVpnPackage(userId, null, false);
5372 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5373 }
5374 }
5375
Stuart Scotte3e314d2015-04-20 14:07:45 -07005376 // Turn VPN off
5377 VpnConfig vpnConfig = getVpnConfig(userId);
5378 if (vpnConfig != null) {
5379 if (vpnConfig.legacy) {
5380 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5381 } else {
5382 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5383 // in the future without user intervention.
5384 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005385
Victor Changb04a5ea2016-05-30 20:36:30 +01005386 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005387 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005388 }
5389 }
5390 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005391
5392 @VisibleForTesting
5393 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5394 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5395 return new NetworkMonitor(context, handler, nai, defaultRequest);
5396 }
Erik Kline48f12f22016-04-14 17:30:59 +09005397
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005398 @VisibleForTesting
5399 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5400 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5401 }
5402
Hugo Benichicfddd682016-05-31 16:28:06 +09005403 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005404 int newNetid = NETID_UNSET;
5405 int prevNetid = NETID_UNSET;
5406 int[] transports = new int[0];
5407 boolean hadIPv4 = false;
5408 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005409
Hugo Benichi5f16f762016-04-20 12:09:33 +09005410 if (newNai != null) {
5411 newNetid = newNai.network.netId;
5412 transports = newNai.networkCapabilities.getTransportTypes();
5413 }
5414 if (prevNai != null) {
5415 prevNetid = prevNai.network.netId;
5416 final LinkProperties lp = prevNai.linkProperties;
5417 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5418 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5419 }
5420
Hugo Benichicfddd682016-05-31 16:28:06 +09005421 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5422 }
5423
5424 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5425 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427}