blob: 86afe08cedce31d557aebe8bb0de7e8df1fd6dc4 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060032import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070033import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070034import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060036import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070037import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060038
Wenchao Tongf5ea3402015-03-04 13:26:38 -080039import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080040import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090041import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070042import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.ContentResolver;
45import android.content.Context;
46import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070047import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070049import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090050import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070051import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090053import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070055import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070056import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070058import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080059import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070060import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070061import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070062import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070063import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070064import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070066import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070067import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070068import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070069import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070070import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070071import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070072import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040073import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070074import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040075import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040076import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090077import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090078import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090079import android.net.metrics.NetworkEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080081import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070082import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040083import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070085import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070086import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070087import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.Looper;
89import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070090import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070091import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070092import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070093import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070094import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080095import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090096import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070098import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040099import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700101import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700102import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700103import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700104import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600105import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700106import android.util.LocalLog;
107import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600108import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700109import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800110import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700111import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500112import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700114import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Wink Savilleab9321d2013-06-29 21:10:57 -0700116import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400117import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400118import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700119import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700120import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700122import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800123import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700124import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700125import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700126import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900127import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900128import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700129import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700130import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400131import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900132import com.android.server.connectivity.KeepaliveTracker;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900133import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900134import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700135import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600136import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400137import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900138import com.android.server.connectivity.NetworkNotificationManager;
139import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400140import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700141import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800142import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700143import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700144import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700145import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600146
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700147import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700148
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700149import org.xmlpull.v1.XmlPullParser;
150import org.xmlpull.v1.XmlPullParserException;
151
152import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700154import java.io.FileNotFoundException;
155import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700156import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700158import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700159import java.net.InetAddress;
160import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700161import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700162import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700163import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700164import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700165import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700166import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700167import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700168import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700169import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600170import java.util.SortedSet;
171import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
173/**
174 * @hide
175 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800176public class ConnectivityService extends IConnectivityManager.Stub
177 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900178 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900180 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700181 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
Jake Hamby786e71a2014-02-06 14:43:50 -0800183 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900184 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700185
Jeff Sharkey899223b2012-08-04 15:24:58 -0700186 // TODO: create better separation between radio types and network types
187
Robert Greenwalt42acef32009-08-12 16:08:25 -0700188 // how long to wait before switching back to a radio's default network
189 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
190 // system property that can override the above value
191 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
192 "android.telephony.apn-restore";
193
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900194 // How long to wait before putting up a "This network doesn't have an Internet connection,
195 // connect anyway?" dialog after the user selects a network that doesn't validate.
196 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
197
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900198 // Default to 30s linger time-out. Modifiable only for testing.
199 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
200 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
201 @VisibleForTesting
202 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
203
Jeremy Joslin79294842014-12-03 17:15:28 -0800204 // How long to delay to removal of a pending intent based request.
205 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
206 private final int mReleasePendingIntentDelayMs;
207
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800208 private Tethering mTethering;
209
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700210 private final PermissionMonitor mPermissionMonitor;
211
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700212 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700213
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700214 @GuardedBy("mVpns")
215 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700216
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700217 private boolean mLockdownEnabled;
218 private LockdownVpnTracker mLockdownTracker;
219
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700220 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
221 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600223 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700224 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700225 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600226 @GuardedBy("mRulesLock")
227 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
228 /** Flag indicating if background data is restricted. */
229 @GuardedBy("mRulesLock")
230 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700231
Erik Klineda4bfa82015-04-30 12:58:40 +0900232 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700234 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700235 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800237 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
239 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700240 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700242 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800243 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700244 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700245
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700246 private String mCurrentTcpBufferSizes;
247
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700248 private static final int ENABLED = 1;
249 private static final int DISABLED = 0;
250
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900251 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900252 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
253 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900254
Paul Jensenb10e37f2014-11-25 12:33:08 -0500255 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400256 // Tear down networks that have no chance (e.g. even if validated) of becoming
257 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500258 // all networks have been rematched against all NetworkRequests.
259 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400260 // Don't reap networks. This should be passed when some networks have not yet been
261 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500262 DONT_REAP
263 };
264
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700265 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700266 * used internally to change our mobile data enabled flag
267 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700268 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700269
270 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700271 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700272 * from one net to another. Clear happens when we get a new
273 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
274 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700275 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700276 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700277
Robert Greenwalt434203a2010-10-11 16:00:27 -0700278 /**
279 * used internally to reload global proxy settings
280 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700281 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700282
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700283 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400284 * PAC manager has received new port.
285 */
286 private static final int EVENT_PROXY_HAS_CHANGED = 16;
287
Robert Greenwalte049c232014-04-11 15:53:27 -0700288 /**
289 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700290 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700291 */
292 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
293
Robert Greenwalt7b816022014-04-18 15:25:25 -0700294 /**
295 * used internally when registering NetworkAgents
296 * obj = Messenger
297 */
298 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
299
Robert Greenwalt9258c642014-03-26 16:47:06 -0700300 /**
301 * used to add a network request
302 * includes a NetworkRequestInfo
303 */
304 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
305
306 /**
307 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900308 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700309 * cancel it.
310 * includes a NetworkRequestInfo
311 */
312 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
313
314 /**
315 * used to add a network listener - no request
316 * includes a NetworkRequestInfo
317 */
318 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
319
320 /**
321 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400322 * arg1 = UID of caller
323 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700324 */
325 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
326
Robert Greenwalta67be032014-05-16 15:49:14 -0700327 /**
328 * used internally when registering NetworkFactories
329 * obj = Messenger
330 */
331 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
332
Robert Greenwalt27711812014-06-25 16:45:57 -0700333 /**
334 * used internally to expire a wakelock when transitioning
335 * from one net to another. Expire happens when we fail to find
336 * a new network (typically after 1 minute) -
337 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
338 * a replacement network.
339 */
340 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
341
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700342 /**
343 * Used internally to indicate the system is ready.
344 */
345 private static final int EVENT_SYSTEM_READY = 25;
346
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800347 /**
348 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400349 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800350 */
351 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
352
353 /**
354 * used to remove a pending intent and its associated network request.
355 * arg1 = UID of caller
356 * obj = PendingIntent
357 */
358 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
359
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900360 /**
361 * used to specify whether a network should be used even if unvalidated.
362 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
363 * arg2 = whether to remember this choice in the future (1 or 0)
364 * obj = network
365 */
366 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
367
368 /**
369 * used to ask the user to confirm a connection to an unvalidated network.
370 * obj = network
371 */
372 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700373
Erik Klineda4bfa82015-04-30 12:58:40 +0900374 /**
375 * used internally to (re)configure mobile data always-on settings.
376 */
377 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
378
Paul Jensen694f2b82015-06-17 14:15:39 -0400379 /**
380 * used to add a network listener with a pending intent
381 * obj = NetworkRequestInfo
382 */
383 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
384
Erik Klineacdd6392016-07-07 16:50:58 +0900385 /**
386 * Indicates a caller has requested to have its callback invoked with
387 * the latest LinkProperties or NetworkCapabilities.
388 *
389 * arg1 = UID of caller
390 * obj = NetworkRequest
391 */
392 private static final int EVENT_REQUEST_LINKPROPERTIES = 32;
393 private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
394
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900395 /** Handler thread used for both of the handlers below. */
396 @VisibleForTesting
397 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700398 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700399 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700400 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700401 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700402
Mike Lockwood0f79b542009-08-14 14:18:49 -0400403 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800404 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400405
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700406 private PowerManager.WakeLock mNetTransitionWakeLock;
407 private String mNetTransitionWakeLockCausedBy = "";
408 private int mNetTransitionWakeLockSerialNumber;
409 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800410 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700411
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700412 // used in DBG mode to track inet condition reports
413 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
414 private ArrayList mInetLog;
415
Robert Greenwalt434203a2010-10-11 16:00:27 -0700416 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400417 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700418 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700419 private boolean mDefaultProxyDisabled = false;
420
Robert Greenwalt434203a2010-10-11 16:00:27 -0700421 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400422 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700423
Jason Monk602b2322013-07-03 17:04:33 -0400424 private PacManager mPacManager = null;
425
Erik Klineda4bfa82015-04-30 12:58:40 +0900426 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700427
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400428 private UserManager mUserManager;
429
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700430 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700431 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700432
Robert Greenwalt50393202011-06-21 17:26:14 -0700433 // the set of network types that can only be enabled by system/sig apps
434 List mProtectedNetworks;
435
John Spurlockbf991a82013-06-24 14:20:23 -0400436 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700437
Wink Savilleab9321d2013-06-29 21:10:57 -0700438 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400439
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900440 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900441 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900442 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900443
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700444 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
445 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700446 private final static int MAX_NET_ID = 65535;
447 private int mNextNetId = MIN_NET_ID;
448
Robert Greenwalt34524f02014-05-18 16:22:10 -0700449 // sequence number of NetworkRequests
450 private int mNextNetworkRequestId = 1;
451
Erik Kline7523eb32015-07-09 18:24:03 +0900452 // NetworkRequest activity String log entries.
453 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
454 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
455
Hugo Benichic2ae2872016-07-11 11:05:12 +0900456 // NetworkInfo blocked and unblocked String log entries
457 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
458 private static final int MAX_NETWORK_INFO_LOGS = 100;
459 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
460
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700461 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
462 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400463 private static class ValidationLog {
464 final Network mNetwork;
465 final String mNetworkExtraInfo;
466 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700467
Paul Jensen0808eb82016-06-03 13:51:21 -0400468 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
469 mNetwork = network;
470 mNetworkExtraInfo = networkExtraInfo;
471 mLog = log;
472 }
473 }
474 private final ArrayDeque<ValidationLog> mValidationLogs =
475 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
476
477 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700478 synchronized(mValidationLogs) {
479 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
480 mValidationLogs.removeLast();
481 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400482 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700483 }
484 }
485
Hugo Benichif9fdf872016-07-28 17:53:06 +0900486 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900487
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700488 /**
489 * Implements support for the legacy "one network per network type" model.
490 *
491 * We used to have a static array of NetworkStateTrackers, one for each
492 * network type, but that doesn't work any more now that we can have,
493 * for example, more that one wifi network. This class stores all the
494 * NetworkAgentInfo objects that support a given type, but the legacy
495 * API will only see the first one.
496 *
497 * It serves two main purposes:
498 *
499 * 1. Provide information about "the network for a given type" (since this
500 * API only supports one).
501 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
502 * the first network for a given type changes, or if the default network
503 * changes.
504 */
505 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900506
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900507 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900508 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900509
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700510 /**
511 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
512 * Each list holds references to all NetworkAgentInfos that are used to
513 * satisfy requests for that network type.
514 *
515 * This array is built out at startup such that an unsupported network
516 * doesn't get an ArrayList instance, making this a tristate:
517 * unsupported, supported but not active and active.
518 *
519 * The actual lists are populated when we scan the network types that
520 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900521 *
522 * Threading model:
523 * - addSupportedType() is only called in the constructor
524 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
525 * They are therefore not thread-safe with respect to each other.
526 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
527 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
528 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700529 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900530 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700531
532 public LegacyTypeTracker() {
533 mTypeLists = (ArrayList<NetworkAgentInfo>[])
534 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
535 }
536
537 public void addSupportedType(int type) {
538 if (mTypeLists[type] != null) {
539 throw new IllegalStateException(
540 "legacy list for type " + type + "already initialized");
541 }
542 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
543 }
544
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700545 public boolean isTypeSupported(int type) {
546 return isNetworkTypeValid(type) && mTypeLists[type] != null;
547 }
548
549 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900550 synchronized (mTypeLists) {
551 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
552 return mTypeLists[type].get(0);
553 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700554 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900555 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700556 }
557
Robert Greenwalt8d482522015-06-24 13:23:42 -0700558 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900559 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900560 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700561 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900562 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900563 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900564 }
565 }
566
567 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700568 public void add(int type, NetworkAgentInfo nai) {
569 if (!isTypeSupported(type)) {
570 return; // Invalid network type.
571 }
572 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
573
574 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
575 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700576 return;
577 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900578 synchronized (mTypeLists) {
579 list.add(nai);
580 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900581
582 // 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 +0900583 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900584 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700585 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
586 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700587 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700588 }
589
Lorenzo Colittia793a672014-07-31 23:20:17 +0900590 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900591 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900592 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
593 if (list == null || list.isEmpty()) {
594 return;
595 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900596 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900597
Hugo Benichi78caa2582016-06-21 09:48:07 +0900598 synchronized (mTypeLists) {
599 if (!list.remove(nai)) {
600 return;
601 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900602 }
603
Robert Greenwalt8d482522015-06-24 13:23:42 -0700604 final DetailedState state = DetailedState.DISCONNECTED;
605
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900606 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700607 maybeLogBroadcast(nai, state, type, wasDefault);
608 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900609 }
610
611 if (!list.isEmpty() && wasFirstNetwork) {
612 if (DBG) log("Other network available for type " + type +
613 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900614 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700615 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
616 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900617 }
618 }
619
620 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
622 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700623 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900624 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700625 }
626 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700627
Robert Greenwalt8d482522015-06-24 13:23:42 -0700628 // send out another legacy broadcast - currently only used for suspend/unsuspend
629 // toggle
630 public void update(NetworkAgentInfo nai) {
631 final boolean isDefault = isDefaultNetwork(nai);
632 final DetailedState state = nai.networkInfo.getDetailedState();
633 for (int type = 0; type < mTypeLists.length; type++) {
634 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700635 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900636 final boolean isFirst = contains && (nai == list.get(0));
637 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700638 maybeLogBroadcast(nai, state, type, isDefault);
639 sendLegacyNetworkBroadcast(nai, state, type);
640 }
641 }
642 }
643
Lorenzo Colittia793a672014-07-31 23:20:17 +0900644 private String naiToString(NetworkAgentInfo nai) {
645 String name = (nai != null) ? nai.name() : "null";
646 String state = (nai.networkInfo != null) ?
647 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
648 "???/???";
649 return name + " " + state;
650 }
651
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700652 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900653 pw.println("mLegacyTypeTracker:");
654 pw.increaseIndent();
655 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700656 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900657 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700658 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900659 pw.println();
660 pw.println("Current state:");
661 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900662 synchronized (mTypeLists) {
663 for (int type = 0; type < mTypeLists.length; type++) {
664 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
665 for (NetworkAgentInfo nai : mTypeLists[type]) {
666 pw.println(type + " " + naiToString(nai));
667 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900668 }
669 }
670 pw.decreaseIndent();
671 pw.decreaseIndent();
672 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700673 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700674 }
675 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
676
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900677 @VisibleForTesting
678 protected HandlerThread createHandlerThread() {
679 return new HandlerThread("ConnectivityServiceThread");
680 }
681
Jeff Sharkey899223b2012-08-04 15:24:58 -0700682 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700683 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900684 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
685 }
686
687 @VisibleForTesting
688 protected ConnectivityService(Context context, INetworkManagementService netManager,
689 INetworkStatsService statsService, INetworkPolicyManager policyManager,
690 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800691 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800692
Hugo Benichif9fdf872016-07-28 17:53:06 +0900693 mMetricsLog = logger;
Erik Klineda4bfa82015-04-30 12:58:40 +0900694 mDefaultRequest = createInternetRequestForTransport(-1);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900695 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900696 mNetworkRequests.put(mDefaultRequest, defaultNRI);
697 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900698
699 mDefaultMobileDataRequest = createInternetRequestForTransport(
700 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700701
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900702 mHandlerThread = createHandlerThread();
703 mHandlerThread.start();
704 mHandler = new InternalHandler(mHandlerThread.getLooper());
705 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700706
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800707 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800708 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
709 String id = Settings.Secure.getString(context.getContentResolver(),
710 Settings.Secure.ANDROID_ID);
711 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700712 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800713 SystemProperties.set("net.hostname", name);
714 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800715 }
716
Jeremy Joslin79294842014-12-03 17:15:28 -0800717 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
718 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
719
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900720 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
721
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700722 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700723 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800724 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700725 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700726 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700727 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700728
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700729 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600730 mPolicyManager.setConnectivityListener(mPolicyListener);
731 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700732 } catch (RemoteException e) {
733 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700734 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700735 }
736
737 final PowerManager powerManager = (PowerManager) context.getSystemService(
738 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700739 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
740 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
741 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800742 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700743
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700744 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700745
Wink Saville51f456f2013-04-23 14:26:51 -0700746 // TODO: What is the "correct" way to do determine if this is a wifi only device?
747 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
748 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700749 String[] naStrings = context.getResources().getStringArray(
750 com.android.internal.R.array.networkAttributes);
751 for (String naString : naStrings) {
752 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700753 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700754 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700755 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800756 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700757 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700758 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700759 }
Wink Saville51f456f2013-04-23 14:26:51 -0700760 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
761 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
762 n.type);
763 continue;
764 }
Wink Saville975c8482011-04-07 14:23:45 -0700765 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800766 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700767 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700768 continue;
769 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700770 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700771
Wink Saville975c8482011-04-07 14:23:45 -0700772 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700773 mNetworksDefined++;
774 } catch(Exception e) {
775 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700776 }
777 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700778
779 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
780 if (mNetConfigs[TYPE_VPN] == null) {
781 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
782 // don't need to add TYPE_VPN to mNetConfigs.
783 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
784 mNetworksDefined++; // used only in the log() statement below.
785 }
786
Wink Saville5e56bc52013-07-29 15:00:57 -0700787 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700788
Robert Greenwalt50393202011-06-21 17:26:14 -0700789 mProtectedNetworks = new ArrayList<Integer>();
790 int[] protectedNetworks = context.getResources().getIntArray(
791 com.android.internal.R.array.config_protectedNetworks);
792 for (int p : protectedNetworks) {
793 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
794 mProtectedNetworks.add(p);
795 } else {
796 if (DBG) loge("Ignoring protectedNetwork " + p);
797 }
798 }
799
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700800 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
801 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700802
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800803 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800804
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700805 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
806
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700807 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700808 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100809 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700810 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700811 intentFilter.addAction(Intent.ACTION_USER_ADDED);
812 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000813 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700814 mContext.registerReceiverAsUser(
815 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900816
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700817 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700818 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700819 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700820 } catch (RemoteException e) {
821 loge("Error registering observer :" + e);
822 }
823
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700824 if (DBG) {
825 mInetLog = new ArrayList();
826 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700827
Erik Klineda4bfa82015-04-30 12:58:40 +0900828 mSettingsObserver = new SettingsObserver(mContext, mHandler);
829 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800830
John Spurlockbf991a82013-06-24 14:20:23 -0400831 mDataConnectionStats = new DataConnectionStats(mContext);
832 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400833
Jason Monkdecd2952013-10-10 14:02:51 -0400834 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700835
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400836 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900837
838 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900839 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
840 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900841 mLingerMonitor = new LingerMonitor(mContext, mNotifier);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700843
Erik Klineda4bfa82015-04-30 12:58:40 +0900844 private NetworkRequest createInternetRequestForTransport(int transportType) {
845 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900846 netCap.addCapability(NET_CAPABILITY_INTERNET);
847 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900848 if (transportType > -1) {
849 netCap.addTransportType(transportType);
850 }
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900851 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(),
852 NetworkRequest.Type.REQUEST);
Erik Klineda4bfa82015-04-30 12:58:40 +0900853 }
854
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900855 // Used only for testing.
856 // TODO: Delete this and either:
857 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
858 // changing ContentResolver to make registerContentObserver non-final).
859 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
860 // by subclassing SettingsObserver.
861 @VisibleForTesting
862 void updateMobileDataAlwaysOn() {
863 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
864 }
865
Erik Klineda4bfa82015-04-30 12:58:40 +0900866 private void handleMobileDataAlwaysOn() {
867 final boolean enable = (Settings.Global.getInt(
868 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
869 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
870 if (enable == isEnabled) {
871 return; // Nothing to do.
872 }
873
874 if (enable) {
875 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900876 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900877 } else {
878 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
879 }
880 }
881
882 private void registerSettingsCallbacks() {
883 // Watch for global HTTP proxy changes.
884 mSettingsObserver.observe(
885 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
886 EVENT_APPLY_GLOBAL_HTTP_PROXY);
887
888 // Watch for whether or not to keep mobile data always on.
889 mSettingsObserver.observe(
890 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
891 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
892 }
893
Robert Greenwalt34524f02014-05-18 16:22:10 -0700894 private synchronized int nextNetworkRequestId() {
895 return mNextNetworkRequestId++;
896 }
897
Paul Jensen67b0b072015-06-10 11:22:17 -0400898 @VisibleForTesting
899 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400900 synchronized (mNetworkForNetId) {
901 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
902 int netId = mNextNetId;
903 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
904 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500905 if (!mNetIdInUse.get(netId)) {
906 mNetIdInUse.put(netId, true);
907 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400908 }
909 }
910 }
911 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700912 }
913
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600914 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800915 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600916 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
917 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800918 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600919 state = nai.getNetworkState();
920 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800921 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600922 final NetworkInfo info = new NetworkInfo(networkType, 0,
923 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800924 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
925 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600926 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
927 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800928 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600929 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600930 return state;
931 } else {
932 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800933 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400934 }
935
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800936 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
937 if (network == null) {
938 return null;
939 }
940 synchronized (mNetworkForNetId) {
941 return mNetworkForNetId.get(network.netId);
942 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600943 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800944
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900945 private Network[] getVpnUnderlyingNetworks(int uid) {
946 if (!mLockdownEnabled) {
947 int user = UserHandle.getUserId(uid);
948 synchronized (mVpns) {
949 Vpn vpn = mVpns.get(user);
950 if (vpn != null && vpn.appliesToUid(uid)) {
951 return vpn.getUnderlyingNetworks();
952 }
953 }
954 }
955 return null;
956 }
957
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800958 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400959 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800960
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900961 final Network[] networks = getVpnUnderlyingNetworks(uid);
962 if (networks != null) {
963 // getUnderlyingNetworks() returns:
964 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
965 // empty array => the VPN explicitly said "no default network".
966 // non-empty array => the VPN specified one or more default networks; we use the
967 // first one.
968 if (networks.length > 0) {
969 nai = getNetworkAgentInfoForNetwork(networks[0]);
970 } else {
971 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800972 }
973 }
974
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800975 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600976 return nai.getNetworkState();
977 } else {
978 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800979 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400980 }
981
982 /**
983 * Check if UID should be blocked from using the network with the given LinkProperties.
984 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600985 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
986 boolean ignoreBlocked) {
987 // Networks aren't blocked when ignoring blocked status
988 if (ignoreBlocked) return false;
989 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -0700990 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600991
992 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700993 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700994
Robin Lee17e61832016-05-09 13:46:28 +0100995 synchronized (mVpns) {
996 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
997 if (vpn != null && vpn.isBlockingUid(uid)) {
998 return true;
999 }
1000 }
1001
Robert Greenwalt12e67352014-05-13 21:41:06 -07001002 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001003 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001004 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001005 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001006 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001007
Felipe Lemed31a97f2016-05-06 14:53:50 -07001008 boolean allowed = true;
1009 // Check Data Saver Mode first...
1010 if (networkMetered) {
1011 if ((uidRules & RULE_REJECT_METERED) != 0) {
1012 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1013 // Explicitly blacklisted.
1014 allowed = false;
1015 } else {
1016 allowed = !mRestrictBackground
1017 || (uidRules & RULE_ALLOW_METERED) != 0
1018 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1019 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1020 + " mRestrictBackground=" + mRestrictBackground
1021 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1022 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1023 + ": " + allowed);
1024 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001025 }
Felipe Leme781ba142016-05-09 16:24:48 -07001026 // ...then power restrictions.
1027 if (allowed) {
1028 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001029 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001030 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001031 }
1032 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001033 }
1034
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001035 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001036 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1037 return;
1038 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001039 boolean removed = false;
1040 boolean added = false;
1041 synchronized (mBlockedAppUids) {
1042 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1043 added = true;
1044 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1045 removed = true;
1046 }
1047 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001048 if (added) {
1049 log("Returning blocked NetworkInfo to uid=" + uid);
1050 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1051 } else if (removed) {
1052 log("Returning unblocked NetworkInfo to uid=" + uid);
1053 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1054 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001055 }
1056
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001057 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001058 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1059 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1060 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1061 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001062 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001063 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001064 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1065
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001066 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001067 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001068 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001069 if (mLockdownTracker != null) {
1070 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001071 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001072
1073 // TODO: apply metered state closer to NetworkAgentInfo
1074 final long token = Binder.clearCallingIdentity();
1075 try {
1076 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1077 } catch (RemoteException e) {
1078 } finally {
1079 Binder.restoreCallingIdentity(token);
1080 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001081 }
1082
1083 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 * Return NetworkInfo for the active (i.e., connected) network interface.
1085 * It is assumed that at most one network is active at a time. If more
1086 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001087 * @return the info for the active network, or {@code null} if none is
1088 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001090 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001092 enforceAccessPermission();
1093 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001094 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001095 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001096 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1097 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 }
1099
Paul Jensen31a94f42015-02-13 14:18:39 -05001100 @Override
1101 public Network getActiveNetwork() {
1102 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001103 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001104 }
1105
1106 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001107 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001108 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001109 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001110 }
1111
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001112 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001113 final int user = UserHandle.getUserId(uid);
1114 int vpnNetId = NETID_UNSET;
1115 synchronized (mVpns) {
1116 final Vpn vpn = mVpns.get(user);
1117 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1118 }
1119 NetworkAgentInfo nai;
1120 if (vpnNetId != NETID_UNSET) {
1121 synchronized (mNetworkForNetId) {
1122 nai = mNetworkForNetId.get(vpnNetId);
1123 }
1124 if (nai != null) return nai.network;
1125 }
1126 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001127 if (nai != null
1128 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1129 nai = null;
1130 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001131 return nai != null ? nai.network : null;
1132 }
1133
Lorenzo Colitti18660282016-07-04 12:55:44 +09001134 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001135 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1136 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001137 final int uid = Binder.getCallingUid();
1138 NetworkState state = getUnfilteredActiveNetworkState(uid);
1139 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001140 }
1141
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001142 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001143 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001144 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001145 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001146 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001147 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001148 }
1149
1150 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 public NetworkInfo getNetworkInfo(int networkType) {
1152 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001153 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001154 if (getVpnUnderlyingNetworks(uid) != null) {
1155 // A VPN is active, so we may need to return one of its underlying networks. This
1156 // information is not available in LegacyTypeTracker, so we have to get it from
1157 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001158 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001159 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001160 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001161 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001162 }
1163 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001164 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001165 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
1167
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001169 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001170 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001171 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001173 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001174 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001175 return state.networkInfo;
1176 } else {
1177 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001178 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001179 }
1180
1181 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 public NetworkInfo[] getAllNetworkInfo() {
1183 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001184 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001185 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1186 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 NetworkInfo info = getNetworkInfo(networkType);
1188 if (info != null) {
1189 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001192 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 }
1194
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001195 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001196 public Network getNetworkForType(int networkType) {
1197 enforceAccessPermission();
1198 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001199 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1200 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001201 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001202 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001203 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001204 }
1205
1206 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001207 public Network[] getAllNetworks() {
1208 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001209 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001210 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001211 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001212 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001213 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001214 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001215 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001216 }
1217
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001218 @Override
1219 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1220 // The basic principle is: if an app's traffic could possibly go over a
1221 // network, without the app doing anything multinetwork-specific,
1222 // (hence, by "default"), then include that network's capabilities in
1223 // the array.
1224 //
1225 // In the normal case, app traffic only goes over the system's default
1226 // network connection, so that's the only network returned.
1227 //
1228 // With a VPN in force, some app traffic may go into the VPN, and thus
1229 // over whatever underlying networks the VPN specifies, while other app
1230 // traffic may go over the system default network (e.g.: a split-tunnel
1231 // VPN, or an app disallowed by the VPN), so the set of networks
1232 // returned includes the VPN's underlying networks and the system
1233 // default.
1234 enforceAccessPermission();
1235
1236 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1237
1238 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001239 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001240 if (nc != null) {
1241 result.put(nai.network, nc);
1242 }
1243
1244 if (!mLockdownEnabled) {
1245 synchronized (mVpns) {
1246 Vpn vpn = mVpns.get(userId);
1247 if (vpn != null) {
1248 Network[] networks = vpn.getUnderlyingNetworks();
1249 if (networks != null) {
1250 for (Network network : networks) {
1251 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001252 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001253 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001254 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001255 }
1256 }
1257 }
1258 }
1259 }
1260 }
1261
1262 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1263 out = result.values().toArray(out);
1264 return out;
1265 }
1266
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001267 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001268 public boolean isNetworkSupported(int networkType) {
1269 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001270 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001271 }
1272
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001273 /**
1274 * Return LinkProperties for the active (i.e., connected) default
1275 * network interface. It is assumed that at most one default network
1276 * is active at a time. If more than one is active, it is indeterminate
1277 * which will be returned.
1278 * @return the ip properties for the active network, or {@code null} if
1279 * none is active
1280 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001281 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001282 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001283 enforceAccessPermission();
1284 final int uid = Binder.getCallingUid();
1285 NetworkState state = getUnfilteredActiveNetworkState(uid);
1286 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001287 }
1288
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001289 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001290 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001291 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001292 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1293 if (nai != null) {
1294 synchronized (nai) {
1295 return new LinkProperties(nai.linkProperties);
1296 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001297 }
1298 return null;
1299 }
1300
Robert Greenwalt12e67352014-05-13 21:41:06 -07001301 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001302 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001303 public LinkProperties getLinkProperties(Network network) {
1304 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001305 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001306 if (nai != null) {
1307 synchronized (nai) {
1308 return new LinkProperties(nai.linkProperties);
1309 }
1310 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001311 return null;
1312 }
1313
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001314 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001315 if (nai != null) {
1316 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001317 if (nai.networkCapabilities != null) {
1318 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001319 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001320 }
1321 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001322 return null;
1323 }
1324
1325 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001326 public NetworkCapabilities getNetworkCapabilities(Network network) {
1327 enforceAccessPermission();
1328 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1329 }
1330
1331 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001332 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001333 // Require internal since we're handing out IMSI details
1334 enforceConnectivityInternalPermission();
1335
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001336 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001337 for (Network network : getAllNetworks()) {
1338 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1339 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001340 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001341 }
1342 }
1343 return result.toArray(new NetworkState[result.size()]);
1344 }
1345
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001346 @Override
1347 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1348 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001349 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001350 final long token = Binder.clearCallingIdentity();
1351 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001352 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1353 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001354 try {
1355 return mPolicyManager.getNetworkQuotaInfo(state);
1356 } catch (RemoteException e) {
1357 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001358 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001359 return null;
1360 } finally {
1361 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001362 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001363 }
1364
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001365 @Override
1366 public boolean isActiveNetworkMetered() {
1367 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001368
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001369 final NetworkInfo info = getActiveNetworkInfo();
1370 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001371 }
1372
Jeff Sharkey216c1812012-08-05 14:29:23 -07001373 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1374 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001375 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001376 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001377 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001378 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001379 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001380
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001381 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 * Ensure that a network route exists to deliver traffic to the specified
1383 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001384 * @param networkType the type of the network over which traffic to the
1385 * specified host is to be routed
1386 * @param hostAddress the IP address of the host to which the route is
1387 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 * @return {@code true} on success, {@code false} on failure
1389 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001390 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001391 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001393 if (mProtectedNetworks.contains(networkType)) {
1394 enforceConnectivityInternalPermission();
1395 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001396
Chad Brubakerc0234532014-02-14 13:24:29 -08001397 InetAddress addr;
1398 try {
1399 addr = InetAddress.getByAddress(hostAddress);
1400 } catch (UnknownHostException e) {
1401 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1402 return false;
1403 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001406 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 return false;
1408 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001409
1410 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1411 if (nai == null) {
1412 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1413 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1414 } else {
1415 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1416 }
1417 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001418 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001419
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001420 DetailedState netState;
1421 synchronized (nai) {
1422 netState = nai.networkInfo.getDetailedState();
1423 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001424
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001425 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001426 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001427 log("requestRouteToHostAddress on down network "
1428 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001429 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001430 }
1431 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001433
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001434 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001435 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001436 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001437 LinkProperties lp;
1438 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001439 synchronized (nai) {
1440 lp = nai.linkProperties;
1441 netId = nai.network.netId;
1442 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001443 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001444 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1445 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001446 } finally {
1447 Binder.restoreCallingIdentity(token);
1448 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001449 }
1450
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001451 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001452 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001453 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001454 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001455 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001456 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001457 if (bestRoute.getGateway().equals(addr)) {
1458 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001459 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001460 } else {
1461 // if we will connect to this through another route, add a direct route
1462 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001463 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001464 }
1465 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001466 if (DBG) log("Adding legacy route " + bestRoute +
1467 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001468 try {
1469 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1470 } catch (Exception e) {
1471 // never crash - catch them all
1472 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001473 return false;
1474 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001475 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
1477
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001478 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1479 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001480 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001481 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001482 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001483 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001484 }
1485
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001486 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001487 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001488 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001489 if (oldRules == uidRules) return;
1490
Felipe Leme781ba142016-05-09 16:24:48 -07001491 if (uidRules == RULE_NONE) {
1492 mUidRules.delete(uid);
1493 } else {
1494 mUidRules.put(uid, uidRules);
1495 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001496 }
1497
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001498 // TODO: notify UID when it has requested targeted updates
1499 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001500
1501 @Override
1502 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001503 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001504 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001505 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001506 }
1507
1508 synchronized (mRulesLock) {
1509 mMeteredIfaces.clear();
1510 for (String iface : meteredIfaces) {
1511 mMeteredIfaces.add(iface);
1512 }
1513 }
1514 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001515
1516 @Override
1517 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1518 // caller is NPMS, since we only register with them
1519 if (LOGD_RULES) {
1520 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1521 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001522
1523 synchronized (mRulesLock) {
1524 mRestrictBackground = restrictBackground;
1525 }
1526
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001527 if (restrictBackground) {
1528 log("onRestrictBackgroundChanged(true): disabling tethering");
1529 mTethering.untetherAll();
1530 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001531 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001532
1533 @Override
1534 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1535 if (LOGD_RULES) {
1536 // caller is NPMS, since we only register with them
1537 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1538 + whitelisted + ")");
1539 }
1540 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001541 @Override
1542 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1543 if (LOGD_RULES) {
1544 // caller is NPMS, since we only register with them
1545 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1546 + blacklisted + ")");
1547 }
1548 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001549 };
1550
Robin Lee3b3dd942015-05-12 18:14:58 +01001551 /**
1552 * Require that the caller is either in the same user or has appropriate permission to interact
1553 * across users.
1554 *
1555 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1556 */
1557 private void enforceCrossUserPermission(int userId) {
1558 if (userId == UserHandle.getCallingUserId()) {
1559 // Not a cross-user call.
1560 return;
1561 }
1562 mContext.enforceCallingOrSelfPermission(
1563 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1564 "ConnectivityService");
1565 }
1566
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001567 private void enforceInternetPermission() {
1568 mContext.enforceCallingOrSelfPermission(
1569 android.Manifest.permission.INTERNET,
1570 "ConnectivityService");
1571 }
1572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001574 mContext.enforceCallingOrSelfPermission(
1575 android.Manifest.permission.ACCESS_NETWORK_STATE,
1576 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
1578
1579 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001580 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 }
1582
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001583 private void enforceTetherAccessPermission() {
1584 mContext.enforceCallingOrSelfPermission(
1585 android.Manifest.permission.ACCESS_NETWORK_STATE,
1586 "ConnectivityService");
1587 }
1588
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001589 private void enforceConnectivityInternalPermission() {
1590 mContext.enforceCallingOrSelfPermission(
1591 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1592 "ConnectivityService");
1593 }
1594
Hugo Benichi514da602016-07-19 15:59:27 +09001595 private void enforceConnectivityRestrictedNetworksPermission() {
1596 try {
1597 mContext.enforceCallingOrSelfPermission(
1598 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1599 "ConnectivityService");
1600 return;
1601 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1602 enforceConnectivityInternalPermission();
1603 }
1604
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001605 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001606 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001607 }
1608
Lorenzo Colitti18660282016-07-04 12:55:44 +09001609 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001610 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001611 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001612 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001613 }
1614
1615 private void sendInetConditionBroadcast(NetworkInfo info) {
1616 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1617 }
1618
Wink Saville628b0852011-08-04 15:01:58 -07001619 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001620 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001621 info = new NetworkInfo(info);
1622 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001623 }
1624
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001625 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001626 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001627 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 if (info.isFailover()) {
1629 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1630 info.setFailover(false);
1631 }
1632 if (info.getReason() != null) {
1633 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1634 }
1635 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001636 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1637 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001639 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001640 return intent;
1641 }
1642
1643 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1644 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1645 }
1646
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001647 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001648 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1649 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1650 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001651 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001652 final long ident = Binder.clearCallingIdentity();
1653 try {
1654 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1655 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1656 } finally {
1657 Binder.restoreCallingIdentity(ident);
1658 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001659 }
1660
Mike Lockwood0f79b542009-08-14 14:18:49 -04001661 private void sendStickyBroadcast(Intent intent) {
1662 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001663 if (!mSystemReady) {
1664 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001665 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001666 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001667 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001668 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001669 }
1670
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001671 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001672 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001673 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001674 final NetworkInfo ni = intent.getParcelableExtra(
1675 ConnectivityManager.EXTRA_NETWORK_INFO);
1676 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1677 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1678 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001679 } else {
1680 BroadcastOptions opts = BroadcastOptions.makeBasic();
1681 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1682 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001683 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001684 final IBatteryStats bs = BatteryStatsService.getService();
1685 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001686 bs.noteConnectivityChanged(intent.getIntExtra(
1687 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1688 ni != null ? ni.getState().toString() : "?");
1689 } catch (RemoteException e) {
1690 }
1691 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001692 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001693 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001694 } finally {
1695 Binder.restoreCallingIdentity(ident);
1696 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001697 }
1698 }
1699
1700 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001701 loadGlobalProxy();
1702
Mike Lockwood0f79b542009-08-14 14:18:49 -04001703 synchronized(this) {
1704 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001705 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001706 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001707 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001708 }
1709 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001710 // load the global proxy at startup
1711 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001712
Robin Lee244ce8e2016-01-05 18:03:46 +00001713 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1714 // for user to unlock device too.
1715 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001716
Erik Klineda4bfa82015-04-30 12:58:40 +09001717 // Configure whether mobile data is always on.
1718 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1719
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001721
1722 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 }
1724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001726 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001727 *
1728 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001729 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001730 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001731 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1732 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001733
1734 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001735 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001736
Robert Greenwalt7b816022014-04-18 15:25:25 -07001737 if (networkAgent.networkCapabilities.hasTransport(
1738 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001739 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1740 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001741 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001742 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001743 } else if (networkAgent.networkCapabilities.hasTransport(
1744 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001745 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1746 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001747 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001748 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001749 } else {
1750 // do not track any other networks
1751 timeout = 0;
1752 }
1753
Robert Greenwalt7b816022014-04-18 15:25:25 -07001754 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001755 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001756 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001757 } catch (Exception e) {
1758 // You shall not crash!
1759 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001760 }
1761 }
1762 }
1763
1764 /**
1765 * Remove data activity tracking when network disconnects.
1766 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001767 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1768 final String iface = networkAgent.linkProperties.getInterfaceName();
1769 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001770
Robert Greenwalt7b816022014-04-18 15:25:25 -07001771 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1772 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001773 try {
1774 // the call fails silently if no idletimer setup for this interface
1775 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001776 } catch (Exception e) {
1777 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001778 }
1779 }
1780 }
1781
1782 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001783 * Reads the network specific MTU size from reources.
1784 * and set it on it's iface.
1785 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001786 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1787 final String iface = newLp.getInterfaceName();
1788 final int mtu = newLp.getMtu();
1789 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1790 if (VDBG) log("identical MTU - not setting");
1791 return;
1792 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001793
Robert Greenwalt43074032014-08-15 17:53:05 -07001794 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001795 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001796 return;
1797 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001798
w1997615afd812014-08-05 15:18:11 -07001799 // Cannot set MTU without interface name
1800 if (TextUtils.isEmpty(iface)) {
1801 loge("Setting MTU size with null iface.");
1802 return;
1803 }
1804
Robert Greenwalt7b816022014-04-18 15:25:25 -07001805 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001806 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001807 mNetd.setMtu(iface, mtu);
1808 } catch (Exception e) {
1809 Slog.e(TAG, "exception in setMtu()" + e);
1810 }
1811 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001812
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001813 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001814 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1815
1816 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001817 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001818 protected int getDefaultTcpRwnd() {
1819 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1820 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001821
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001822 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1823 if (isDefaultNetwork(nai) == false) {
1824 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001825 }
1826
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001827 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1828 String[] values = null;
1829 if (tcpBufferSizes != null) {
1830 values = tcpBufferSizes.split(",");
1831 }
1832
1833 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001834 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001835 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1836 values = tcpBufferSizes.split(",");
1837 }
1838
1839 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1840
1841 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001842 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001843
1844 final String prefix = "/sys/kernel/ipv4/tcp_";
1845 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1846 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1847 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1848 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1849 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1850 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1851 mCurrentTcpBufferSizes = tcpBufferSizes;
1852 } catch (IOException e) {
1853 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001854 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001855
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001856 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001857 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001858 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1859 if (rwndValue != 0) {
1860 SystemProperties.set(sysctlKey, rwndValue.toString());
1861 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001862 }
1863
Mattias Falk8b47b362011-08-23 14:15:13 +02001864 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001865 /*
1866 * Tell the VMs to toss their DNS caches
1867 */
1868 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1869 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001870 /*
1871 * Connectivity events can happen before boot has completed ...
1872 */
1873 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001874 final long ident = Binder.clearCallingIdentity();
1875 try {
1876 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1877 } finally {
1878 Binder.restoreCallingIdentity(ident);
1879 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001880 }
1881
Robert Greenwalt562cc542014-05-15 18:07:26 -07001882 @Override
1883 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001884 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1885 NETWORK_RESTORE_DELAY_PROP_NAME);
1886 if(restoreDefaultNetworkDelayStr != null &&
1887 restoreDefaultNetworkDelayStr.length() != 0) {
1888 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001889 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001890 } catch (NumberFormatException e) {
1891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001893 // if the system property isn't set, use the value for the apn type
1894 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1895
1896 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1897 (mNetConfigs[networkType] != null)) {
1898 ret = mNetConfigs[networkType].restoreTime;
1899 }
1900 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
1902
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001903 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001904 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001905 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001906 }
1907 return false;
1908 }
1909
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001910 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1911 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1912 final long DIAG_TIME_MS = 5000;
1913 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1914 // Start gathering diagnostic information.
1915 netDiags.add(new NetworkDiagnostics(
1916 nai.network,
1917 new LinkProperties(nai.linkProperties), // Must be a copy.
1918 DIAG_TIME_MS));
1919 }
1920
1921 for (NetworkDiagnostics netDiag : netDiags) {
1922 pw.println();
1923 netDiag.waitForMeasurements();
1924 netDiag.dump(pw);
1925 }
1926 }
1927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001929 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1930 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001931 if (mContext.checkCallingOrSelfPermission(
1932 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001934 pw.println("Permission Denial: can't dump ConnectivityService " +
1935 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1936 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 return;
1938 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001939
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001940 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001941 dumpNetworkDiagnostics(pw);
1942 return;
1943 }
Erik Kline379747a2015-06-05 17:47:34 +09001944
Lorenzo Colittie3805462015-06-03 11:18:24 +09001945 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001946 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001947 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001948 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001949 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001950 pw.println();
1951
Paul Jensen85cf78e2015-06-25 13:25:07 -04001952 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001953 pw.print("Active default network: ");
1954 if (defaultNai == null) {
1955 pw.println("none");
1956 } else {
1957 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001959 pw.println();
1960
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001961 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001962 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001963 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1964 pw.println(nai.toString());
1965 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001966 pw.println(String.format("Requests: %d request/%d total",
1967 nai.numRequestNetworkRequests(), nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001968 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001969 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1970 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001971 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001972 pw.decreaseIndent();
1973 pw.println("Lingered:");
1974 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001975 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001976 pw.decreaseIndent();
1977 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001978 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001979 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001980 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001981
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001982 pw.println("Metered Interfaces:");
1983 pw.increaseIndent();
1984 for (String value : mMeteredIfaces) {
1985 pw.println(value);
1986 }
1987 pw.decreaseIndent();
1988 pw.println();
1989
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001990 pw.print("Restrict background: ");
1991 pw.println(mRestrictBackground);
1992 pw.println();
1993
Felipe Leme46c4fc32016-05-04 09:21:43 -07001994 pw.println("Status for known UIDs:");
1995 pw.increaseIndent();
1996 final int size = mUidRules.size();
1997 for (int i = 0; i < size; i++) {
1998 final int uid = mUidRules.keyAt(i);
1999 pw.print("UID=");
2000 pw.print(uid);
2001 final int uidRules = mUidRules.get(uid, RULE_NONE);
2002 pw.print(" rules=");
2003 pw.print(uidRulesToString(uidRules));
2004 pw.println();
2005 }
2006 pw.println();
2007 pw.decreaseIndent();
2008
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002009 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002010 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002011 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2012 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002013 }
2014 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002015 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002016
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002017 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002018
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002019 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002020 pw.print("mNetTransitionWakeLock: currently " +
2021 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2022 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2023 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2024 } else {
2025 pw.println(", last requested never");
2026 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002027 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002028
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002029 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002030 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002031
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002032 pw.println();
2033 mKeepaliveTracker.dump(pw);
2034
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002035 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002036
Lorenzo Colittie3805462015-06-03 11:18:24 +09002037 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002038 pw.println();
2039 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002040 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002041 for(int i = 0; i < mInetLog.size(); i++) {
2042 pw.println(mInetLog.get(i));
2043 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002044 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002045 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002046
2047 if (argsContain(args, "--short") == false) {
2048 pw.println();
2049 synchronized (mValidationLogs) {
2050 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002051 for (ValidationLog p : mValidationLogs) {
2052 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002053 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002054 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002055 pw.decreaseIndent();
2056 }
2057 }
Erik Kline7523eb32015-07-09 18:24:03 +09002058
2059 pw.println();
2060 pw.println("mNetworkRequestInfoLogs (most recent first):");
2061 pw.increaseIndent();
2062 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2063 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002064
2065 pw.println();
2066 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2067 pw.increaseIndent();
2068 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2069 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002073 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002074 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002075 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002076 if (officialNai != null && officialNai.equals(nai)) return true;
2077 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002078 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002079 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002080 " - " + nai);
2081 }
2082 return false;
2083 }
2084
Robert Greenwalt42acef32009-08-12 16:08:25 -07002085 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002086 private class NetworkStateTrackerHandler extends Handler {
2087 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002088 super(looper);
2089 }
2090
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002091 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002093 default:
2094 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002095 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002096 handleAsyncChannelHalfConnect(msg);
2097 break;
2098 }
2099 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2100 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2101 if (nai != null) nai.asyncChannel.disconnect();
2102 break;
2103 }
2104 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2105 handleAsyncChannelDisconnected(msg);
2106 break;
2107 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002108 }
2109 return true;
2110 }
2111
2112 private void maybeHandleNetworkAgentMessage(Message msg) {
2113 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2114 if (nai == null) {
2115 if (VDBG) {
2116 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2117 log(String.format("%s from unknown NetworkAgent", what));
2118 }
2119 return;
2120 }
2121
2122 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002123 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002124 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2125 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2126 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2127 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002128 }
Robin Lee585e2482016-05-01 23:00:00 +01002129 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002130 networkCapabilities)) {
2131 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2132 + nai.networkCapabilities + " -> " + networkCapabilities);
2133 }
2134 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002135 break;
2136 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002137 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002138 if (VDBG) {
2139 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002140 "; created=" + nai.created +
2141 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002142 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002143 LinkProperties oldLp = nai.linkProperties;
2144 synchronized (nai) {
2145 nai.linkProperties = (LinkProperties)msg.obj;
2146 }
Robin Lee585e2482016-05-01 23:00:00 +01002147 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002148 break;
2149 }
2150 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002151 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002152 updateNetworkInfo(nai, info);
2153 break;
2154 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002155 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002156 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002157 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002158 break;
2159 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002160 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002161 try {
2162 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002163 } catch (Exception e) {
2164 // Never crash!
2165 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002166 }
2167 break;
2168 }
2169 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002170 try {
2171 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002172 } catch (Exception e) {
2173 // Never crash!
2174 loge("Exception in removeVpnUidRanges: " + e);
2175 }
2176 break;
2177 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002178 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002179 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2180 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002181 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002182 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002183 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002184 break;
2185 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002186 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002187 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2188 break;
2189 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002190 }
2191 }
2192
2193 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2194 switch (msg.what) {
2195 default:
2196 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002197 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002198 final NetworkAgentInfo nai;
2199 synchronized (mNetworkForNetId) {
2200 nai = mNetworkForNetId.get(msg.arg2);
2201 }
2202 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002203 final boolean valid =
2204 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002205 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2206 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002207 if (valid != nai.lastValidated) {
2208 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002209 nai.lastValidated = valid;
2210 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002211 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002212 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2213 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002214 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002215 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002216 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002217 Bundle redirectUrlBundle = new Bundle();
2218 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002219 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002220 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002221 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002222 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002223 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002224 break;
2225 }
Paul Jensen869868be2014-05-15 10:33:05 -04002226 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002227 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002228 final boolean visible = (msg.arg1 != 0);
2229 final NetworkAgentInfo nai;
2230 synchronized (mNetworkForNetId) {
2231 nai = mNetworkForNetId.get(netId);
2232 }
2233 // If captive portal status has changed, update capabilities.
2234 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2235 nai.lastCaptivePortalDetected = visible;
2236 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002237 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002238 }
2239 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002240 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002241 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002242 if (nai == null) {
2243 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2244 break;
2245 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002246 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002247 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002248 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002249 }
Paul Jensen869868be2014-05-15 10:33:05 -04002250 }
Paul Jensen869868be2014-05-15 10:33:05 -04002251 break;
2252 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002253 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002254 return true;
2255 }
2256
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002257 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2258 switch (msg.what) {
2259 default:
2260 return false;
2261 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2262 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2263 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2264 handleLingerComplete(nai);
2265 }
2266 break;
2267 }
2268 }
2269 return true;
2270 }
2271
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002272 @Override
2273 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002274 if (!maybeHandleAsyncChannelMessage(msg) &&
2275 !maybeHandleNetworkMonitorMessage(msg) &&
2276 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002277 maybeHandleNetworkAgentMessage(msg);
2278 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002279 }
2280 }
2281
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002282 private void updateLingerState(NetworkAgentInfo nai, long now) {
2283 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2284 // 2. If the network was lingering and there are now requests, unlinger it.
2285 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2286 // one lingered request, start lingering.
2287 nai.updateLingerTimer();
2288 if (nai.isLingering() && nai.numRequestNetworkRequests() > 0) {
2289 if (DBG) log("Unlingering " + nai.name());
2290 nai.unlinger();
2291 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
2292 } else if (unneeded(nai) && nai.getLingerExpiry() > 0) { // unneeded() calls isLingering()
2293 int lingerTime = (int) (nai.getLingerExpiry() - now);
2294 if (DBG) {
2295 Log.d(TAG, "Lingering " + nai.name() + " for " + lingerTime + "ms");
2296 }
2297 nai.linger();
2298 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2299 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2300 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002301 }
2302
Robert Greenwalt7b816022014-04-18 15:25:25 -07002303 private void handleAsyncChannelHalfConnect(Message msg) {
2304 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002305 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002306 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2307 if (VDBG) log("NetworkFactory connected");
2308 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002309 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002310 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002311 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002312 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002313 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002314 }
2315 } else {
2316 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002317 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002318 }
2319 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2320 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2321 if (VDBG) log("NetworkAgent connected");
2322 // A network agent has requested a connection. Establish the connection.
2323 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2324 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2325 } else {
2326 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002327 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002328 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002329 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002330 synchronized (mNetworkForNetId) {
2331 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002332 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002333 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002334 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002335 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002336 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002337 }
2338 }
2339 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002340
Robert Greenwalt7b816022014-04-18 15:25:25 -07002341 private void handleAsyncChannelDisconnected(Message msg) {
2342 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2343 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002344 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002345 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002346 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002347 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002348 // TODO - if we move the logic to the network agent (have them disconnect
2349 // because they lost all their requests or because their score isn't good)
2350 // then they would disconnect organically, report their new state and then
2351 // disconnect the channel.
2352 if (nai.networkInfo.isConnected()) {
2353 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2354 null, null);
2355 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002356 final boolean wasDefault = isDefaultNetwork(nai);
2357 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002358 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002359 // Log default network disconnection before required book-keeping.
2360 // Let rematchAllNetworksAndRequests() below record a new default network event
2361 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2362 // whose timestamps tell how long it takes to recover a default network.
2363 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002364 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002365 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002366 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2367 // by other networks that are already connected. Perhaps that can be done by
2368 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2369 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002370 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002371 mKeepaliveTracker.handleStopAllKeepalives(nai,
2372 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002373 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002374 mNetworkAgentInfos.remove(msg.replyTo);
2375 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002376 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002377 // Remove the NetworkAgent, but don't mark the netId as
2378 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002379 mNetworkForNetId.remove(nai.network.netId);
2380 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002381 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002382 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2383 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002384 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2385 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2386 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002387 sendUpdatedScoreToFactories(request, 0);
2388 }
2389 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002390 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002391 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002392 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002393 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002394 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002395 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002396 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002397 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002398 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002399 if (nai.created) {
2400 // Tell netd to clean up the configuration for this network
2401 // (routing rules, DNS, etc).
2402 // This may be slow as it requires a lot of netd shelling out to ip and
2403 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2404 // after we've rematched networks with requests which should make a potential
2405 // fallback network the default or requested a new network from the
2406 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2407 // long time.
2408 try {
2409 mNetd.removeNetwork(nai.network.netId);
2410 } catch (Exception e) {
2411 loge("Exception removing network: " + e);
2412 }
2413 }
2414 synchronized (mNetworkForNetId) {
2415 mNetIdInUse.delete(nai.network.netId);
2416 }
2417 } else {
2418 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2419 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002420 }
2421 }
2422
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002423 // If this method proves to be too slow then we can maintain a separate
2424 // pendingIntent => NetworkRequestInfo map.
2425 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2426 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2427 Intent intent = pendingIntent.getIntent();
2428 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2429 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2430 if (existingPendingIntent != null &&
2431 existingPendingIntent.getIntent().filterEquals(intent)) {
2432 return entry.getValue();
2433 }
2434 }
2435 return null;
2436 }
2437
2438 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2439 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2440
2441 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2442 if (existingRequest != null) { // remove the existing request.
2443 if (DBG) log("Replacing " + existingRequest.request + " with "
2444 + nri.request + " because their intents matched.");
2445 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2446 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002447 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002448 }
2449
Erik Klineda4bfa82015-04-30 12:58:40 +09002450 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002451 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002452 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002453 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002454 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002455 if (nri.request.networkCapabilities.hasSignalStrength() &&
2456 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2457 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002458 }
2459 }
2460 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002461 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002462 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002463 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002464 }
2465 }
2466
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002467 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2468 int callingUid) {
2469 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2470 if (nri != null) {
2471 handleReleaseNetworkRequest(nri.request, callingUid);
2472 }
2473 }
2474
Paul Jensen99364842014-12-09 11:43:45 -05002475 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002476 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2477 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002478 private boolean unneeded(NetworkAgentInfo nai) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002479 if (!nai.everConnected || nai.isVPN() ||
2480 nai.isLingering() || nai.numRequestNetworkRequests() > 0) {
2481 return false;
2482 }
Paul Jensene0988542015-06-25 15:30:08 -04002483 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2484 // If this Network is already the highest scoring Network for a request, or if
2485 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002486 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002487 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002488 // Note that this catches two important cases:
2489 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2490 // is currently satisfying the request. This is desirable when
2491 // cellular ends up validating but WiFi does not.
2492 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002493 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002494 // WiFi ends up validating and out scoring cellular.
2495 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2496 nai.getCurrentScoreAsValidated())) {
2497 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002498 }
2499 }
Paul Jensene0988542015-06-25 15:30:08 -04002500 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002501 }
2502
Erik Klineacdd6392016-07-07 16:50:58 +09002503 private NetworkRequestInfo getNriForAppRequest(
2504 NetworkRequest request, int callingUid, String requestedOperation) {
2505 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2506
Robert Greenwalt9258c642014-03-26 16:47:06 -07002507 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002508 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002509 log(String.format("UID %d attempted to %s for unowned request %s",
2510 callingUid, requestedOperation, nri));
2511 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002512 }
Erik Klineacdd6392016-07-07 16:50:58 +09002513 }
2514
2515 return nri;
2516 }
2517
2518 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2519 String description, int callbackType) {
2520 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2521 if (nri == null) return;
2522
2523 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2524 // The network that is satisfying this request may have changed since
2525 // the application requested the update.
2526 //
2527 // - If the request is no longer satisfied, don't send any updates.
2528 // - If the request is satisfied by a different network, it is the
2529 // caller's responsibility to check that the Network object in the
2530 // callback matches the network that was returned in the last
2531 // onAvailable() callback for this request.
2532 if (nai == null) return;
2533 callCallbackForRequest(nri, nai, callbackType, 0);
2534 }
2535
2536 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2537 handleRequestCallbackUpdate(request, callingUid,
2538 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2539 }
2540
2541 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2542 handleRequestCallbackUpdate(request, callingUid,
2543 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2544 }
2545
2546 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2547 final NetworkRequestInfo nri = getNriForAppRequest(
2548 request, callingUid, "release NetworkRequest");
2549 if (nri == null) return;
2550
2551 if (VDBG || (DBG && nri.request.isRequest())) log("releasing " + request);
2552 nri.unlinkDeathRecipient();
2553 mNetworkRequests.remove(request);
2554 synchronized (mUidToNetworkRequestCount) {
2555 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2556 if (requests < 1) {
2557 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2558 nri.mUid);
2559 } else if (requests == 1) {
2560 mUidToNetworkRequestCount.removeAt(
2561 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2562 } else {
2563 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2564 }
2565 }
2566 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2567 if (nri.request.isRequest()) {
2568 boolean wasKept = false;
2569 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2570 if (nai != null) {
2571 nai.removeRequest(nri.request.requestId);
2572 if (VDBG) {
2573 log(" Removing from current network " + nai.name() +
2574 ", leaving " + nai.numNetworkRequests() + " requests.");
2575 }
2576 // If there are still lingered requests on this network, don't tear it down,
2577 // but resume lingering instead.
2578 updateLingerState(nai, SystemClock.elapsedRealtime());
2579 if (unneeded(nai)) {
2580 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2581 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002582 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002583 wasKept = true;
2584 }
2585 mNetworkForRequestId.remove(nri.request.requestId);
2586 }
2587
2588 // TODO: remove this code once we know that the Slog.wtf is never hit.
2589 //
2590 // Find all networks that are satisfying this request and remove the request
2591 // from their request lists.
2592 // TODO - it's my understanding that for a request there is only a single
2593 // network satisfying it, so this loop is wasteful
2594 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2595 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2596 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2597 otherNai.name() + ", but mNetworkAgentInfos says " +
2598 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002599 }
2600 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002601
Erik Klineacdd6392016-07-07 16:50:58 +09002602 // Maintain the illusion. When this request arrived, we might have pretended
2603 // that a network connected to serve it, even though the network was already
2604 // connected. Now that this request has gone away, we might have to pretend
2605 // that the network disconnected. LegacyTypeTracker will generate that
2606 // phantom disconnect for this type.
2607 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2608 boolean doRemove = true;
2609 if (wasKept) {
2610 // check if any of the remaining requests for this network are for the
2611 // same legacy type - if so, don't remove the nai
2612 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2613 NetworkRequest otherRequest = nai.requestAt(i);
2614 if (otherRequest.legacyType == nri.request.legacyType &&
2615 otherRequest.isRequest()) {
2616 if (DBG) log(" still have other legacy request - leaving");
2617 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002618 }
2619 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002620 }
2621
Erik Klineacdd6392016-07-07 16:50:58 +09002622 if (doRemove) {
2623 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002624 }
2625 }
Erik Klineacdd6392016-07-07 16:50:58 +09002626
2627 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2628 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2629 nri.request);
2630 }
2631 } else {
2632 // listens don't have a singular affectedNetwork. Check all networks to see
2633 // if this listen request applies and remove it.
2634 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2635 nai.removeRequest(nri.request.requestId);
2636 if (nri.request.networkCapabilities.hasSignalStrength() &&
2637 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2638 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2639 }
2640 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002641 }
Erik Klineacdd6392016-07-07 16:50:58 +09002642 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002643 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002644
Lorenzo Colitti18660282016-07-04 12:55:44 +09002645 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002646 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2647 enforceConnectivityInternalPermission();
2648 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2649 accept ? 1 : 0, always ? 1: 0, network));
2650 }
2651
2652 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2653 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2654 " accept=" + accept + " always=" + always);
2655
2656 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2657 if (nai == null) {
2658 // Nothing to do.
2659 return;
2660 }
2661
2662 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002663 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002664 return;
2665 }
2666
2667 if (!nai.networkMisc.explicitlySelected) {
2668 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2669 }
2670
2671 if (accept != nai.networkMisc.acceptUnvalidated) {
2672 int oldScore = nai.getCurrentScore();
2673 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002674 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002675 sendUpdatedScoreToFactories(nai);
2676 }
2677
2678 if (always) {
2679 nai.asyncChannel.sendMessage(
2680 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2681 }
2682
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002683 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002684 // Tell the NetworkAgent to not automatically reconnect to the network.
2685 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2686 // Teardown the nework.
2687 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002688 }
2689
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002690 }
2691
2692 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002693 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002694 mHandler.sendMessageDelayed(
2695 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2696 PROMPT_UNVALIDATED_DELAY_MS);
2697 }
2698
2699 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002700 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002701 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2702
2703 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2704 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002705 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002706 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002707 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2708 return;
2709 }
2710
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002711 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002712 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002713 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2714 intent.setClassName("com.android.settings",
2715 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002716
2717 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2718 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
fionaxu1bf6ec22016-05-23 16:33:16 -07002719
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002720 mNotifier.showNotification(nai.network.netId, NotificationType.NO_INTERNET, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002721 pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002722 }
2723
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002724 private class InternalHandler extends Handler {
2725 public InternalHandler(Looper looper) {
2726 super(looper);
2727 }
2728
2729 @Override
2730 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002731 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002732 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002733 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002734 String causedBy = null;
2735 synchronized (ConnectivityService.this) {
2736 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2737 mNetTransitionWakeLock.isHeld()) {
2738 mNetTransitionWakeLock.release();
2739 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002740 } else {
2741 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002742 }
2743 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002744 if (VDBG) {
2745 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2746 log("Failed to find a new network - expiring NetTransition Wakelock");
2747 } else {
2748 log("NetTransition Wakelock (" +
2749 (causedBy == null ? "unknown" : causedBy) +
2750 " cleared because we found a replacement network");
2751 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002752 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002753 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002754 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002755 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002756 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002757 break;
2758 }
Jason Monkdecd2952013-10-10 14:02:51 -04002759 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002760 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002761 break;
2762 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002763 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002764 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2765 break;
2766 }
2767 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2768 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002769 break;
2770 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002771 case EVENT_REGISTER_NETWORK_AGENT: {
2772 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2773 break;
2774 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002775 case EVENT_REGISTER_NETWORK_REQUEST:
2776 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002777 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002778 break;
2779 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002780 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2781 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002782 handleRegisterNetworkRequestWithIntent(msg);
2783 break;
2784 }
2785 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2786 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2787 break;
2788 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002789 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002790 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002791 break;
2792 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002793 case EVENT_SET_ACCEPT_UNVALIDATED: {
2794 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2795 break;
2796 }
2797 case EVENT_PROMPT_UNVALIDATED: {
2798 handlePromptUnvalidated((Network) msg.obj);
2799 break;
2800 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002801 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2802 handleMobileDataAlwaysOn();
2803 break;
2804 }
Erik Klineacdd6392016-07-07 16:50:58 +09002805 case EVENT_REQUEST_LINKPROPERTIES:
2806 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2807 break;
2808 case EVENT_REQUEST_NETCAPABILITIES:
2809 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2810 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002811 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2812 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2813 mKeepaliveTracker.handleStartKeepalive(msg);
2814 break;
2815 }
2816 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2817 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2818 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2819 int slot = msg.arg1;
2820 int reason = msg.arg2;
2821 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2822 break;
2823 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002824 case EVENT_SYSTEM_READY: {
2825 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2826 nai.networkMonitor.systemReady = true;
2827 }
2828 break;
2829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 }
2831 }
2832 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002833
2834 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002835 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002836 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002837 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002838 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002839 final int status = mTethering.tether(iface);
2840 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2841 try {
2842 mPolicyManager.onTetheringChanged(iface, true);
2843 } catch (RemoteException e) {
2844 }
2845 }
2846 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002847 } else {
2848 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2849 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002850 }
2851
2852 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002853 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002854 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002855 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002856
2857 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002858 final int status = mTethering.untether(iface);
2859 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2860 try {
2861 mPolicyManager.onTetheringChanged(iface, false);
2862 } catch (RemoteException e) {
2863 }
2864 }
2865 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002866 } else {
2867 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2868 }
2869 }
2870
2871 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002872 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002873 public int getLastTetherError(String iface) {
2874 enforceTetherAccessPermission();
2875
2876 if (isTetheringSupported()) {
2877 return mTethering.getLastTetherError(iface);
2878 } else {
2879 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2880 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002881 }
2882
2883 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002884 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002885 public String[] getTetherableUsbRegexs() {
2886 enforceTetherAccessPermission();
2887 if (isTetheringSupported()) {
2888 return mTethering.getTetherableUsbRegexs();
2889 } else {
2890 return new String[0];
2891 }
2892 }
2893
Lorenzo Colitti18660282016-07-04 12:55:44 +09002894 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002895 public String[] getTetherableWifiRegexs() {
2896 enforceTetherAccessPermission();
2897 if (isTetheringSupported()) {
2898 return mTethering.getTetherableWifiRegexs();
2899 } else {
2900 return new String[0];
2901 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002902 }
2903
Lorenzo Colitti18660282016-07-04 12:55:44 +09002904 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002905 public String[] getTetherableBluetoothRegexs() {
2906 enforceTetherAccessPermission();
2907 if (isTetheringSupported()) {
2908 return mTethering.getTetherableBluetoothRegexs();
2909 } else {
2910 return new String[0];
2911 }
2912 }
2913
Lorenzo Colitti18660282016-07-04 12:55:44 +09002914 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002915 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002916 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002917 if (isTetheringSupported()) {
2918 return mTethering.setUsbTethering(enable);
2919 } else {
2920 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2921 }
2922 }
2923
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002924 // TODO - move iface listing, queries, etc to new module
2925 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002926 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002927 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002928 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002929 return mTethering.getTetherableIfaces();
2930 }
2931
Lorenzo Colitti18660282016-07-04 12:55:44 +09002932 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002933 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002934 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002935 return mTethering.getTetheredIfaces();
2936 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002937
Lorenzo Colitti18660282016-07-04 12:55:44 +09002938 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002939 public String[] getTetheringErroredIfaces() {
2940 enforceTetherAccessPermission();
2941 return mTethering.getErroredIfaces();
2942 }
2943
Lorenzo Colitti18660282016-07-04 12:55:44 +09002944 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002945 public String[] getTetheredDhcpRanges() {
2946 enforceConnectivityInternalPermission();
2947 return mTethering.getTetheredDhcpRanges();
2948 }
2949
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002950 // if ro.tether.denied = true we default to no tethering
2951 // gservices could set the secure setting to 1 though to enable it on a build where it
2952 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002953 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002954 public boolean isTetheringSupported() {
2955 enforceTetherAccessPermission();
2956 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002957 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002958 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2959 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002960 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2961 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002962 mTethering.getTetherableWifiRegexs().length != 0 ||
2963 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2964 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002965 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002966
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002967 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002968 public void startTethering(int type, ResultReceiver receiver,
2969 boolean showProvisioningUi) {
2970 ConnectivityManager.enforceTetherChangePermission(mContext);
2971 if (!isTetheringSupported()) {
2972 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2973 return;
2974 }
2975 mTethering.startTethering(type, receiver, showProvisioningUi);
2976 }
2977
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002978 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002979 public void stopTethering(int type) {
2980 ConnectivityManager.enforceTetherChangePermission(mContext);
2981 mTethering.stopTethering(type);
2982 }
2983
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002984 // Called when we lose the default network and have no replacement yet.
2985 // This will automatically be cleared after X seconds or a new default network
2986 // becomes CONNECTED, whichever happens first. The timer is started by the
2987 // first caller and not restarted by subsequent callers.
2988 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002989 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002990 synchronized (this) {
2991 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002992 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002993 mNetTransitionWakeLock.acquire();
2994 mNetTransitionWakeLockCausedBy = forWhom;
2995 }
2996 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002997 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002998 mNetTransitionWakeLockTimeout);
2999 return;
3000 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003001
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003002 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003003 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003004 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003005 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003006 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003007 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003008 }
3009
Lorenzo Colitti18660282016-07-04 12:55:44 +09003010 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003011 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003012 enforceAccessPermission();
3013 enforceInternetPermission();
3014
Paul Jensenbfd17b72015-04-07 12:43:13 -04003015 NetworkAgentInfo nai;
3016 if (network == null) {
3017 nai = getDefaultNetwork();
3018 } else {
3019 nai = getNetworkAgentInfoForNetwork(network);
3020 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003021 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3022 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3023 return;
3024 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003025 // Revalidate if the app report does not match our current validated state.
3026 if (hasConnectivity == nai.lastValidated) return;
3027 final int uid = Binder.getCallingUid();
3028 if (DBG) {
3029 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3030 ") by " + uid);
3031 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003032 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003033 // Validating a network that has not yet connected could result in a call to
3034 // rematchNetworkAndRequests() which is not meant to work on such networks.
3035 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003036
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003037 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003038
3039 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3040 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003041 }
3042
Paul Jensencee9b512015-05-06 07:32:40 -04003043 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003044 // this information is already available as a world read/writable jvm property
3045 // so this API change wouldn't have a benifit. It also breaks the passing
3046 // of proxy info to all the JVMs.
3047 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003048 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003049 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003050 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3051 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003052 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003053 }
3054
Lorenzo Colitti18660282016-07-04 12:55:44 +09003055 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003056 public ProxyInfo getProxyForNetwork(Network network) {
3057 if (network == null) return getDefaultProxy();
3058 final ProxyInfo globalProxy = getGlobalProxy();
3059 if (globalProxy != null) return globalProxy;
3060 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3061 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3062 // caller may not have.
3063 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3064 if (nai == null) return null;
3065 synchronized (nai) {
3066 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3067 if (proxyInfo == null) return null;
3068 return new ProxyInfo(proxyInfo);
3069 }
3070 }
3071
Paul Jensene0bef712014-12-10 15:12:18 -05003072 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3073 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3074 // proxy is null then there is no proxy in place).
3075 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3076 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3077 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3078 proxy = null;
3079 }
3080 return proxy;
3081 }
3082
3083 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3084 // better for determining if a new proxy broadcast is necessary:
3085 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3086 // avoid unnecessary broadcasts.
3087 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3088 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3089 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3090 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3091 // all set.
3092 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3093 a = canonicalizeProxyInfo(a);
3094 b = canonicalizeProxyInfo(b);
3095 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3096 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3097 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3098 }
3099
Jason Monk207900c2014-04-25 15:00:09 -04003100 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003101 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003102
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003103 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003104 if (proxyProperties == mGlobalProxy) return;
3105 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3106 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3107
3108 String host = "";
3109 int port = 0;
3110 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003111 String pacFileUrl = "";
3112 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003113 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003114 if (!proxyProperties.isValid()) {
3115 if (DBG)
3116 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3117 return;
3118 }
Jason Monk207900c2014-04-25 15:00:09 -04003119 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003120 host = mGlobalProxy.getHost();
3121 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003122 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003123 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003124 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003125 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003126 } else {
3127 mGlobalProxy = null;
3128 }
3129 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003130 final long token = Binder.clearCallingIdentity();
3131 try {
3132 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3133 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3134 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3135 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003136 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003137 } finally {
3138 Binder.restoreCallingIdentity(token);
3139 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003140
Jason Monkcf0f97a2014-10-02 15:39:38 -04003141 if (mGlobalProxy == null) {
3142 proxyProperties = mDefaultProxy;
3143 }
3144 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003145 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003146 }
3147
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003148 private void loadGlobalProxy() {
3149 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003150 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3151 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3152 String exclList = Settings.Global.getString(res,
3153 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003154 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3155 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003156 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003157 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003158 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003159 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003160 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003161 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003162 if (!proxyProperties.isValid()) {
3163 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3164 return;
3165 }
3166
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003167 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003168 mGlobalProxy = proxyProperties;
3169 }
3170 }
3171 }
3172
Jason Monk207900c2014-04-25 15:00:09 -04003173 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003174 // this information is already available as a world read/writable jvm property
3175 // so this API change wouldn't have a benifit. It also breaks the passing
3176 // of proxy info to all the JVMs.
3177 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003178 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003179 return mGlobalProxy;
3180 }
3181 }
3182
Jason Monk207900c2014-04-25 15:00:09 -04003183 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003184 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003185 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003186 proxy = null;
3187 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003188 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003189 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003190 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003191 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003192 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3193 return;
3194 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003195
3196 // This call could be coming from the PacManager, containing the port of the local
3197 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3198 // global (to get the correct local port), and send a broadcast.
3199 // TODO: Switch PacManager to have its own message to send back rather than
3200 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003201 if ((mGlobalProxy != null) && (proxy != null)
3202 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003203 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3204 mGlobalProxy = proxy;
3205 sendProxyBroadcast(mGlobalProxy);
3206 return;
3207 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003208 mDefaultProxy = proxy;
3209
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003210 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003211 if (!mDefaultProxyDisabled) {
3212 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003213 }
3214 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003215 }
3216
Paul Jensene0bef712014-12-10 15:12:18 -05003217 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3218 // This method gets called when any network changes proxy, but the broadcast only ever contains
3219 // the default proxy (even if it hasn't changed).
3220 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3221 // world where an app might be bound to a non-default network.
3222 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3223 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3224 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3225
3226 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3227 sendProxyBroadcast(getDefaultProxy());
3228 }
3229 }
3230
Robert Greenwalt434203a2010-10-11 16:00:27 -07003231 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003232 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3233 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003234 if (!TextUtils.isEmpty(proxy)) {
3235 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003236 if (data.length == 0) {
3237 return;
3238 }
3239
Robert Greenwalt434203a2010-10-11 16:00:27 -07003240 String proxyHost = data[0];
3241 int proxyPort = 8080;
3242 if (data.length > 1) {
3243 try {
3244 proxyPort = Integer.parseInt(data[1]);
3245 } catch (NumberFormatException e) {
3246 return;
3247 }
3248 }
Jason Monk207900c2014-04-25 15:00:09 -04003249 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003250 setGlobalProxy(p);
3251 }
3252 }
3253
Jason Monk207900c2014-04-25 15:00:09 -04003254 private void sendProxyBroadcast(ProxyInfo proxy) {
3255 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003256 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003257 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003258 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003259 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3260 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003261 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003262 final long ident = Binder.clearCallingIdentity();
3263 try {
3264 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3265 } finally {
3266 Binder.restoreCallingIdentity(ident);
3267 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003268 }
3269
3270 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003271 final private HashMap<Uri, Integer> mUriEventMap;
3272 final private Context mContext;
3273 final private Handler mHandler;
3274
3275 SettingsObserver(Context context, Handler handler) {
3276 super(null);
3277 mUriEventMap = new HashMap<Uri, Integer>();
3278 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003279 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003280 }
3281
Erik Klineda4bfa82015-04-30 12:58:40 +09003282 void observe(Uri uri, int what) {
3283 mUriEventMap.put(uri, what);
3284 final ContentResolver resolver = mContext.getContentResolver();
3285 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003286 }
3287
3288 @Override
3289 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003290 Slog.wtf(TAG, "Should never be reached.");
3291 }
3292
3293 @Override
3294 public void onChange(boolean selfChange, Uri uri) {
3295 final Integer what = mUriEventMap.get(uri);
3296 if (what != null) {
3297 mHandler.obtainMessage(what.intValue()).sendToTarget();
3298 } else {
3299 loge("No matching event to send for URI=" + uri);
3300 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003301 }
3302 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003303
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003304 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003305 Slog.d(TAG, s);
3306 }
3307
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003308 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003309 Slog.e(TAG, s);
3310 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003311
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003312 private static <T> T checkNotNull(T value, String message) {
3313 if (value == null) {
3314 throw new NullPointerException(message);
3315 }
3316 return value;
3317 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003318
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003319 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003320 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003321 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3322 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3323 *
3324 * @param oldPackage Package name of the application which currently controls VPN, which will
3325 * be replaced. If there is no such application, this should should either be
3326 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3327 * @param newPackage Package name of the application which should gain control of VPN, or
3328 * {@code null} to disable.
3329 * @param userId User for whom to prepare the new VPN.
3330 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003331 * @hide
3332 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003333 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003334 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3335 int userId) {
3336 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003337 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003338
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003339 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003340 Vpn vpn = mVpns.get(userId);
3341 if (vpn != null) {
3342 return vpn.prepare(oldPackage, newPackage);
3343 } else {
3344 return false;
3345 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003346 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003347 }
3348
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003349 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003350 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3351 * This method is used by system-privileged apps.
3352 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3353 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3354 *
3355 * @param packageName The package for which authorization state should change.
3356 * @param userId User for whom {@code packageName} is installed.
3357 * @param authorized {@code true} if this app should be able to start a VPN connection without
3358 * explicit user approval, {@code false} if not.
3359 *
Jeff Davidson05542602014-08-11 14:07:27 -07003360 * @hide
3361 */
3362 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003363 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3364 enforceCrossUserPermission(userId);
3365
Jeff Davidson05542602014-08-11 14:07:27 -07003366 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003367 Vpn vpn = mVpns.get(userId);
3368 if (vpn != null) {
3369 vpn.setPackageAuthorization(packageName, authorized);
3370 }
Jeff Davidson05542602014-08-11 14:07:27 -07003371 }
3372 }
3373
3374 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003375 * Configure a TUN interface and return its file descriptor. Parameters
3376 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003377 * and not available in ConnectivityManager. Permissions are checked in
3378 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003379 * @hide
3380 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003381 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003382 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003383 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003384 int user = UserHandle.getUserId(Binder.getCallingUid());
3385 synchronized(mVpns) {
3386 return mVpns.get(user).establish(config);
3387 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003388 }
3389
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003390 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003391 * Start legacy VPN, controlling native daemons as needed. Creates a
3392 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003393 */
3394 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003395 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003396 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003397 final LinkProperties egress = getActiveLinkProperties();
3398 if (egress == null) {
3399 throw new IllegalStateException("Missing active network connection");
3400 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003401 int user = UserHandle.getUserId(Binder.getCallingUid());
3402 synchronized(mVpns) {
3403 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3404 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003405 }
3406
3407 /**
3408 * Return the information of the ongoing legacy VPN. This method is used
3409 * by VpnSettings and not available in ConnectivityManager. Permissions
3410 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003411 */
3412 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003413 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3414 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003415
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003416 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003417 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003418 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003419 }
3420
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003421 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003422 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3423 * and not available in ConnectivityManager.
3424 */
3425 @Override
3426 public VpnInfo[] getAllVpnInfo() {
3427 enforceConnectivityInternalPermission();
3428 if (mLockdownEnabled) {
3429 return new VpnInfo[0];
3430 }
3431
3432 synchronized(mVpns) {
3433 List<VpnInfo> infoList = new ArrayList<>();
3434 for (int i = 0; i < mVpns.size(); i++) {
3435 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3436 if (info != null) {
3437 infoList.add(info);
3438 }
3439 }
3440 return infoList.toArray(new VpnInfo[infoList.size()]);
3441 }
3442 }
3443
3444 /**
3445 * @return VPN information for accounting, or null if we can't retrieve all required
3446 * information, e.g primary underlying iface.
3447 */
3448 @Nullable
3449 private VpnInfo createVpnInfo(Vpn vpn) {
3450 VpnInfo info = vpn.getVpnInfo();
3451 if (info == null) {
3452 return null;
3453 }
3454 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3455 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3456 // the underlyingNetworks list.
3457 if (underlyingNetworks == null) {
3458 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3459 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3460 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3461 }
3462 } else if (underlyingNetworks.length > 0) {
3463 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3464 if (linkProperties != null) {
3465 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3466 }
3467 }
3468 return info.primaryUnderlyingIface == null ? null : info;
3469 }
3470
3471 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003472 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3473 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003474 * Permissions are checked in Vpn class.
3475 * @hide
3476 */
3477 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003478 public VpnConfig getVpnConfig(int userId) {
3479 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003480 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003481 Vpn vpn = mVpns.get(userId);
3482 if (vpn != null) {
3483 return vpn.getVpnConfig();
3484 } else {
3485 return null;
3486 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003487 }
3488 }
3489
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003490 @Override
3491 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003492 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3493 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3494 return false;
3495 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003496
3497 // Tear down existing lockdown if profile was removed
3498 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3499 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003500 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3501 final VpnProfile profile = VpnProfile.decode(
3502 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003503 if (profile == null) {
3504 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3505 setLockdownTracker(null);
3506 return true;
3507 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003508 int user = UserHandle.getUserId(Binder.getCallingUid());
3509 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003510 Vpn vpn = mVpns.get(user);
3511 if (vpn == null) {
3512 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3513 return false;
3514 }
3515 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003516 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003517 } else {
3518 setLockdownTracker(null);
3519 }
3520
3521 return true;
3522 }
3523
3524 /**
3525 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3526 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3527 */
3528 private void setLockdownTracker(LockdownVpnTracker tracker) {
3529 // Shutdown any existing tracker
3530 final LockdownVpnTracker existing = mLockdownTracker;
3531 mLockdownTracker = null;
3532 if (existing != null) {
3533 existing.shutdown();
3534 }
3535
3536 try {
3537 if (tracker != null) {
3538 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003539 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003540 mLockdownTracker = tracker;
3541 mLockdownTracker.init();
3542 } else {
3543 mNetd.setFirewallEnabled(false);
3544 }
3545 } catch (RemoteException e) {
3546 // ignored; NMS lives inside system_server
3547 }
3548 }
3549
3550 private void throwIfLockdownEnabled() {
3551 if (mLockdownEnabled) {
3552 throw new IllegalStateException("Unavailable in lockdown mode");
3553 }
3554 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003555
Robin Lee244ce8e2016-01-05 18:03:46 +00003556 /**
Robin Lee17e61832016-05-09 13:46:28 +01003557 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3558 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003559 *
Robin Lee17e61832016-05-09 13:46:28 +01003560 * @return {@code true} if the service was started, the service was already connected, or there
3561 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003562 */
Robin Lee17e61832016-05-09 13:46:28 +01003563 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003564 synchronized (mVpns) {
3565 Vpn vpn = mVpns.get(userId);
3566 if (vpn == null) {
3567 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3568 // exists already.
3569 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3570 return false;
3571 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003572
Robin Lee812800c2016-05-13 15:38:08 +01003573 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003574 }
3575 }
3576
3577 @Override
Robin Leedc679712016-05-03 13:23:03 +01003578 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003579 enforceConnectivityInternalPermission();
3580 enforceCrossUserPermission(userId);
3581
3582 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3583 if (LockdownVpnTracker.isEnabled()) {
3584 return false;
3585 }
3586
Robin Lee244ce8e2016-01-05 18:03:46 +00003587 synchronized (mVpns) {
3588 Vpn vpn = mVpns.get(userId);
3589 if (vpn == null) {
3590 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3591 return false;
3592 }
Robin Lee17e61832016-05-09 13:46:28 +01003593 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003594 return false;
3595 }
Robin Lee17e61832016-05-09 13:46:28 +01003596 if (!startAlwaysOnVpn(userId)) {
3597 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003598 return false;
3599 }
Robin Lee17e61832016-05-09 13:46:28 +01003600
Robin Lee812800c2016-05-13 15:38:08 +01003601 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003602 }
3603 return true;
3604 }
3605
3606 @Override
3607 public String getAlwaysOnVpnPackage(int userId) {
3608 enforceConnectivityInternalPermission();
3609 enforceCrossUserPermission(userId);
3610
3611 synchronized (mVpns) {
3612 Vpn vpn = mVpns.get(userId);
3613 if (vpn == null) {
3614 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3615 return null;
3616 }
3617 return vpn.getAlwaysOnPackage();
3618 }
3619 }
3620
Wink Savilleab9321d2013-06-29 21:10:57 -07003621 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003622 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003623 // TODO: Remove? Any reason to trigger a provisioning check?
3624 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003625 }
3626
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003627 /** Location to an updatable file listing carrier provisioning urls.
3628 * An example:
3629 *
3630 * <?xml version="1.0" encoding="utf-8"?>
3631 * <provisioningUrls>
3632 * <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 -07003633 * </provisioningUrls>
3634 */
3635 private static final String PROVISIONING_URL_PATH =
3636 "/data/misc/radio/provisioning_urls.xml";
3637 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003638
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003639 /** XML tag for root element. */
3640 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3641 /** XML tag for individual url */
3642 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003643 /** XML attribute for mcc */
3644 private static final String ATTR_MCC = "mcc";
3645 /** XML attribute for mnc */
3646 private static final String ATTR_MNC = "mnc";
3647
Paul Jensen434dde82015-06-11 09:43:30 -04003648 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003649 FileReader fileReader = null;
3650 XmlPullParser parser = null;
3651 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003652
3653 try {
3654 fileReader = new FileReader(mProvisioningUrlFile);
3655 parser = Xml.newPullParser();
3656 parser.setInput(fileReader);
3657 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3658
3659 while (true) {
3660 XmlUtils.nextElement(parser);
3661
3662 String element = parser.getName();
3663 if (element == null) break;
3664
Paul Jensen434dde82015-06-11 09:43:30 -04003665 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003666 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3667 try {
3668 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3669 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3670 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3671 parser.next();
3672 if (parser.getEventType() == XmlPullParser.TEXT) {
3673 return parser.getText();
3674 }
3675 }
3676 }
3677 } catch (NumberFormatException e) {
3678 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3679 }
3680 }
3681 }
3682 return null;
3683 } catch (FileNotFoundException e) {
3684 loge("Carrier Provisioning Urls file not found");
3685 } catch (XmlPullParserException e) {
3686 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3687 } catch (IOException e) {
3688 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3689 } finally {
3690 if (fileReader != null) {
3691 try {
3692 fileReader.close();
3693 } catch (IOException e) {}
3694 }
3695 }
3696 return null;
3697 }
3698
Wink Saville42d4f082013-07-20 20:31:59 -07003699 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003700 public String getMobileProvisioningUrl() {
3701 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003702 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003703 if (TextUtils.isEmpty(url)) {
3704 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003705 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003706 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003707 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003708 }
Wink Saville8cf35602013-07-10 23:00:07 -07003709 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003710 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003711 String phoneNumber = mTelephonyManager.getLine1Number();
3712 if (TextUtils.isEmpty(phoneNumber)) {
3713 phoneNumber = "0000000000";
3714 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003715 url = String.format(url,
3716 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3717 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003718 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003719 }
3720
Wink Savilleab9321d2013-06-29 21:10:57 -07003721 return url;
3722 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003723
Wink Saville948282b2013-08-29 08:55:16 -07003724 @Override
3725 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003726 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003727 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003728 final long ident = Binder.clearCallingIdentity();
3729 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003730 // Concatenate the range of types onto the range of NetIDs.
3731 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3732 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003733 } finally {
3734 Binder.restoreCallingIdentity(ident);
3735 }
Wink Saville948282b2013-08-29 08:55:16 -07003736 }
Wink Saville7788c612013-08-29 14:57:08 -07003737
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003738 @Override
3739 public void setAirplaneMode(boolean enable) {
3740 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003741 final long ident = Binder.clearCallingIdentity();
3742 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003743 final ContentResolver cr = mContext.getContentResolver();
3744 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3745 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3746 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003747 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003748 } finally {
3749 Binder.restoreCallingIdentity(ident);
3750 }
3751 }
3752
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003753 private void onUserStart(int userId) {
3754 synchronized(mVpns) {
3755 Vpn userVpn = mVpns.get(userId);
3756 if (userVpn != null) {
3757 loge("Starting user already has a VPN");
3758 return;
3759 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003760 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003761 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003762
3763 final ContentResolver cr = mContext.getContentResolver();
3764 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3765 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3766 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3767 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3768 if (alwaysOnPackage != null) {
3769 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3770 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003771 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003772 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3773 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003774 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003775 }
3776
3777 private void onUserStop(int userId) {
3778 synchronized(mVpns) {
3779 Vpn userVpn = mVpns.get(userId);
3780 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003781 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003782 return;
3783 }
Robin Lee17e61832016-05-09 13:46:28 +01003784 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003785 mVpns.delete(userId);
3786 }
3787 }
3788
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003789 private void onUserAdded(int userId) {
3790 synchronized(mVpns) {
3791 final int vpnsSize = mVpns.size();
3792 for (int i = 0; i < vpnsSize; i++) {
3793 Vpn vpn = mVpns.valueAt(i);
3794 vpn.onUserAdded(userId);
3795 }
3796 }
3797 }
3798
3799 private void onUserRemoved(int userId) {
3800 synchronized(mVpns) {
3801 final int vpnsSize = mVpns.size();
3802 for (int i = 0; i < vpnsSize; i++) {
3803 Vpn vpn = mVpns.valueAt(i);
3804 vpn.onUserRemoved(userId);
3805 }
3806 }
3807 }
3808
Robin Lee89e7a692016-02-29 14:38:17 +00003809 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003810 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3811 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3812 updateLockdownVpn();
3813 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003814 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003815 }
3816 }
3817
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003818 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3819 @Override
3820 public void onReceive(Context context, Intent intent) {
3821 final String action = intent.getAction();
3822 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3823 if (userId == UserHandle.USER_NULL) return;
3824
Robin Lee323f29d2016-05-04 16:38:06 +01003825 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003826 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003827 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003828 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003829 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3830 onUserAdded(userId);
3831 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3832 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003833 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3834 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003835 }
3836 }
3837 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003838
Robert Greenwalta67be032014-05-16 15:49:14 -07003839 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3840 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003841 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3842 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003843
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003844 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3845 // Map from UID to number of NetworkRequests that UID has filed.
3846 @GuardedBy("mUidToNetworkRequestCount")
3847 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3848
Robert Greenwalta67be032014-05-16 15:49:14 -07003849 private static class NetworkFactoryInfo {
3850 public final String name;
3851 public final Messenger messenger;
3852 public final AsyncChannel asyncChannel;
3853
3854 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3855 this.name = name;
3856 this.messenger = messenger;
3857 this.asyncChannel = asyncChannel;
3858 }
3859 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003860
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003861 private void ensureNetworkRequestHasType(NetworkRequest request) {
3862 if (request.type == NetworkRequest.Type.NONE) {
3863 throw new IllegalArgumentException(
3864 "All NetworkRequests in ConnectivityService must have a type");
3865 }
3866 }
3867
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003868 /**
3869 * Tracks info about the requester.
3870 * Also used to notice when the calling process dies so we can self-expire
3871 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003872 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003873 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003874 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003875 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003876 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003877 final int mPid;
3878 final int mUid;
3879 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003880
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003881 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003882 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003883 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003884 mPendingIntent = pi;
3885 messenger = null;
3886 mBinder = null;
3887 mPid = getCallingPid();
3888 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003889 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003890 }
3891
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003892 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003893 super();
3894 messenger = m;
3895 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003896 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003897 mBinder = binder;
3898 mPid = getCallingPid();
3899 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003900 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003901 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003902
3903 try {
3904 mBinder.linkToDeath(this, 0);
3905 } catch (RemoteException e) {
3906 binderDied();
3907 }
3908 }
3909
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003910 private void enforceRequestCountLimit() {
3911 synchronized (mUidToNetworkRequestCount) {
3912 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3913 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3914 throw new IllegalArgumentException("Too many NetworkRequests filed");
3915 }
3916 mUidToNetworkRequestCount.put(mUid, networkRequests);
3917 }
3918 }
3919
Robert Greenwalt9258c642014-03-26 16:47:06 -07003920 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003921 if (mBinder != null) {
3922 mBinder.unlinkToDeath(this, 0);
3923 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003924 }
3925
3926 public void binderDied() {
3927 log("ConnectivityService NetworkRequestInfo binderDied(" +
3928 request + ", " + mBinder + ")");
3929 releaseNetworkRequest(request);
3930 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003931
3932 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003933 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003934 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003935 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003936 }
3937
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003938 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3939 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3940 if (badCapability != null) {
3941 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003942 }
3943 }
3944
Erik Kline9d598e12015-07-13 16:37:51 +09003945 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003946 final SortedSet<Integer> thresholds = new TreeSet();
3947 synchronized (nai) {
3948 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3949 if (nri.request.networkCapabilities.hasSignalStrength() &&
3950 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3951 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3952 }
3953 }
3954 }
Erik Kline9d598e12015-07-13 16:37:51 +09003955 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003956 }
3957
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003958 private void updateSignalStrengthThresholds(
3959 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3960 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003961 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003962 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3963
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003964 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003965 String detail;
3966 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3967 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3968 } else {
3969 detail = reason;
3970 }
3971 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3972 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3973 }
3974
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003975 nai.asyncChannel.sendMessage(
3976 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003977 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003978 }
3979
Robert Greenwalt9258c642014-03-26 16:47:06 -07003980 @Override
3981 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003982 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003983 final NetworkRequest.Type type = (networkCapabilities == null)
3984 ? NetworkRequest.Type.TRACK_DEFAULT
3985 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003986 // If the requested networkCapabilities is null, take them instead from
3987 // the default network request. This allows callers to keep track of
3988 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003989 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003990 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3991 enforceAccessPermission();
3992 } else {
3993 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3994 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09003995 // TODO: this is incorrect. We mark the request as metered or not depending on the state
3996 // of the app when the request is filed, but we never change the request if the app
3997 // changes network state. http://b/29964605
3998 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09003999 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004000 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004001
Robert Greenwalt6078b502014-06-11 16:05:07 -07004002 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004003 throw new IllegalArgumentException("Bad timeout specified");
4004 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004005
Etan Cohenddb9ef02015-11-18 10:56:15 -08004006 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4007 .equals(networkCapabilities.getNetworkSpecifier())) {
4008 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4009 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4010 }
4011
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004012 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004013 nextNetworkRequestId(), type);
4014 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004015 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004016
4017 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004018 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004019 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004020 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004021 }
4022 return networkRequest;
4023 }
4024
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004025 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004026 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004027 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004028 } else {
4029 enforceChangePermission();
4030 }
4031 }
4032
fenglub15e72b2015-03-20 11:29:56 -07004033 @Override
fengludb571472015-04-21 17:12:05 -07004034 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004035 enforceAccessPermission();
4036 NetworkAgentInfo nai = null;
4037 if (network == null) {
4038 return false;
4039 }
4040 synchronized (mNetworkForNetId) {
4041 nai = mNetworkForNetId.get(network.netId);
4042 }
4043 if (nai != null) {
4044 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4045 return true;
4046 }
4047 return false;
4048 }
4049
Felipe Lemeee27cab2016-06-20 16:36:29 -07004050 private boolean isSystem(int uid) {
4051 return uid < Process.FIRST_APPLICATION_UID;
4052 }
fenglub15e72b2015-03-20 11:29:56 -07004053
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004054 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004055 final int uid = Binder.getCallingUid();
4056 if (isSystem(uid)) {
4057 return;
4058 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004059 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004060 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004061 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004062 synchronized(mRulesLock) {
4063 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4064 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004065 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4066 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004067 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004068 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004069 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004070 }
4071 }
4072 }
4073
Robert Greenwalt9258c642014-03-26 16:47:06 -07004074 @Override
4075 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4076 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004077 checkNotNull(operation, "PendingIntent cannot be null.");
4078 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4079 enforceNetworkRequestPermissions(networkCapabilities);
4080 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004081 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004082
4083 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004084 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4085 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004086 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004087 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4088 nri));
4089 return networkRequest;
4090 }
4091
Jeremy Joslin79294842014-12-03 17:15:28 -08004092 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4093 mHandler.sendMessageDelayed(
4094 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4095 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4096 }
4097
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004098 @Override
4099 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004100 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004101 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4102 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004103 }
4104
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004105 // In order to implement the compatibility measure for pre-M apps that call
4106 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4107 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4108 // This ensures it has permission to do so.
4109 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4110 if (nc == null) {
4111 return false;
4112 }
4113 int[] transportTypes = nc.getTransportTypes();
4114 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4115 return false;
4116 }
4117 try {
4118 mContext.enforceCallingOrSelfPermission(
4119 android.Manifest.permission.ACCESS_WIFI_STATE,
4120 "ConnectivityService");
4121 } catch (SecurityException e) {
4122 return false;
4123 }
4124 return true;
4125 }
4126
Robert Greenwalt9258c642014-03-26 16:47:06 -07004127 @Override
4128 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4129 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004130 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4131 enforceAccessPermission();
4132 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004133
Erik Kline7523eb32015-07-09 18:24:03 +09004134 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004135 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4136 NetworkRequest.Type.LISTEN);
4137 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004138 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004139
4140 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4141 return networkRequest;
4142 }
4143
4144 @Override
4145 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4146 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004147 checkNotNull(operation, "PendingIntent cannot be null.");
4148 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4149 enforceAccessPermission();
4150 }
4151
Erik Kline7523eb32015-07-09 18:24:03 +09004152 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004153 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4154 NetworkRequest.Type.LISTEN);
4155 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004156 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004157
4158 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004159 }
4160
4161 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004162 public void requestLinkProperties(NetworkRequest networkRequest) {
4163 ensureNetworkRequestHasType(networkRequest);
4164 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4165 mHandler.sendMessage(mHandler.obtainMessage(
4166 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4167 }
4168
4169 @Override
4170 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4171 ensureNetworkRequestHasType(networkRequest);
4172 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4173 mHandler.sendMessage(mHandler.obtainMessage(
4174 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4175 }
4176
4177 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004178 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004179 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004180 mHandler.sendMessage(mHandler.obtainMessage(
4181 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004182 }
4183
4184 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004185 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004186 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004187 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4188 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004189 }
4190
Robert Greenwalta67be032014-05-16 15:49:14 -07004191 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004192 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004193 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4194 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4195 }
4196
4197 @Override
4198 public void unregisterNetworkFactory(Messenger messenger) {
4199 enforceConnectivityInternalPermission();
4200 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4201 }
4202
4203 private void handleUnregisterNetworkFactory(Messenger messenger) {
4204 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4205 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004206 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004207 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004208 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004209 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004210 }
4211
Robert Greenwalt7b816022014-04-18 15:25:25 -07004212 /**
4213 * NetworkAgentInfo supporting a request by requestId.
4214 * These have already been vetted (their Capabilities satisfy the request)
4215 * and the are the highest scored network available.
4216 * the are keyed off the Requests requestId.
4217 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004218 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004219 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4220 new SparseArray<NetworkAgentInfo>();
4221
Paul Jensen31a94f42015-02-13 14:18:39 -05004222 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4223 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004224 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4225 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004226 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4227 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4228 // there may not be a strict 1:1 correlation between the two.
4229 @GuardedBy("mNetworkForNetId")
4230 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004231
Robert Greenwalt7b816022014-04-18 15:25:25 -07004232 // NetworkAgentInfo keyed off its connecting messenger
4233 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004234 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004235 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4236 new HashMap<Messenger, NetworkAgentInfo>();
4237
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004238 @GuardedBy("mBlockedAppUids")
4239 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4240
Paul Jensen2c311d62014-11-17 12:34:51 -05004241 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004242 private final NetworkRequest mDefaultRequest;
4243
Erik Klineda4bfa82015-04-30 12:58:40 +09004244 // Request used to optionally keep mobile data active even when higher
4245 // priority networks like Wi-Fi are active.
4246 private final NetworkRequest mDefaultMobileDataRequest;
4247
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004248 private NetworkAgentInfo getDefaultNetwork() {
4249 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4250 }
4251
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004252 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004253 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004254 }
4255
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004256 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4257 return nri.request.requestId == mDefaultRequest.requestId;
4258 }
4259
Paul Jensen31a94f42015-02-13 14:18:39 -05004260 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004261 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004262 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004263 enforceConnectivityInternalPermission();
4264
Paul Jensen2c311d62014-11-17 12:34:51 -05004265 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4266 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004267 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004268 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4269 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004270 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004271 synchronized (this) {
4272 nai.networkMonitor.systemReady = mSystemReady;
4273 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004274 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4275 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004276 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004277 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004278 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004279 }
4280
4281 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4282 if (VDBG) log("Got NetworkAgent Messenger");
4283 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004284 synchronized (mNetworkForNetId) {
4285 mNetworkForNetId.put(na.network.netId, na);
4286 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004287 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4288 NetworkInfo networkInfo = na.networkInfo;
4289 na.networkInfo = null;
4290 updateNetworkInfo(na, networkInfo);
4291 }
4292
4293 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4294 LinkProperties newLp = networkAgent.linkProperties;
4295 int netId = networkAgent.network.netId;
4296
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004297 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4298 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004299 if (networkAgent.clatd != null) {
4300 networkAgent.clatd.fixupLinkProperties(oldLp);
4301 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004302
Paul Jensen992f2522014-04-28 10:33:11 -04004303 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004304 updateMtu(newLp, oldLp);
4305 // TODO - figure out what to do for clat
4306// for (LinkProperties lp : newLp.getStackedLinks()) {
4307// updateMtu(lp, null);
4308// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004309 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004310
Erik Kline94887872016-04-05 13:30:49 +09004311 updateRoutes(newLp, oldLp, netId);
4312 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004313
Paul Jensen3b759822014-05-13 11:44:01 -04004314 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004315 if (isDefaultNetwork(networkAgent)) {
4316 handleApplyDefaultProxy(newLp.getHttpProxy());
4317 } else {
4318 updateProxy(newLp, oldLp, networkAgent);
4319 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004320 // TODO - move this check to cover the whole function
4321 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004322 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004323 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4324 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004325
4326 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004327 }
4328
Lorenzo Colitti95439462014-10-09 13:44:48 +09004329 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4330 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4331 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004332
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004333 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004334 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4335 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004336 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004337 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004338 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004339 }
Paul Jensen992f2522014-04-28 10:33:11 -04004340
4341 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4342 CompareResult<String> interfaceDiff = new CompareResult<String>();
4343 if (oldLp != null) {
4344 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4345 } else if (newLp != null) {
4346 interfaceDiff.added = newLp.getAllInterfaceNames();
4347 }
4348 for (String iface : interfaceDiff.added) {
4349 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004350 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004351 mNetd.addInterfaceToNetwork(iface, netId);
4352 } catch (Exception e) {
4353 loge("Exception adding interface: " + e);
4354 }
4355 }
4356 for (String iface : interfaceDiff.removed) {
4357 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004358 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004359 mNetd.removeInterfaceFromNetwork(iface, netId);
4360 } catch (Exception e) {
4361 loge("Exception removing interface: " + e);
4362 }
4363 }
4364 }
4365
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004366 /**
4367 * Have netd update routes from oldLp to newLp.
4368 * @return true if routes changed between oldLp and newLp
4369 */
4370 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004371 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4372 if (oldLp != null) {
4373 routeDiff = oldLp.compareAllRoutes(newLp);
4374 } else if (newLp != null) {
4375 routeDiff.added = newLp.getAllRoutes();
4376 }
4377
4378 // add routes before removing old in case it helps with continuous connectivity
4379
4380 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4381 for (RouteInfo route : routeDiff.added) {
4382 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004383 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004384 try {
4385 mNetd.addRoute(netId, route);
4386 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004387 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4388 loge("Exception in addRoute for non-gateway: " + e);
4389 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004390 }
4391 }
4392 for (RouteInfo route : routeDiff.added) {
4393 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004394 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004395 try {
4396 mNetd.addRoute(netId, route);
4397 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004398 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4399 loge("Exception in addRoute for gateway: " + e);
4400 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004401 }
4402 }
4403
4404 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004405 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004406 try {
4407 mNetd.removeRoute(netId, route);
4408 } catch (Exception e) {
4409 loge("Exception in removeRoute: " + e);
4410 }
4411 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004412 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004413 }
Erik Kline41368502015-06-17 13:19:54 +09004414
Erik Kline94887872016-04-05 13:30:49 +09004415 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4416 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4417 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004418 }
Erik Kline94887872016-04-05 13:30:49 +09004419
4420 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004421 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004422 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004423 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004424 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4425 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004426 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004427 }
4428 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4429 if (defaultNai != null && defaultNai.network.netId == netId) {
4430 setDefaultDnsSystemProperties(dnses);
4431 }
4432 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004433 }
4434
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004435 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4436 int last = 0;
4437 for (InetAddress dns : dnses) {
4438 ++last;
4439 String key = "net.dns" + last;
4440 String value = dns.getHostAddress();
4441 SystemProperties.set(key, value);
4442 }
4443 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4444 String key = "net.dns" + i;
4445 SystemProperties.set(key, "");
4446 }
4447 mNumDnsEntries = last;
4448 }
4449
Paul Jensen3d194ea2015-06-16 14:27:36 -04004450 /**
4451 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4452 * augmented with any stateful capabilities implied from {@code networkAgent}
4453 * (e.g., validated status and captive portal status).
4454 *
Paul Jensene0988542015-06-25 15:30:08 -04004455 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004456 * @param networkCapabilities the new network capabilities.
4457 */
Paul Jensene0988542015-06-25 15:30:08 -04004458 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004459 // Don't modify caller's NetworkCapabilities.
4460 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004461 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004462 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4463 } else {
4464 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4465 }
Paul Jensene0988542015-06-25 15:30:08 -04004466 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004467 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4468 } else {
4469 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4470 }
Paul Jensene0988542015-06-25 15:30:08 -04004471 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4472 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004473 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4474 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4475 try {
4476 mNetd.setNetworkPermission(nai.network.netId,
4477 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4478 null : NetworkManagementService.PERMISSION_SYSTEM);
4479 } catch (RemoteException e) {
4480 loge("Exception in setNetworkPermission: " + e);
4481 }
4482 }
Paul Jensene0988542015-06-25 15:30:08 -04004483 synchronized (nai) {
4484 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004485 }
Paul Jensene0988542015-06-25 15:30:08 -04004486 rematchAllNetworksAndRequests(nai, oldScore);
4487 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004488 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004489 }
4490
Paul Jensenc8b9a742014-09-30 15:37:41 -04004491 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004492 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4493 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004494 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004495 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004496 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4497 }
4498 }
4499
Robert Greenwalt7b816022014-04-18 15:25:25 -07004500 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4501 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004502 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004503 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4504 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004505 }
4506 }
4507
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004508 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4509 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004510 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004511 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004512 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4513 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004514 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004515 sendIntent(nri.mPendingIntent, intent);
4516 }
4517 // else not handled
4518 }
4519
4520 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4521 mPendingIntentWakeLock.acquire();
4522 try {
4523 if (DBG) log("Sending " + pendingIntent);
4524 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4525 } catch (PendingIntent.CanceledException e) {
4526 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4527 mPendingIntentWakeLock.release();
4528 releasePendingNetworkRequest(pendingIntent);
4529 }
4530 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4531 }
4532
4533 @Override
4534 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4535 String resultData, Bundle resultExtras) {
4536 if (DBG) log("Finished sending " + pendingIntent);
4537 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004538 // Release with a delay so the receiving client has an opportunity to put in its
4539 // own request.
4540 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004541 }
4542
Robert Greenwalt9258c642014-03-26 16:47:06 -07004543 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004544 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004545 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004546 Bundle bundle = new Bundle();
4547 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4548 new NetworkRequest(nri.request));
4549 Message msg = Message.obtain();
4550 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4551 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4552 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4553 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004554 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004555 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004556 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004557 break;
4558 }
4559 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4560 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4561 new NetworkCapabilities(networkAgent.networkCapabilities));
4562 break;
4563 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004564 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004565 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4566 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004567 break;
4568 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004569 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004570 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004571 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004572 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004573 if (VDBG) {
4574 log("sending notification " + notifyTypeToName(notificationType) +
4575 " for " + nri.request);
4576 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004577 nri.messenger.send(msg);
4578 } catch (RemoteException e) {
4579 // may occur naturally in the race of binder death.
4580 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4581 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004582 }
4583
Paul Jensenc8b9a742014-09-30 15:37:41 -04004584 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004585 if (nai.numRequestNetworkRequests() != 0) {
4586 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4587 NetworkRequest nr = nai.requestAt(i);
4588 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004589 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004590 loge("Dead network still had at least " + nr);
4591 break;
4592 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004593 }
4594 nai.asyncChannel.disconnect();
4595 }
4596
Robert Greenwalt7b816022014-04-18 15:25:25 -07004597 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4598 if (oldNetwork == null) {
4599 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4600 return;
4601 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004602 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004603
4604 // If we get here it means that the last linger timeout for this network expired. So there
4605 // must be no other active linger timers, and we must stop lingering.
4606 oldNetwork.clearLingerState();
4607
4608 if (unneeded(oldNetwork)) {
4609 teardownUnneededNetwork(oldNetwork);
4610 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004611 }
4612
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004613 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004614 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004615 setupDataActivityTracking(newNetwork);
4616 try {
4617 mNetd.setDefaultNetId(newNetwork.network.netId);
4618 } catch (Exception e) {
4619 loge("Exception setting default network :" + e);
4620 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004621 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004622 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004623 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004624 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004625 }
4626
Paul Jensen2161a8e2014-09-11 11:00:39 -04004627 // Handles a network appearing or improving its score.
4628 //
4629 // - Evaluates all current NetworkRequests that can be
4630 // satisfied by newNetwork, and reassigns to newNetwork
4631 // any such requests for which newNetwork is the best.
4632 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004633 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004634 // needed. A network is needed if it is the best network for
4635 // one or more NetworkRequests, or if it is a VPN.
4636 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004637 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004638 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004639 //
4640 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4641 // networks that have no chance (i.e. even if validated)
4642 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004643 //
4644 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4645 // it does not remove NetworkRequests that other Networks could better satisfy.
4646 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4647 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4648 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004649 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004650 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004651 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4652 // performed to tear down unvalidated networks that have no chance (i.e. even if
4653 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004654 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004655 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004656 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004657 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004658 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004659 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004660 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004661 // Find and migrate to this Network any NetworkRequests for
4662 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004663 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004664 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004665 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004666 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004667 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4668 final boolean satisfies = newNetwork.satisfies(nri.request);
4669 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004670 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004671 log("Network " + newNetwork.name() + " was already satisfying" +
4672 " request " + nri.request.requestId + ". No change.");
4673 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004674 keep = true;
4675 continue;
4676 }
4677
4678 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004679 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004680 if (satisfies) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004681 if (nri.request.isListen()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004682 // This is not a request, it's a callback listener.
4683 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004684 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004685 continue;
4686 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004687
Robert Greenwalt7b816022014-04-18 15:25:25 -07004688 // next check if it's better than any current network we're using for
4689 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004690 if (VDBG) {
4691 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004692 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4693 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004694 }
4695 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004696 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004697 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004698 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004699 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004700 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004701 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004702 affectedNetworks.add(currentNetwork);
4703 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004704 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004705 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004706 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004707 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004708 if (!newNetwork.addRequest(nri.request)) {
4709 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4710 }
4711 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004712 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004713 // Tell NetworkFactories about the new score, so they can stop
4714 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004715 // TODO - this could get expensive if we have alot of requests for this
4716 // network. Think about if there is a way to reduce this. Push
4717 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004718 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004719 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004720 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004721 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004722 if (currentNetwork != null) {
4723 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4724 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004725 }
4726 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004727 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004728 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4729 // mark it as no longer satisfying "nri". Because networks are processed by
4730 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4731 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4732 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4733 // This means this code doesn't have to handle the case where "currentNetwork" no
4734 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4735 if (DBG) {
4736 log("Network " + newNetwork.name() + " stopped satisfying" +
4737 " request " + nri.request.requestId);
4738 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004739 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004740 if (currentNetwork == newNetwork) {
4741 mNetworkForRequestId.remove(nri.request.requestId);
4742 sendUpdatedScoreToFactories(nri.request, 0);
4743 } else {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004744 if (nri.request.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004745 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4746 newNetwork.name() +
4747 " without updating mNetworkForRequestId or factories!");
4748 }
4749 }
4750 // TODO: technically, sending CALLBACK_LOST here is
4751 // incorrect if nri is a request (not a listen) and there
4752 // is a replacement network currently connected that can
4753 // satisfy it. However, the only capability that can both
4754 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4755 // so this code is only incorrect for a network that loses
4756 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004757 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004758 }
4759 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004760 if (isNewDefault) {
4761 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004762 makeDefault(newNetwork);
4763 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4764 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004765 synchronized (ConnectivityService.this) {
4766 // have a new default network, release the transition wakelock in
4767 // a second if it's held. The second pause is to allow apps
4768 // to reconnect over the new network
4769 if (mNetTransitionWakeLock.isHeld()) {
4770 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4771 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4772 mNetTransitionWakeLockSerialNumber, 0),
4773 1000);
4774 }
4775 }
4776 }
4777
4778 // do this after the default net is switched, but
4779 // before LegacyTypeTracker sends legacy broadcasts
4780 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4781
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004782 // Linger any networks that are no longer needed. This should be done after sending the
4783 // available callback for newNetwork.
4784 for (NetworkAgentInfo nai : affectedNetworks) {
4785 updateLingerState(nai, now);
4786 }
4787 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4788 // does not need to be done in any particular order.
4789 updateLingerState(newNetwork, now);
4790
Paul Jensencf4c2c62015-07-01 14:16:32 -04004791 if (isNewDefault) {
4792 // Maintain the illusion: since the legacy API only
4793 // understands one network at a time, we must pretend
4794 // that the current default network disconnected before
4795 // the new one connected.
4796 if (oldDefaultNetwork != null) {
4797 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4798 oldDefaultNetwork, true);
4799 }
4800 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4801 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4802 notifyLockdownVpn(newNetwork);
4803 }
4804
Robert Greenwalt7b816022014-04-18 15:25:25 -07004805 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004806 // Notify battery stats service about this network, both the normal
4807 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004808 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004809 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004810 final IBatteryStats bs = BatteryStatsService.getService();
4811 final int type = newNetwork.networkInfo.getType();
4812
4813 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4814 bs.noteNetworkInterfaceType(baseIface, type);
4815 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4816 final String stackedIface = stacked.getInterfaceName();
4817 bs.noteNetworkInterfaceType(stackedIface, type);
4818 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4819 }
4820 } catch (RemoteException ignored) {
4821 }
4822
Robert Greenwalt152ed372014-12-17 17:19:53 -08004823 // This has to happen after the notifyNetworkCallbacks as that tickles each
4824 // ConnectivityManager instance so that legacy requests correctly bind dns
4825 // requests to this network. The legacy users are listening for this bcast
4826 // and will generally do a dns request so they can ensureRouteToHost and if
4827 // they do that before the callbacks happen they'll use the default network.
4828 //
4829 // TODO: Is there still a race here? We send the broadcast
4830 // after sending the callback, but if the app can receive the
4831 // broadcast before the callback, it might still break.
4832 //
4833 // This *does* introduce a race where if the user uses the new api
4834 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4835 // they may get old info. Reverse this after the old startUsing api is removed.
4836 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004837 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4838 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004839 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004840 // legacy type tracker filters out repeat adds
4841 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4842 }
4843 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004844
4845 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4846 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4847 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4848 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4849 if (newNetwork.isVPN()) {
4850 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4851 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004852 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004853 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4854 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004855 if (unneeded(nai)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004856 if (nai.getLingerExpiry() > 0) {
4857 // This network has active linger timers and no requests, but is not
4858 // lingering. Linger it.
4859 //
4860 // One way (the only way?) this can happen if this network is unvalidated
4861 // and became unneeded due to another network improving its score to the
4862 // point where this network will no longer be able to satisfy any requests
4863 // even if it validates.
4864 updateLingerState(nai, now);
4865 } else {
4866 if (DBG) log("Reaping " + nai.name());
4867 teardownUnneededNetwork(nai);
4868 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004869 }
4870 }
4871 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004872 }
4873
Paul Jensen1c7ba022015-06-16 14:27:36 -04004874 /**
4875 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4876 * being disconnected.
4877 * @param changed If only one Network's score or capabilities have been modified since the last
4878 * time this function was called, pass this Network in this argument, otherwise pass
4879 * null.
4880 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4881 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4882 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4883 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4884 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004885 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004886 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004887 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4888 // to avoid the slowness. It is not simply enough to process just "changed", for
4889 // example in the case where "changed"'s score decreases and another network should begin
4890 // satifying a NetworkRequest that "changed" currently satisfies.
4891
4892 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4893 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4894 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004895 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04004896 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004897 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004898 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004899 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4900 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4901 // Rematch higher scoring networks first to prevent requests first matching a lower
4902 // scoring network and then a higher scoring network, which could produce multiple
4903 // callbacks and inadvertently unlinger networks.
4904 Arrays.sort(nais);
4905 for (NetworkAgentInfo nai : nais) {
4906 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004907 // Only reap the last time through the loop. Reaping before all rematching
4908 // is complete could incorrectly teardown a network that hasn't yet been
4909 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004910 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004911 : ReapUnvalidatedNetworks.REAP,
4912 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004913 }
4914 }
4915 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004916
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004917 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004918 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004919 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004920 // For now only update icons for default connection.
4921 // TODO: Update WiFi and cellular icons separately. b/17237507
4922 if (!isDefaultNetwork(nai)) return;
4923
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004924 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004925 // Don't repeat publish.
4926 if (newInetCondition == mDefaultInetConditionPublished) return;
4927
4928 mDefaultInetConditionPublished = newInetCondition;
4929 sendInetConditionBroadcast(nai.networkInfo);
4930 }
4931
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004932 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4933 if (mLockdownTracker != null) {
4934 if (nai != null && nai.isVPN()) {
4935 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4936 } else {
4937 mLockdownTracker.onNetworkInfoChanged();
4938 }
4939 }
4940 }
4941
Robert Greenwalt7b816022014-04-18 15:25:25 -07004942 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4943 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004944 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004945 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004946 synchronized (networkAgent) {
4947 oldInfo = networkAgent.networkInfo;
4948 networkAgent.networkInfo = newInfo;
4949 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004950 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004951
4952 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004953 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4954 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4955 notifyIfacesChangedForNetworkStats();
4956 } else if (VDBG) log("ignoring duplicate network state non-change");
4957 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004958 return;
4959 }
4960 if (DBG) {
4961 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4962 (oldInfo == null ? "null" : oldInfo.getState()) +
4963 " to " + state);
4964 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004965
Robin Lee585e2482016-05-01 23:00:00 +01004966 if (!networkAgent.created
4967 && (state == NetworkInfo.State.CONNECTED
4968 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004969 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004970 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004971 if (networkAgent.isVPN()) {
4972 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004973 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4974 (networkAgent.networkMisc == null ||
4975 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004976 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004977 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4978 networkAgent.networkCapabilities.hasCapability(
4979 NET_CAPABILITY_NOT_RESTRICTED) ?
4980 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004981 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004982 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004983 loge("Error creating network " + networkAgent.network.netId + ": "
4984 + e.getMessage());
4985 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004986 }
Paul Jenseneec75412014-08-04 12:21:19 -04004987 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004988 }
4989
4990 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4991 networkAgent.everConnected = true;
4992
Robert Greenwalt7b816022014-04-18 15:25:25 -07004993 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004994 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004995
Paul Jensenca8f16a2014-05-09 12:47:55 -04004996 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004997 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004998
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004999 if (networkAgent.isVPN()) {
5000 // Temporarily disable the default proxy (not global).
5001 synchronized (mProxyLock) {
5002 if (!mDefaultProxyDisabled) {
5003 mDefaultProxyDisabled = true;
5004 if (mGlobalProxy == null && mDefaultProxy != null) {
5005 sendProxyBroadcast(null);
5006 }
5007 }
5008 }
5009 // TODO: support proxy per network.
5010 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005011
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005012 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5013 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5014 // capabilities, so it only needs to be done once on initial connect, not every time the
5015 // network's capabilities change. Note that we do this before rematching the network,
5016 // so we could decide to tear it down immediately afterwards. That's fine though - on
5017 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5018 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005019 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005020
Paul Jensen2161a8e2014-09-11 11:00:39 -04005021 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005022 final long now = SystemClock.elapsedRealtime();
5023 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005024
5025 // This has to happen after matching the requests, because callbacks are just requests.
5026 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005027 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005028 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005029 if (networkAgent.isVPN()) {
5030 synchronized (mProxyLock) {
5031 if (mDefaultProxyDisabled) {
5032 mDefaultProxyDisabled = false;
5033 if (mGlobalProxy == null && mDefaultProxy != null) {
5034 sendProxyBroadcast(mDefaultProxy);
5035 }
5036 }
5037 }
5038 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005039 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5040 state == NetworkInfo.State.SUSPENDED) {
5041 // going into or coming out of SUSPEND: rescore and notify
5042 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005043 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005044 }
5045 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5046 ConnectivityManager.CALLBACK_SUSPENDED :
5047 ConnectivityManager.CALLBACK_RESUMED));
5048 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005049 }
5050 }
5051
Robert Greenwaltac96c522014-06-03 16:43:57 -07005052 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005053 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005054 if (score < 0) {
5055 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5056 "). Bumping score to min of 0");
5057 score = 0;
5058 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005059
Paul Jensen2161a8e2014-09-11 11:00:39 -04005060 final int oldScore = nai.getCurrentScore();
5061 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005062
Paul Jensen85cf78e2015-06-25 13:25:07 -04005063 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005064
Paul Jensenc8b9a742014-09-30 15:37:41 -04005065 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005066 }
5067
Robert Greenwalt9258c642014-03-26 16:47:06 -07005068 // notify only this one new request of the current state
5069 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5070 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005071 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005072 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005073 } else {
5074 sendPendingIntentForRequest(nri, nai, notifyType);
5075 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005076 }
5077
Robert Greenwalt8d482522015-06-24 13:23:42 -07005078 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005079 // The NetworkInfo we actually send out has no bearing on the real
5080 // state of affairs. For example, if the default connection is mobile,
5081 // and a request for HIPRI has just gone away, we need to pretend that
5082 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5083 // the state to DISCONNECTED, even though the network is of type MOBILE
5084 // and is still connected.
5085 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5086 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005087 if (state != DetailedState.DISCONNECTED) {
5088 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005089 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005090 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005091 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005092 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5093 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5094 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5095 if (info.isFailover()) {
5096 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5097 nai.networkInfo.setFailover(false);
5098 }
5099 if (info.getReason() != null) {
5100 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5101 }
5102 if (info.getExtraInfo() != null) {
5103 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5104 }
5105 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005106 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005107 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005108 if (newDefaultAgent != null) {
5109 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5110 newDefaultAgent.networkInfo);
5111 } else {
5112 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5113 }
5114 }
5115 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5116 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005117 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005118 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005119 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005120 }
5121 }
5122 }
5123
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005124 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005125 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005126 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5127 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005128 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5129 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005130 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005131 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005132 } else {
5133 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5134 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005135 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005136 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005137
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005138 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5139 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5140 }
5141
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005142 private String notifyTypeToName(int notifyType) {
5143 switch (notifyType) {
5144 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5145 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5146 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5147 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5148 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5149 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5150 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5151 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5152 }
5153 return "UNKNOWN";
5154 }
5155
Jeff Sharkey69736342014-12-08 14:50:12 -08005156 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005157 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5158 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005159 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005160 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005161 try {
5162 mStatsService.forceUpdateIfaces();
5163 } catch (Exception ignored) {
5164 }
5165 }
5166
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005167 @Override
5168 public boolean addVpnAddress(String address, int prefixLength) {
5169 throwIfLockdownEnabled();
5170 int user = UserHandle.getUserId(Binder.getCallingUid());
5171 synchronized (mVpns) {
5172 return mVpns.get(user).addAddress(address, prefixLength);
5173 }
5174 }
5175
5176 @Override
5177 public boolean removeVpnAddress(String address, int prefixLength) {
5178 throwIfLockdownEnabled();
5179 int user = UserHandle.getUserId(Binder.getCallingUid());
5180 synchronized (mVpns) {
5181 return mVpns.get(user).removeAddress(address, prefixLength);
5182 }
5183 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005184
5185 @Override
5186 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5187 throwIfLockdownEnabled();
5188 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005189 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005190 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005191 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005192 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005193 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005194 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005195 }
5196 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005197 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005198
5199 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005200 public String getCaptivePortalServerUrl() {
5201 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5202 }
5203
5204 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005205 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5206 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5207 enforceKeepalivePermission();
5208 mKeepaliveTracker.startNattKeepalive(
5209 getNetworkAgentInfoForNetwork(network),
5210 intervalSeconds, messenger, binder,
5211 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5212 }
5213
5214 @Override
5215 public void stopKeepalive(Network network, int slot) {
5216 mHandler.sendMessage(mHandler.obtainMessage(
5217 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5218 }
5219
5220 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005221 public void factoryReset() {
5222 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005223
5224 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5225 return;
5226 }
5227
Robin Lee3b3dd942015-05-12 18:14:58 +01005228 final int userId = UserHandle.getCallingUserId();
5229
Stuart Scottf1fb3972015-04-02 18:00:02 -07005230 // Turn airplane mode off
5231 setAirplaneMode(false);
5232
Stuart Scotte3e314d2015-04-20 14:07:45 -07005233 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5234 // Untether
5235 for (String tether : getTetheredIfaces()) {
5236 untether(tether);
5237 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005238 }
5239
Stuart Scotte3e314d2015-04-20 14:07:45 -07005240 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005241 // Remove always-on package
5242 synchronized (mVpns) {
5243 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5244 if (alwaysOnPackage != null) {
5245 setAlwaysOnVpnPackage(userId, null, false);
5246 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5247 }
5248 }
5249
Stuart Scotte3e314d2015-04-20 14:07:45 -07005250 // Turn VPN off
5251 VpnConfig vpnConfig = getVpnConfig(userId);
5252 if (vpnConfig != null) {
5253 if (vpnConfig.legacy) {
5254 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5255 } else {
5256 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5257 // in the future without user intervention.
5258 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005259
Victor Changb04a5ea2016-05-30 20:36:30 +01005260 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005261 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005262 }
5263 }
5264 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005265
5266 @VisibleForTesting
5267 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5268 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5269 return new NetworkMonitor(context, handler, nai, defaultRequest);
5270 }
Erik Kline48f12f22016-04-14 17:30:59 +09005271
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005272 @VisibleForTesting
5273 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5274 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5275 }
5276
Hugo Benichicfddd682016-05-31 16:28:06 +09005277 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005278 int newNetid = NETID_UNSET;
5279 int prevNetid = NETID_UNSET;
5280 int[] transports = new int[0];
5281 boolean hadIPv4 = false;
5282 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005283
Hugo Benichi5f16f762016-04-20 12:09:33 +09005284 if (newNai != null) {
5285 newNetid = newNai.network.netId;
5286 transports = newNai.networkCapabilities.getTransportTypes();
5287 }
5288 if (prevNai != null) {
5289 prevNetid = prevNai.network.netId;
5290 final LinkProperties lp = prevNai.linkProperties;
5291 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5292 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5293 }
5294
Hugo Benichicfddd682016-05-31 16:28:06 +09005295 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5296 }
5297
5298 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5299 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005301}