blob: 5d0508c56b35b4fc6a5870940aab60e7403ccb0e [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 Colitti84e6f1232016-08-29 14:03:11 +0900841
842 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
843 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
844 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
845 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
846 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
847 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
848 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700850
Erik Klineda4bfa82015-04-30 12:58:40 +0900851 private NetworkRequest createInternetRequestForTransport(int transportType) {
852 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900853 netCap.addCapability(NET_CAPABILITY_INTERNET);
854 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900855 if (transportType > -1) {
856 netCap.addTransportType(transportType);
857 }
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900858 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(),
859 NetworkRequest.Type.REQUEST);
Erik Klineda4bfa82015-04-30 12:58:40 +0900860 }
861
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900862 // Used only for testing.
863 // TODO: Delete this and either:
864 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
865 // changing ContentResolver to make registerContentObserver non-final).
866 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
867 // by subclassing SettingsObserver.
868 @VisibleForTesting
869 void updateMobileDataAlwaysOn() {
870 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
871 }
872
Erik Klineda4bfa82015-04-30 12:58:40 +0900873 private void handleMobileDataAlwaysOn() {
874 final boolean enable = (Settings.Global.getInt(
875 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
876 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
877 if (enable == isEnabled) {
878 return; // Nothing to do.
879 }
880
881 if (enable) {
882 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900883 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900884 } else {
885 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
886 }
887 }
888
889 private void registerSettingsCallbacks() {
890 // Watch for global HTTP proxy changes.
891 mSettingsObserver.observe(
892 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
893 EVENT_APPLY_GLOBAL_HTTP_PROXY);
894
895 // Watch for whether or not to keep mobile data always on.
896 mSettingsObserver.observe(
897 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
898 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
899 }
900
Robert Greenwalt34524f02014-05-18 16:22:10 -0700901 private synchronized int nextNetworkRequestId() {
902 return mNextNetworkRequestId++;
903 }
904
Paul Jensen67b0b072015-06-10 11:22:17 -0400905 @VisibleForTesting
906 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400907 synchronized (mNetworkForNetId) {
908 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
909 int netId = mNextNetId;
910 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
911 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500912 if (!mNetIdInUse.get(netId)) {
913 mNetIdInUse.put(netId, true);
914 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400915 }
916 }
917 }
918 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700919 }
920
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600921 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800922 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600923 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
924 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800925 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600926 state = nai.getNetworkState();
927 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800928 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600929 final NetworkInfo info = new NetworkInfo(networkType, 0,
930 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800931 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
932 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600933 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
934 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800935 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600936 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600937 return state;
938 } else {
939 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800940 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400941 }
942
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800943 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
944 if (network == null) {
945 return null;
946 }
947 synchronized (mNetworkForNetId) {
948 return mNetworkForNetId.get(network.netId);
949 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600950 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800951
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900952 private Network[] getVpnUnderlyingNetworks(int uid) {
953 if (!mLockdownEnabled) {
954 int user = UserHandle.getUserId(uid);
955 synchronized (mVpns) {
956 Vpn vpn = mVpns.get(user);
957 if (vpn != null && vpn.appliesToUid(uid)) {
958 return vpn.getUnderlyingNetworks();
959 }
960 }
961 }
962 return null;
963 }
964
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800965 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400966 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800967
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900968 final Network[] networks = getVpnUnderlyingNetworks(uid);
969 if (networks != null) {
970 // getUnderlyingNetworks() returns:
971 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
972 // empty array => the VPN explicitly said "no default network".
973 // non-empty array => the VPN specified one or more default networks; we use the
974 // first one.
975 if (networks.length > 0) {
976 nai = getNetworkAgentInfoForNetwork(networks[0]);
977 } else {
978 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800979 }
980 }
981
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800982 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600983 return nai.getNetworkState();
984 } else {
985 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800986 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400987 }
988
989 /**
990 * Check if UID should be blocked from using the network with the given LinkProperties.
991 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600992 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
993 boolean ignoreBlocked) {
994 // Networks aren't blocked when ignoring blocked status
995 if (ignoreBlocked) return false;
996 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -0700997 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600998
999 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001000 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001001
Robin Lee17e61832016-05-09 13:46:28 +01001002 synchronized (mVpns) {
1003 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1004 if (vpn != null && vpn.isBlockingUid(uid)) {
1005 return true;
1006 }
1007 }
1008
Robert Greenwalt12e67352014-05-13 21:41:06 -07001009 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001010 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001011 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001012 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001013 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001014
Felipe Lemed31a97f2016-05-06 14:53:50 -07001015 boolean allowed = true;
1016 // Check Data Saver Mode first...
1017 if (networkMetered) {
1018 if ((uidRules & RULE_REJECT_METERED) != 0) {
1019 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1020 // Explicitly blacklisted.
1021 allowed = false;
1022 } else {
1023 allowed = !mRestrictBackground
1024 || (uidRules & RULE_ALLOW_METERED) != 0
1025 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1026 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1027 + " mRestrictBackground=" + mRestrictBackground
1028 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1029 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1030 + ": " + allowed);
1031 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001032 }
Felipe Leme781ba142016-05-09 16:24:48 -07001033 // ...then power restrictions.
1034 if (allowed) {
1035 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001036 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001037 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001038 }
1039 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001040 }
1041
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001042 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001043 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1044 return;
1045 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001046 boolean removed = false;
1047 boolean added = false;
1048 synchronized (mBlockedAppUids) {
1049 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1050 added = true;
1051 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1052 removed = true;
1053 }
1054 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001055 if (added) {
1056 log("Returning blocked NetworkInfo to uid=" + uid);
1057 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1058 } else if (removed) {
1059 log("Returning unblocked NetworkInfo to uid=" + uid);
1060 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1061 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001062 }
1063
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001064 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001065 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1066 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1067 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1068 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001069 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001070 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001071 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1072
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001073 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001074 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001075 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001076 if (mLockdownTracker != null) {
1077 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001078 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001079
1080 // TODO: apply metered state closer to NetworkAgentInfo
1081 final long token = Binder.clearCallingIdentity();
1082 try {
1083 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1084 } catch (RemoteException e) {
1085 } finally {
1086 Binder.restoreCallingIdentity(token);
1087 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001088 }
1089
1090 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 * Return NetworkInfo for the active (i.e., connected) network interface.
1092 * It is assumed that at most one network is active at a time. If more
1093 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001094 * @return the info for the active network, or {@code null} if none is
1095 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001097 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001099 enforceAccessPermission();
1100 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001101 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001102 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001103 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1104 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 }
1106
Paul Jensen31a94f42015-02-13 14:18:39 -05001107 @Override
1108 public Network getActiveNetwork() {
1109 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001110 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001111 }
1112
1113 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001114 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001115 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001116 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001117 }
1118
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001119 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001120 final int user = UserHandle.getUserId(uid);
1121 int vpnNetId = NETID_UNSET;
1122 synchronized (mVpns) {
1123 final Vpn vpn = mVpns.get(user);
1124 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1125 }
1126 NetworkAgentInfo nai;
1127 if (vpnNetId != NETID_UNSET) {
1128 synchronized (mNetworkForNetId) {
1129 nai = mNetworkForNetId.get(vpnNetId);
1130 }
1131 if (nai != null) return nai.network;
1132 }
1133 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001134 if (nai != null
1135 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1136 nai = null;
1137 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001138 return nai != null ? nai.network : null;
1139 }
1140
Lorenzo Colitti18660282016-07-04 12:55:44 +09001141 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001142 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1143 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001144 final int uid = Binder.getCallingUid();
1145 NetworkState state = getUnfilteredActiveNetworkState(uid);
1146 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001147 }
1148
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001149 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001150 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001151 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001152 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001153 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001154 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001155 }
1156
1157 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 public NetworkInfo getNetworkInfo(int networkType) {
1159 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001160 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001161 if (getVpnUnderlyingNetworks(uid) != null) {
1162 // A VPN is active, so we may need to return one of its underlying networks. This
1163 // information is not available in LegacyTypeTracker, so we have to get it from
1164 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001165 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001166 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001167 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001168 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001169 }
1170 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001171 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 }
1174
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001176 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001177 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001178 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001180 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001181 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001182 return state.networkInfo;
1183 } else {
1184 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001185 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001186 }
1187
1188 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 public NetworkInfo[] getAllNetworkInfo() {
1190 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001191 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001192 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1193 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001194 NetworkInfo info = getNetworkInfo(networkType);
1195 if (info != null) {
1196 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001199 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
1201
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001202 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001203 public Network getNetworkForType(int networkType) {
1204 enforceAccessPermission();
1205 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001206 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1207 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001208 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001209 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001210 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001211 }
1212
1213 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001214 public Network[] getAllNetworks() {
1215 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001216 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001217 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001218 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001219 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001220 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001221 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001222 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001223 }
1224
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001225 @Override
1226 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1227 // The basic principle is: if an app's traffic could possibly go over a
1228 // network, without the app doing anything multinetwork-specific,
1229 // (hence, by "default"), then include that network's capabilities in
1230 // the array.
1231 //
1232 // In the normal case, app traffic only goes over the system's default
1233 // network connection, so that's the only network returned.
1234 //
1235 // With a VPN in force, some app traffic may go into the VPN, and thus
1236 // over whatever underlying networks the VPN specifies, while other app
1237 // traffic may go over the system default network (e.g.: a split-tunnel
1238 // VPN, or an app disallowed by the VPN), so the set of networks
1239 // returned includes the VPN's underlying networks and the system
1240 // default.
1241 enforceAccessPermission();
1242
1243 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1244
1245 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001246 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001247 if (nc != null) {
1248 result.put(nai.network, nc);
1249 }
1250
1251 if (!mLockdownEnabled) {
1252 synchronized (mVpns) {
1253 Vpn vpn = mVpns.get(userId);
1254 if (vpn != null) {
1255 Network[] networks = vpn.getUnderlyingNetworks();
1256 if (networks != null) {
1257 for (Network network : networks) {
1258 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001259 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001260 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001261 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001262 }
1263 }
1264 }
1265 }
1266 }
1267 }
1268
1269 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1270 out = result.values().toArray(out);
1271 return out;
1272 }
1273
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001274 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001275 public boolean isNetworkSupported(int networkType) {
1276 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001277 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001278 }
1279
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001280 /**
1281 * Return LinkProperties for the active (i.e., connected) default
1282 * network interface. It is assumed that at most one default network
1283 * is active at a time. If more than one is active, it is indeterminate
1284 * which will be returned.
1285 * @return the ip properties for the active network, or {@code null} if
1286 * none is active
1287 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001288 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001289 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001290 enforceAccessPermission();
1291 final int uid = Binder.getCallingUid();
1292 NetworkState state = getUnfilteredActiveNetworkState(uid);
1293 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001294 }
1295
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001296 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001297 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001298 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001299 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1300 if (nai != null) {
1301 synchronized (nai) {
1302 return new LinkProperties(nai.linkProperties);
1303 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001304 }
1305 return null;
1306 }
1307
Robert Greenwalt12e67352014-05-13 21:41:06 -07001308 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001309 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001310 public LinkProperties getLinkProperties(Network network) {
1311 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001312 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001313 if (nai != null) {
1314 synchronized (nai) {
1315 return new LinkProperties(nai.linkProperties);
1316 }
1317 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001318 return null;
1319 }
1320
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001321 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001322 if (nai != null) {
1323 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001324 if (nai.networkCapabilities != null) {
1325 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001326 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001327 }
1328 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001329 return null;
1330 }
1331
1332 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001333 public NetworkCapabilities getNetworkCapabilities(Network network) {
1334 enforceAccessPermission();
1335 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1336 }
1337
1338 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001339 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001340 // Require internal since we're handing out IMSI details
1341 enforceConnectivityInternalPermission();
1342
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001343 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001344 for (Network network : getAllNetworks()) {
1345 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1346 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001347 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001348 }
1349 }
1350 return result.toArray(new NetworkState[result.size()]);
1351 }
1352
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001353 @Override
1354 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1355 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001356 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001357 final long token = Binder.clearCallingIdentity();
1358 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001359 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1360 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001361 try {
1362 return mPolicyManager.getNetworkQuotaInfo(state);
1363 } catch (RemoteException e) {
1364 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001365 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001366 return null;
1367 } finally {
1368 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001369 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001370 }
1371
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001372 @Override
1373 public boolean isActiveNetworkMetered() {
1374 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001375
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001376 final NetworkInfo info = getActiveNetworkInfo();
1377 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001378 }
1379
Jeff Sharkey216c1812012-08-05 14:29:23 -07001380 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1381 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001382 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001383 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001384 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001385 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001386 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001387
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001388 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 * Ensure that a network route exists to deliver traffic to the specified
1390 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001391 * @param networkType the type of the network over which traffic to the
1392 * specified host is to be routed
1393 * @param hostAddress the IP address of the host to which the route is
1394 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 * @return {@code true} on success, {@code false} on failure
1396 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001397 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001398 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001400 if (mProtectedNetworks.contains(networkType)) {
1401 enforceConnectivityInternalPermission();
1402 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001403
Chad Brubakerc0234532014-02-14 13:24:29 -08001404 InetAddress addr;
1405 try {
1406 addr = InetAddress.getByAddress(hostAddress);
1407 } catch (UnknownHostException e) {
1408 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1409 return false;
1410 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001413 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 return false;
1415 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001416
1417 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1418 if (nai == null) {
1419 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1420 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1421 } else {
1422 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1423 }
1424 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001425 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001426
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001427 DetailedState netState;
1428 synchronized (nai) {
1429 netState = nai.networkInfo.getDetailedState();
1430 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001431
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001432 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001433 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001434 log("requestRouteToHostAddress on down network "
1435 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001436 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001437 }
1438 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001440
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001441 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001442 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001443 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001444 LinkProperties lp;
1445 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001446 synchronized (nai) {
1447 lp = nai.linkProperties;
1448 netId = nai.network.netId;
1449 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001450 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001451 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1452 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001453 } finally {
1454 Binder.restoreCallingIdentity(token);
1455 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001456 }
1457
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001458 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001459 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001460 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001461 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001462 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001463 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001464 if (bestRoute.getGateway().equals(addr)) {
1465 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001466 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001467 } else {
1468 // if we will connect to this through another route, add a direct route
1469 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001470 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001471 }
1472 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001473 if (DBG) log("Adding legacy route " + bestRoute +
1474 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001475 try {
1476 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1477 } catch (Exception e) {
1478 // never crash - catch them all
1479 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001480 return false;
1481 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001482 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 }
1484
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001485 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1486 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001487 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001488 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001489 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001490 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001491 }
1492
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001493 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001494 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001495 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001496 if (oldRules == uidRules) return;
1497
Felipe Leme781ba142016-05-09 16:24:48 -07001498 if (uidRules == RULE_NONE) {
1499 mUidRules.delete(uid);
1500 } else {
1501 mUidRules.put(uid, uidRules);
1502 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001503 }
1504
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001505 // TODO: notify UID when it has requested targeted updates
1506 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001507
1508 @Override
1509 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001510 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001511 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001512 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001513 }
1514
1515 synchronized (mRulesLock) {
1516 mMeteredIfaces.clear();
1517 for (String iface : meteredIfaces) {
1518 mMeteredIfaces.add(iface);
1519 }
1520 }
1521 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001522
1523 @Override
1524 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1525 // caller is NPMS, since we only register with them
1526 if (LOGD_RULES) {
1527 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1528 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001529
1530 synchronized (mRulesLock) {
1531 mRestrictBackground = restrictBackground;
1532 }
1533
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001534 if (restrictBackground) {
1535 log("onRestrictBackgroundChanged(true): disabling tethering");
1536 mTethering.untetherAll();
1537 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001538 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001539
1540 @Override
1541 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1542 if (LOGD_RULES) {
1543 // caller is NPMS, since we only register with them
1544 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1545 + whitelisted + ")");
1546 }
1547 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001548 @Override
1549 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1550 if (LOGD_RULES) {
1551 // caller is NPMS, since we only register with them
1552 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1553 + blacklisted + ")");
1554 }
1555 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001556 };
1557
Robin Lee3b3dd942015-05-12 18:14:58 +01001558 /**
1559 * Require that the caller is either in the same user or has appropriate permission to interact
1560 * across users.
1561 *
1562 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1563 */
1564 private void enforceCrossUserPermission(int userId) {
1565 if (userId == UserHandle.getCallingUserId()) {
1566 // Not a cross-user call.
1567 return;
1568 }
1569 mContext.enforceCallingOrSelfPermission(
1570 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1571 "ConnectivityService");
1572 }
1573
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001574 private void enforceInternetPermission() {
1575 mContext.enforceCallingOrSelfPermission(
1576 android.Manifest.permission.INTERNET,
1577 "ConnectivityService");
1578 }
1579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001581 mContext.enforceCallingOrSelfPermission(
1582 android.Manifest.permission.ACCESS_NETWORK_STATE,
1583 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 }
1585
1586 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001587 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 }
1589
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001590 private void enforceTetherAccessPermission() {
1591 mContext.enforceCallingOrSelfPermission(
1592 android.Manifest.permission.ACCESS_NETWORK_STATE,
1593 "ConnectivityService");
1594 }
1595
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001596 private void enforceConnectivityInternalPermission() {
1597 mContext.enforceCallingOrSelfPermission(
1598 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1599 "ConnectivityService");
1600 }
1601
Hugo Benichi514da602016-07-19 15:59:27 +09001602 private void enforceConnectivityRestrictedNetworksPermission() {
1603 try {
1604 mContext.enforceCallingOrSelfPermission(
1605 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1606 "ConnectivityService");
1607 return;
1608 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1609 enforceConnectivityInternalPermission();
1610 }
1611
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001612 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001613 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001614 }
1615
Lorenzo Colitti18660282016-07-04 12:55:44 +09001616 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001617 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001618 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001619 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001620 }
1621
1622 private void sendInetConditionBroadcast(NetworkInfo info) {
1623 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1624 }
1625
Wink Saville628b0852011-08-04 15:01:58 -07001626 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001627 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001628 info = new NetworkInfo(info);
1629 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001630 }
1631
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001632 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001633 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001634 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 if (info.isFailover()) {
1636 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1637 info.setFailover(false);
1638 }
1639 if (info.getReason() != null) {
1640 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1641 }
1642 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001643 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1644 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001646 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001647 return intent;
1648 }
1649
1650 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1651 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1652 }
1653
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001654 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001655 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1656 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1657 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001658 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001659 final long ident = Binder.clearCallingIdentity();
1660 try {
1661 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1662 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1663 } finally {
1664 Binder.restoreCallingIdentity(ident);
1665 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001666 }
1667
Mike Lockwood0f79b542009-08-14 14:18:49 -04001668 private void sendStickyBroadcast(Intent intent) {
1669 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001670 if (!mSystemReady) {
1671 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001672 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001673 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001674 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001675 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001676 }
1677
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001678 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001679 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001680 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001681 final NetworkInfo ni = intent.getParcelableExtra(
1682 ConnectivityManager.EXTRA_NETWORK_INFO);
1683 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1684 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1685 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001686 } else {
1687 BroadcastOptions opts = BroadcastOptions.makeBasic();
1688 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1689 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001690 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001691 final IBatteryStats bs = BatteryStatsService.getService();
1692 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001693 bs.noteConnectivityChanged(intent.getIntExtra(
1694 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1695 ni != null ? ni.getState().toString() : "?");
1696 } catch (RemoteException e) {
1697 }
1698 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001699 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001700 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001701 } finally {
1702 Binder.restoreCallingIdentity(ident);
1703 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001704 }
1705 }
1706
1707 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001708 loadGlobalProxy();
1709
Mike Lockwood0f79b542009-08-14 14:18:49 -04001710 synchronized(this) {
1711 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001712 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001713 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001714 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001715 }
1716 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001717 // load the global proxy at startup
1718 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001719
Robin Lee244ce8e2016-01-05 18:03:46 +00001720 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1721 // for user to unlock device too.
1722 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001723
Erik Klineda4bfa82015-04-30 12:58:40 +09001724 // Configure whether mobile data is always on.
1725 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1726
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001727 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001728
1729 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 }
1731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001733 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001734 *
1735 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001736 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001737 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001738 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1739 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001740
1741 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001742 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001743
Robert Greenwalt7b816022014-04-18 15:25:25 -07001744 if (networkAgent.networkCapabilities.hasTransport(
1745 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001746 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1747 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001748 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001749 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001750 } else if (networkAgent.networkCapabilities.hasTransport(
1751 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001752 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1753 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001754 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001755 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001756 } else {
1757 // do not track any other networks
1758 timeout = 0;
1759 }
1760
Robert Greenwalt7b816022014-04-18 15:25:25 -07001761 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001762 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001763 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001764 } catch (Exception e) {
1765 // You shall not crash!
1766 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001767 }
1768 }
1769 }
1770
1771 /**
1772 * Remove data activity tracking when network disconnects.
1773 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001774 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1775 final String iface = networkAgent.linkProperties.getInterfaceName();
1776 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001777
Robert Greenwalt7b816022014-04-18 15:25:25 -07001778 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1779 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001780 try {
1781 // the call fails silently if no idletimer setup for this interface
1782 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001783 } catch (Exception e) {
1784 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001785 }
1786 }
1787 }
1788
1789 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001790 * Reads the network specific MTU size from reources.
1791 * and set it on it's iface.
1792 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001793 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1794 final String iface = newLp.getInterfaceName();
1795 final int mtu = newLp.getMtu();
1796 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1797 if (VDBG) log("identical MTU - not setting");
1798 return;
1799 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001800
Robert Greenwalt43074032014-08-15 17:53:05 -07001801 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001802 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001803 return;
1804 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001805
w1997615afd812014-08-05 15:18:11 -07001806 // Cannot set MTU without interface name
1807 if (TextUtils.isEmpty(iface)) {
1808 loge("Setting MTU size with null iface.");
1809 return;
1810 }
1811
Robert Greenwalt7b816022014-04-18 15:25:25 -07001812 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001813 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001814 mNetd.setMtu(iface, mtu);
1815 } catch (Exception e) {
1816 Slog.e(TAG, "exception in setMtu()" + e);
1817 }
1818 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001819
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001820 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001821 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1822
1823 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001824 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001825 protected int getDefaultTcpRwnd() {
1826 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1827 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001828
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001829 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1830 if (isDefaultNetwork(nai) == false) {
1831 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001832 }
1833
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001834 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1835 String[] values = null;
1836 if (tcpBufferSizes != null) {
1837 values = tcpBufferSizes.split(",");
1838 }
1839
1840 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001841 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001842 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1843 values = tcpBufferSizes.split(",");
1844 }
1845
1846 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1847
1848 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001849 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001850
1851 final String prefix = "/sys/kernel/ipv4/tcp_";
1852 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1853 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1854 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1855 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1856 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1857 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1858 mCurrentTcpBufferSizes = tcpBufferSizes;
1859 } catch (IOException e) {
1860 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001861 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001862
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001863 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001864 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001865 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1866 if (rwndValue != 0) {
1867 SystemProperties.set(sysctlKey, rwndValue.toString());
1868 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001869 }
1870
Mattias Falk8b47b362011-08-23 14:15:13 +02001871 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001872 /*
1873 * Tell the VMs to toss their DNS caches
1874 */
1875 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1876 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001877 /*
1878 * Connectivity events can happen before boot has completed ...
1879 */
1880 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001881 final long ident = Binder.clearCallingIdentity();
1882 try {
1883 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1884 } finally {
1885 Binder.restoreCallingIdentity(ident);
1886 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001887 }
1888
Robert Greenwalt562cc542014-05-15 18:07:26 -07001889 @Override
1890 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001891 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1892 NETWORK_RESTORE_DELAY_PROP_NAME);
1893 if(restoreDefaultNetworkDelayStr != null &&
1894 restoreDefaultNetworkDelayStr.length() != 0) {
1895 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001896 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001897 } catch (NumberFormatException e) {
1898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001900 // if the system property isn't set, use the value for the apn type
1901 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1902
1903 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1904 (mNetConfigs[networkType] != null)) {
1905 ret = mNetConfigs[networkType].restoreTime;
1906 }
1907 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 }
1909
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001910 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001911 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001912 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001913 }
1914 return false;
1915 }
1916
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001917 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1918 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1919 final long DIAG_TIME_MS = 5000;
1920 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1921 // Start gathering diagnostic information.
1922 netDiags.add(new NetworkDiagnostics(
1923 nai.network,
1924 new LinkProperties(nai.linkProperties), // Must be a copy.
1925 DIAG_TIME_MS));
1926 }
1927
1928 for (NetworkDiagnostics netDiag : netDiags) {
1929 pw.println();
1930 netDiag.waitForMeasurements();
1931 netDiag.dump(pw);
1932 }
1933 }
1934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001936 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1937 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001938 if (mContext.checkCallingOrSelfPermission(
1939 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001941 pw.println("Permission Denial: can't dump ConnectivityService " +
1942 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1943 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 return;
1945 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001946
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001947 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001948 dumpNetworkDiagnostics(pw);
1949 return;
1950 }
Erik Kline379747a2015-06-05 17:47:34 +09001951
Lorenzo Colittie3805462015-06-03 11:18:24 +09001952 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001953 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001954 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001955 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001956 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001957 pw.println();
1958
Paul Jensen85cf78e2015-06-25 13:25:07 -04001959 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001960 pw.print("Active default network: ");
1961 if (defaultNai == null) {
1962 pw.println("none");
1963 } else {
1964 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001966 pw.println();
1967
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001968 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001969 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001970 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1971 pw.println(nai.toString());
1972 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001973 pw.println(String.format("Requests: %d request/%d total",
1974 nai.numRequestNetworkRequests(), nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001975 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001976 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1977 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001978 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001979 pw.decreaseIndent();
1980 pw.println("Lingered:");
1981 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001982 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001983 pw.decreaseIndent();
1984 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001985 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001986 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001987 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001988
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001989 pw.println("Metered Interfaces:");
1990 pw.increaseIndent();
1991 for (String value : mMeteredIfaces) {
1992 pw.println(value);
1993 }
1994 pw.decreaseIndent();
1995 pw.println();
1996
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001997 pw.print("Restrict background: ");
1998 pw.println(mRestrictBackground);
1999 pw.println();
2000
Felipe Leme46c4fc32016-05-04 09:21:43 -07002001 pw.println("Status for known UIDs:");
2002 pw.increaseIndent();
2003 final int size = mUidRules.size();
2004 for (int i = 0; i < size; i++) {
2005 final int uid = mUidRules.keyAt(i);
2006 pw.print("UID=");
2007 pw.print(uid);
2008 final int uidRules = mUidRules.get(uid, RULE_NONE);
2009 pw.print(" rules=");
2010 pw.print(uidRulesToString(uidRules));
2011 pw.println();
2012 }
2013 pw.println();
2014 pw.decreaseIndent();
2015
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002016 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002017 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002018 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2019 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002020 }
2021 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002022 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002023
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002024 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002025
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002026 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002027 pw.print("mNetTransitionWakeLock: currently " +
2028 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2029 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2030 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2031 } else {
2032 pw.println(", last requested never");
2033 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002034 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002035
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002036 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002037 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002038
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002039 pw.println();
2040 mKeepaliveTracker.dump(pw);
2041
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002042 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002043
Lorenzo Colittie3805462015-06-03 11:18:24 +09002044 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002045 pw.println();
2046 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002047 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002048 for(int i = 0; i < mInetLog.size(); i++) {
2049 pw.println(mInetLog.get(i));
2050 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002051 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002052 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002053
2054 if (argsContain(args, "--short") == false) {
2055 pw.println();
2056 synchronized (mValidationLogs) {
2057 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002058 for (ValidationLog p : mValidationLogs) {
2059 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002060 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002061 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002062 pw.decreaseIndent();
2063 }
2064 }
Erik Kline7523eb32015-07-09 18:24:03 +09002065
2066 pw.println();
2067 pw.println("mNetworkRequestInfoLogs (most recent first):");
2068 pw.increaseIndent();
2069 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2070 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002071
2072 pw.println();
2073 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2074 pw.increaseIndent();
2075 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2076 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 }
2079
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002080 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002081 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002082 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002083 if (officialNai != null && officialNai.equals(nai)) return true;
2084 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002085 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002086 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002087 " - " + nai);
2088 }
2089 return false;
2090 }
2091
Robert Greenwalt42acef32009-08-12 16:08:25 -07002092 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002093 private class NetworkStateTrackerHandler extends Handler {
2094 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002095 super(looper);
2096 }
2097
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002098 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002100 default:
2101 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002102 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002103 handleAsyncChannelHalfConnect(msg);
2104 break;
2105 }
2106 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2107 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2108 if (nai != null) nai.asyncChannel.disconnect();
2109 break;
2110 }
2111 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2112 handleAsyncChannelDisconnected(msg);
2113 break;
2114 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002115 }
2116 return true;
2117 }
2118
2119 private void maybeHandleNetworkAgentMessage(Message msg) {
2120 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2121 if (nai == null) {
2122 if (VDBG) {
2123 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2124 log(String.format("%s from unknown NetworkAgent", what));
2125 }
2126 return;
2127 }
2128
2129 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002130 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002131 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2132 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2133 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2134 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002135 }
Robin Lee585e2482016-05-01 23:00:00 +01002136 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002137 networkCapabilities)) {
2138 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2139 + nai.networkCapabilities + " -> " + networkCapabilities);
2140 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002141 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002142 break;
2143 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002144 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002145 if (VDBG) {
2146 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002147 "; created=" + nai.created +
2148 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002149 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002150 LinkProperties oldLp = nai.linkProperties;
2151 synchronized (nai) {
2152 nai.linkProperties = (LinkProperties)msg.obj;
2153 }
Robin Lee585e2482016-05-01 23:00:00 +01002154 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002155 break;
2156 }
2157 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002158 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002159 updateNetworkInfo(nai, info);
2160 break;
2161 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002162 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002163 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002164 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002165 break;
2166 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002167 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002168 try {
2169 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002170 } catch (Exception e) {
2171 // Never crash!
2172 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002173 }
2174 break;
2175 }
2176 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002177 try {
2178 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002179 } catch (Exception e) {
2180 // Never crash!
2181 loge("Exception in removeVpnUidRanges: " + e);
2182 }
2183 break;
2184 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002185 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002186 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2187 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002188 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002189 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002190 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002191 break;
2192 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002193 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002194 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2195 break;
2196 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002197 }
2198 }
2199
2200 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2201 switch (msg.what) {
2202 default:
2203 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002204 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002205 final NetworkAgentInfo nai;
2206 synchronized (mNetworkForNetId) {
2207 nai = mNetworkForNetId.get(msg.arg2);
2208 }
2209 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002210 final boolean valid =
2211 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002212 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2213 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002214 if (valid != nai.lastValidated) {
2215 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002216 nai.lastValidated = valid;
2217 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002218 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002219 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2220 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002221 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002222 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002223 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002224 Bundle redirectUrlBundle = new Bundle();
2225 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002226 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002227 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002228 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002229 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002230 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002231 break;
2232 }
Paul Jensen869868be2014-05-15 10:33:05 -04002233 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002234 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002235 final boolean visible = (msg.arg1 != 0);
2236 final NetworkAgentInfo nai;
2237 synchronized (mNetworkForNetId) {
2238 nai = mNetworkForNetId.get(netId);
2239 }
2240 // If captive portal status has changed, update capabilities.
2241 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002242 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002243 nai.lastCaptivePortalDetected = visible;
2244 nai.everCaptivePortalDetected |= visible;
Hugo Benichif15b2822016-09-15 18:18:48 +09002245 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002246 }
2247 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002248 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002249 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002250 if (nai == null) {
2251 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2252 break;
2253 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002254 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002255 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002256 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002257 }
Paul Jensen869868be2014-05-15 10:33:05 -04002258 }
Paul Jensen869868be2014-05-15 10:33:05 -04002259 break;
2260 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002261 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002262 return true;
2263 }
2264
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002265 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2266 switch (msg.what) {
2267 default:
2268 return false;
2269 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2270 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2271 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2272 handleLingerComplete(nai);
2273 }
2274 break;
2275 }
2276 }
2277 return true;
2278 }
2279
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002280 @Override
2281 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002282 if (!maybeHandleAsyncChannelMessage(msg) &&
2283 !maybeHandleNetworkMonitorMessage(msg) &&
2284 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002285 maybeHandleNetworkAgentMessage(msg);
2286 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002287 }
2288 }
2289
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002290 private void updateLingerState(NetworkAgentInfo nai, long now) {
2291 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2292 // 2. If the network was lingering and there are now requests, unlinger it.
2293 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2294 // one lingered request, start lingering.
2295 nai.updateLingerTimer();
2296 if (nai.isLingering() && nai.numRequestNetworkRequests() > 0) {
2297 if (DBG) log("Unlingering " + nai.name());
2298 nai.unlinger();
2299 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
2300 } else if (unneeded(nai) && nai.getLingerExpiry() > 0) { // unneeded() calls isLingering()
2301 int lingerTime = (int) (nai.getLingerExpiry() - now);
2302 if (DBG) {
2303 Log.d(TAG, "Lingering " + nai.name() + " for " + lingerTime + "ms");
2304 }
2305 nai.linger();
2306 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2307 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2308 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002309 }
2310
Robert Greenwalt7b816022014-04-18 15:25:25 -07002311 private void handleAsyncChannelHalfConnect(Message msg) {
2312 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002313 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002314 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2315 if (VDBG) log("NetworkFactory connected");
2316 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002317 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002318 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002319 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002320 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002321 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002322 }
2323 } else {
2324 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002325 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002326 }
2327 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2328 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2329 if (VDBG) log("NetworkAgent connected");
2330 // A network agent has requested a connection. Establish the connection.
2331 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2332 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2333 } else {
2334 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002335 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002336 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002337 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002338 synchronized (mNetworkForNetId) {
2339 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002340 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002341 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002342 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002343 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002344 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002345 }
2346 }
2347 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002348
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349 private void handleAsyncChannelDisconnected(Message msg) {
2350 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2351 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002352 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002353 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002354 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002355 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002356 // TODO - if we move the logic to the network agent (have them disconnect
2357 // because they lost all their requests or because their score isn't good)
2358 // then they would disconnect organically, report their new state and then
2359 // disconnect the channel.
2360 if (nai.networkInfo.isConnected()) {
2361 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2362 null, null);
2363 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002364 final boolean wasDefault = isDefaultNetwork(nai);
2365 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002366 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002367 // Log default network disconnection before required book-keeping.
2368 // Let rematchAllNetworksAndRequests() below record a new default network event
2369 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2370 // whose timestamps tell how long it takes to recover a default network.
2371 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002372 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002373 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002374 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2375 // by other networks that are already connected. Perhaps that can be done by
2376 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2377 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002378 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002379 mKeepaliveTracker.handleStopAllKeepalives(nai,
2380 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002381 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002382 mNetworkAgentInfos.remove(msg.replyTo);
2383 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002384 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002385 // Remove the NetworkAgent, but don't mark the netId as
2386 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002387 mNetworkForNetId.remove(nai.network.netId);
2388 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002389 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002390 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2391 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002392 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2393 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2394 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002395 sendUpdatedScoreToFactories(request, 0);
2396 }
2397 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002398 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002399 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002400 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002401 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002402 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002403 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002404 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002405 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002406 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002407 if (nai.created) {
2408 // Tell netd to clean up the configuration for this network
2409 // (routing rules, DNS, etc).
2410 // This may be slow as it requires a lot of netd shelling out to ip and
2411 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2412 // after we've rematched networks with requests which should make a potential
2413 // fallback network the default or requested a new network from the
2414 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2415 // long time.
2416 try {
2417 mNetd.removeNetwork(nai.network.netId);
2418 } catch (Exception e) {
2419 loge("Exception removing network: " + e);
2420 }
2421 }
2422 synchronized (mNetworkForNetId) {
2423 mNetIdInUse.delete(nai.network.netId);
2424 }
2425 } else {
2426 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2427 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002428 }
2429 }
2430
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002431 // If this method proves to be too slow then we can maintain a separate
2432 // pendingIntent => NetworkRequestInfo map.
2433 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2434 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2435 Intent intent = pendingIntent.getIntent();
2436 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2437 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2438 if (existingPendingIntent != null &&
2439 existingPendingIntent.getIntent().filterEquals(intent)) {
2440 return entry.getValue();
2441 }
2442 }
2443 return null;
2444 }
2445
2446 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2447 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2448
2449 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2450 if (existingRequest != null) { // remove the existing request.
2451 if (DBG) log("Replacing " + existingRequest.request + " with "
2452 + nri.request + " because their intents matched.");
2453 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2454 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002455 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002456 }
2457
Erik Klineda4bfa82015-04-30 12:58:40 +09002458 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002459 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002460 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002461 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002462 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002463 if (nri.request.networkCapabilities.hasSignalStrength() &&
2464 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2465 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002466 }
2467 }
2468 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002469 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002470 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002471 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002472 }
2473 }
2474
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002475 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2476 int callingUid) {
2477 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2478 if (nri != null) {
2479 handleReleaseNetworkRequest(nri.request, callingUid);
2480 }
2481 }
2482
Paul Jensen99364842014-12-09 11:43:45 -05002483 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002484 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2485 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002486 private boolean unneeded(NetworkAgentInfo nai) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002487 if (!nai.everConnected || nai.isVPN() ||
2488 nai.isLingering() || nai.numRequestNetworkRequests() > 0) {
2489 return false;
2490 }
Paul Jensene0988542015-06-25 15:30:08 -04002491 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2492 // If this Network is already the highest scoring Network for a request, or if
2493 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002494 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002495 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002496 // Note that this catches two important cases:
2497 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2498 // is currently satisfying the request. This is desirable when
2499 // cellular ends up validating but WiFi does not.
2500 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002501 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002502 // WiFi ends up validating and out scoring cellular.
2503 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2504 nai.getCurrentScoreAsValidated())) {
2505 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002506 }
2507 }
Paul Jensene0988542015-06-25 15:30:08 -04002508 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002509 }
2510
Erik Klineacdd6392016-07-07 16:50:58 +09002511 private NetworkRequestInfo getNriForAppRequest(
2512 NetworkRequest request, int callingUid, String requestedOperation) {
2513 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2514
Robert Greenwalt9258c642014-03-26 16:47:06 -07002515 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002516 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002517 log(String.format("UID %d attempted to %s for unowned request %s",
2518 callingUid, requestedOperation, nri));
2519 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002520 }
Erik Klineacdd6392016-07-07 16:50:58 +09002521 }
2522
2523 return nri;
2524 }
2525
2526 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2527 String description, int callbackType) {
2528 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2529 if (nri == null) return;
2530
2531 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2532 // The network that is satisfying this request may have changed since
2533 // the application requested the update.
2534 //
2535 // - If the request is no longer satisfied, don't send any updates.
2536 // - If the request is satisfied by a different network, it is the
2537 // caller's responsibility to check that the Network object in the
2538 // callback matches the network that was returned in the last
2539 // onAvailable() callback for this request.
2540 if (nai == null) return;
2541 callCallbackForRequest(nri, nai, callbackType, 0);
2542 }
2543
2544 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2545 handleRequestCallbackUpdate(request, callingUid,
2546 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2547 }
2548
2549 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2550 handleRequestCallbackUpdate(request, callingUid,
2551 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2552 }
2553
2554 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2555 final NetworkRequestInfo nri = getNriForAppRequest(
2556 request, callingUid, "release NetworkRequest");
2557 if (nri == null) return;
2558
2559 if (VDBG || (DBG && nri.request.isRequest())) log("releasing " + request);
2560 nri.unlinkDeathRecipient();
2561 mNetworkRequests.remove(request);
2562 synchronized (mUidToNetworkRequestCount) {
2563 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2564 if (requests < 1) {
2565 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2566 nri.mUid);
2567 } else if (requests == 1) {
2568 mUidToNetworkRequestCount.removeAt(
2569 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2570 } else {
2571 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2572 }
2573 }
2574 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2575 if (nri.request.isRequest()) {
2576 boolean wasKept = false;
2577 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2578 if (nai != null) {
2579 nai.removeRequest(nri.request.requestId);
2580 if (VDBG) {
2581 log(" Removing from current network " + nai.name() +
2582 ", leaving " + nai.numNetworkRequests() + " requests.");
2583 }
2584 // If there are still lingered requests on this network, don't tear it down,
2585 // but resume lingering instead.
2586 updateLingerState(nai, SystemClock.elapsedRealtime());
2587 if (unneeded(nai)) {
2588 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2589 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002590 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002591 wasKept = true;
2592 }
2593 mNetworkForRequestId.remove(nri.request.requestId);
2594 }
2595
2596 // TODO: remove this code once we know that the Slog.wtf is never hit.
2597 //
2598 // Find all networks that are satisfying this request and remove the request
2599 // from their request lists.
2600 // TODO - it's my understanding that for a request there is only a single
2601 // network satisfying it, so this loop is wasteful
2602 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2603 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2604 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2605 otherNai.name() + ", but mNetworkAgentInfos says " +
2606 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002607 }
2608 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002609
Erik Klineacdd6392016-07-07 16:50:58 +09002610 // Maintain the illusion. When this request arrived, we might have pretended
2611 // that a network connected to serve it, even though the network was already
2612 // connected. Now that this request has gone away, we might have to pretend
2613 // that the network disconnected. LegacyTypeTracker will generate that
2614 // phantom disconnect for this type.
2615 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2616 boolean doRemove = true;
2617 if (wasKept) {
2618 // check if any of the remaining requests for this network are for the
2619 // same legacy type - if so, don't remove the nai
2620 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2621 NetworkRequest otherRequest = nai.requestAt(i);
2622 if (otherRequest.legacyType == nri.request.legacyType &&
2623 otherRequest.isRequest()) {
2624 if (DBG) log(" still have other legacy request - leaving");
2625 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002626 }
2627 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002628 }
2629
Erik Klineacdd6392016-07-07 16:50:58 +09002630 if (doRemove) {
2631 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002632 }
2633 }
Erik Klineacdd6392016-07-07 16:50:58 +09002634
2635 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2636 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2637 nri.request);
2638 }
2639 } else {
2640 // listens don't have a singular affectedNetwork. Check all networks to see
2641 // if this listen request applies and remove it.
2642 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2643 nai.removeRequest(nri.request.requestId);
2644 if (nri.request.networkCapabilities.hasSignalStrength() &&
2645 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2646 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2647 }
2648 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002649 }
Erik Klineacdd6392016-07-07 16:50:58 +09002650 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002651 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002652
Lorenzo Colitti18660282016-07-04 12:55:44 +09002653 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002654 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2655 enforceConnectivityInternalPermission();
2656 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2657 accept ? 1 : 0, always ? 1: 0, network));
2658 }
2659
2660 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2661 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2662 " accept=" + accept + " always=" + always);
2663
2664 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2665 if (nai == null) {
2666 // Nothing to do.
2667 return;
2668 }
2669
2670 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002671 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002672 return;
2673 }
2674
2675 if (!nai.networkMisc.explicitlySelected) {
2676 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2677 }
2678
2679 if (accept != nai.networkMisc.acceptUnvalidated) {
2680 int oldScore = nai.getCurrentScore();
2681 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002682 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002683 sendUpdatedScoreToFactories(nai);
2684 }
2685
2686 if (always) {
2687 nai.asyncChannel.sendMessage(
2688 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2689 }
2690
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002691 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002692 // Tell the NetworkAgent to not automatically reconnect to the network.
2693 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2694 // Teardown the nework.
2695 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002696 }
2697
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002698 }
2699
2700 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002701 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002702 mHandler.sendMessageDelayed(
2703 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2704 PROMPT_UNVALIDATED_DELAY_MS);
2705 }
2706
2707 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002708 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002709 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2710
2711 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2712 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002713 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002714 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002715 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2716 return;
2717 }
2718
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002719 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002720 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002721 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2722 intent.setClassName("com.android.settings",
2723 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002724
2725 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2726 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
fionaxu1bf6ec22016-05-23 16:33:16 -07002727
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002728 mNotifier.showNotification(nai.network.netId, NotificationType.NO_INTERNET, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002729 pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002730 }
2731
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002732 private class InternalHandler extends Handler {
2733 public InternalHandler(Looper looper) {
2734 super(looper);
2735 }
2736
2737 @Override
2738 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002739 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002740 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002741 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002742 String causedBy = null;
2743 synchronized (ConnectivityService.this) {
2744 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2745 mNetTransitionWakeLock.isHeld()) {
2746 mNetTransitionWakeLock.release();
2747 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002748 } else {
2749 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002750 }
2751 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002752 if (VDBG) {
2753 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2754 log("Failed to find a new network - expiring NetTransition Wakelock");
2755 } else {
2756 log("NetTransition Wakelock (" +
2757 (causedBy == null ? "unknown" : causedBy) +
2758 " cleared because we found a replacement network");
2759 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002760 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002761 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002762 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002763 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002764 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002765 break;
2766 }
Jason Monkdecd2952013-10-10 14:02:51 -04002767 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002768 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002769 break;
2770 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002771 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002772 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2773 break;
2774 }
2775 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2776 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002777 break;
2778 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002779 case EVENT_REGISTER_NETWORK_AGENT: {
2780 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2781 break;
2782 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002783 case EVENT_REGISTER_NETWORK_REQUEST:
2784 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002785 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002786 break;
2787 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002788 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2789 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002790 handleRegisterNetworkRequestWithIntent(msg);
2791 break;
2792 }
2793 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2794 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2795 break;
2796 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002797 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002798 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002799 break;
2800 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002801 case EVENT_SET_ACCEPT_UNVALIDATED: {
2802 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2803 break;
2804 }
2805 case EVENT_PROMPT_UNVALIDATED: {
2806 handlePromptUnvalidated((Network) msg.obj);
2807 break;
2808 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002809 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2810 handleMobileDataAlwaysOn();
2811 break;
2812 }
Erik Klineacdd6392016-07-07 16:50:58 +09002813 case EVENT_REQUEST_LINKPROPERTIES:
2814 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2815 break;
2816 case EVENT_REQUEST_NETCAPABILITIES:
2817 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2818 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002819 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2820 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2821 mKeepaliveTracker.handleStartKeepalive(msg);
2822 break;
2823 }
2824 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2825 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2826 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2827 int slot = msg.arg1;
2828 int reason = msg.arg2;
2829 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2830 break;
2831 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002832 case EVENT_SYSTEM_READY: {
2833 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2834 nai.networkMonitor.systemReady = true;
2835 }
2836 break;
2837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 }
2839 }
2840 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002841
2842 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002843 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002844 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002845 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002846 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002847 final int status = mTethering.tether(iface);
2848 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2849 try {
2850 mPolicyManager.onTetheringChanged(iface, true);
2851 } catch (RemoteException e) {
2852 }
2853 }
2854 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002855 } else {
2856 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2857 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002858 }
2859
2860 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002861 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002862 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002863 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002864
2865 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002866 final int status = mTethering.untether(iface);
2867 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2868 try {
2869 mPolicyManager.onTetheringChanged(iface, false);
2870 } catch (RemoteException e) {
2871 }
2872 }
2873 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002874 } else {
2875 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2876 }
2877 }
2878
2879 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002880 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002881 public int getLastTetherError(String iface) {
2882 enforceTetherAccessPermission();
2883
2884 if (isTetheringSupported()) {
2885 return mTethering.getLastTetherError(iface);
2886 } else {
2887 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2888 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002889 }
2890
2891 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002892 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002893 public String[] getTetherableUsbRegexs() {
2894 enforceTetherAccessPermission();
2895 if (isTetheringSupported()) {
2896 return mTethering.getTetherableUsbRegexs();
2897 } else {
2898 return new String[0];
2899 }
2900 }
2901
Lorenzo Colitti18660282016-07-04 12:55:44 +09002902 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002903 public String[] getTetherableWifiRegexs() {
2904 enforceTetherAccessPermission();
2905 if (isTetheringSupported()) {
2906 return mTethering.getTetherableWifiRegexs();
2907 } else {
2908 return new String[0];
2909 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002910 }
2911
Lorenzo Colitti18660282016-07-04 12:55:44 +09002912 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002913 public String[] getTetherableBluetoothRegexs() {
2914 enforceTetherAccessPermission();
2915 if (isTetheringSupported()) {
2916 return mTethering.getTetherableBluetoothRegexs();
2917 } else {
2918 return new String[0];
2919 }
2920 }
2921
Lorenzo Colitti18660282016-07-04 12:55:44 +09002922 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002923 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002924 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002925 if (isTetheringSupported()) {
2926 return mTethering.setUsbTethering(enable);
2927 } else {
2928 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2929 }
2930 }
2931
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002932 // TODO - move iface listing, queries, etc to new module
2933 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002934 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002935 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002936 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002937 return mTethering.getTetherableIfaces();
2938 }
2939
Lorenzo Colitti18660282016-07-04 12:55:44 +09002940 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002941 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002942 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002943 return mTethering.getTetheredIfaces();
2944 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002945
Lorenzo Colitti18660282016-07-04 12:55:44 +09002946 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002947 public String[] getTetheringErroredIfaces() {
2948 enforceTetherAccessPermission();
2949 return mTethering.getErroredIfaces();
2950 }
2951
Lorenzo Colitti18660282016-07-04 12:55:44 +09002952 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002953 public String[] getTetheredDhcpRanges() {
2954 enforceConnectivityInternalPermission();
2955 return mTethering.getTetheredDhcpRanges();
2956 }
2957
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002958 // if ro.tether.denied = true we default to no tethering
2959 // gservices could set the secure setting to 1 though to enable it on a build where it
2960 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002961 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002962 public boolean isTetheringSupported() {
2963 enforceTetherAccessPermission();
2964 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002965 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002966 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2967 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002968 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2969 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002970 mTethering.getTetherableWifiRegexs().length != 0 ||
2971 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2972 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002973 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002974
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002975 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002976 public void startTethering(int type, ResultReceiver receiver,
2977 boolean showProvisioningUi) {
2978 ConnectivityManager.enforceTetherChangePermission(mContext);
2979 if (!isTetheringSupported()) {
2980 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2981 return;
2982 }
2983 mTethering.startTethering(type, receiver, showProvisioningUi);
2984 }
2985
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002986 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002987 public void stopTethering(int type) {
2988 ConnectivityManager.enforceTetherChangePermission(mContext);
2989 mTethering.stopTethering(type);
2990 }
2991
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002992 // Called when we lose the default network and have no replacement yet.
2993 // This will automatically be cleared after X seconds or a new default network
2994 // becomes CONNECTED, whichever happens first. The timer is started by the
2995 // first caller and not restarted by subsequent callers.
2996 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002997 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002998 synchronized (this) {
2999 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003000 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003001 mNetTransitionWakeLock.acquire();
3002 mNetTransitionWakeLockCausedBy = forWhom;
3003 }
3004 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003005 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003006 mNetTransitionWakeLockTimeout);
3007 return;
3008 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003009
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003010 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003011 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003012 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003013 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003014 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003015 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003016 }
3017
Lorenzo Colitti18660282016-07-04 12:55:44 +09003018 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003019 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003020 enforceAccessPermission();
3021 enforceInternetPermission();
3022
Paul Jensenbfd17b72015-04-07 12:43:13 -04003023 NetworkAgentInfo nai;
3024 if (network == null) {
3025 nai = getDefaultNetwork();
3026 } else {
3027 nai = getNetworkAgentInfoForNetwork(network);
3028 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003029 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3030 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3031 return;
3032 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003033 // Revalidate if the app report does not match our current validated state.
3034 if (hasConnectivity == nai.lastValidated) return;
3035 final int uid = Binder.getCallingUid();
3036 if (DBG) {
3037 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3038 ") by " + uid);
3039 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003040 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003041 // Validating a network that has not yet connected could result in a call to
3042 // rematchNetworkAndRequests() which is not meant to work on such networks.
3043 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003044
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003045 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003046
3047 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3048 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003049 }
3050
Paul Jensencee9b512015-05-06 07:32:40 -04003051 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003052 // this information is already available as a world read/writable jvm property
3053 // so this API change wouldn't have a benifit. It also breaks the passing
3054 // of proxy info to all the JVMs.
3055 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003056 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003057 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003058 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3059 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003060 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003061 }
3062
Lorenzo Colitti18660282016-07-04 12:55:44 +09003063 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003064 public ProxyInfo getProxyForNetwork(Network network) {
3065 if (network == null) return getDefaultProxy();
3066 final ProxyInfo globalProxy = getGlobalProxy();
3067 if (globalProxy != null) return globalProxy;
3068 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3069 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3070 // caller may not have.
3071 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3072 if (nai == null) return null;
3073 synchronized (nai) {
3074 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3075 if (proxyInfo == null) return null;
3076 return new ProxyInfo(proxyInfo);
3077 }
3078 }
3079
Paul Jensene0bef712014-12-10 15:12:18 -05003080 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3081 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3082 // proxy is null then there is no proxy in place).
3083 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3084 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3085 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3086 proxy = null;
3087 }
3088 return proxy;
3089 }
3090
3091 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3092 // better for determining if a new proxy broadcast is necessary:
3093 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3094 // avoid unnecessary broadcasts.
3095 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3096 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3097 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3098 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3099 // all set.
3100 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3101 a = canonicalizeProxyInfo(a);
3102 b = canonicalizeProxyInfo(b);
3103 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3104 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3105 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3106 }
3107
Jason Monk207900c2014-04-25 15:00:09 -04003108 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003109 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003110
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003111 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003112 if (proxyProperties == mGlobalProxy) return;
3113 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3114 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3115
3116 String host = "";
3117 int port = 0;
3118 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003119 String pacFileUrl = "";
3120 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003121 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003122 if (!proxyProperties.isValid()) {
3123 if (DBG)
3124 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3125 return;
3126 }
Jason Monk207900c2014-04-25 15:00:09 -04003127 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003128 host = mGlobalProxy.getHost();
3129 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003130 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003131 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003132 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003133 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003134 } else {
3135 mGlobalProxy = null;
3136 }
3137 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003138 final long token = Binder.clearCallingIdentity();
3139 try {
3140 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3141 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3142 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3143 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003144 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003145 } finally {
3146 Binder.restoreCallingIdentity(token);
3147 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003148
Jason Monkcf0f97a2014-10-02 15:39:38 -04003149 if (mGlobalProxy == null) {
3150 proxyProperties = mDefaultProxy;
3151 }
3152 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003153 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003154 }
3155
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003156 private void loadGlobalProxy() {
3157 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003158 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3159 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3160 String exclList = Settings.Global.getString(res,
3161 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003162 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3163 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003164 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003165 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003166 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003167 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003168 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003169 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003170 if (!proxyProperties.isValid()) {
3171 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3172 return;
3173 }
3174
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003175 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003176 mGlobalProxy = proxyProperties;
3177 }
3178 }
3179 }
3180
Jason Monk207900c2014-04-25 15:00:09 -04003181 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003182 // this information is already available as a world read/writable jvm property
3183 // so this API change wouldn't have a benifit. It also breaks the passing
3184 // of proxy info to all the JVMs.
3185 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003186 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003187 return mGlobalProxy;
3188 }
3189 }
3190
Jason Monk207900c2014-04-25 15:00:09 -04003191 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003192 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003193 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003194 proxy = null;
3195 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003196 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003197 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003198 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003199 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003200 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3201 return;
3202 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003203
3204 // This call could be coming from the PacManager, containing the port of the local
3205 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3206 // global (to get the correct local port), and send a broadcast.
3207 // TODO: Switch PacManager to have its own message to send back rather than
3208 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003209 if ((mGlobalProxy != null) && (proxy != null)
3210 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003211 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3212 mGlobalProxy = proxy;
3213 sendProxyBroadcast(mGlobalProxy);
3214 return;
3215 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003216 mDefaultProxy = proxy;
3217
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003218 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003219 if (!mDefaultProxyDisabled) {
3220 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003221 }
3222 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003223 }
3224
Paul Jensene0bef712014-12-10 15:12:18 -05003225 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3226 // This method gets called when any network changes proxy, but the broadcast only ever contains
3227 // the default proxy (even if it hasn't changed).
3228 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3229 // world where an app might be bound to a non-default network.
3230 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3231 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3232 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3233
3234 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3235 sendProxyBroadcast(getDefaultProxy());
3236 }
3237 }
3238
Robert Greenwalt434203a2010-10-11 16:00:27 -07003239 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003240 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3241 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003242 if (!TextUtils.isEmpty(proxy)) {
3243 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003244 if (data.length == 0) {
3245 return;
3246 }
3247
Robert Greenwalt434203a2010-10-11 16:00:27 -07003248 String proxyHost = data[0];
3249 int proxyPort = 8080;
3250 if (data.length > 1) {
3251 try {
3252 proxyPort = Integer.parseInt(data[1]);
3253 } catch (NumberFormatException e) {
3254 return;
3255 }
3256 }
Jason Monk207900c2014-04-25 15:00:09 -04003257 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003258 setGlobalProxy(p);
3259 }
3260 }
3261
Jason Monk207900c2014-04-25 15:00:09 -04003262 private void sendProxyBroadcast(ProxyInfo proxy) {
3263 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003264 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003265 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003266 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003267 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3268 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003269 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003270 final long ident = Binder.clearCallingIdentity();
3271 try {
3272 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3273 } finally {
3274 Binder.restoreCallingIdentity(ident);
3275 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003276 }
3277
3278 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003279 final private HashMap<Uri, Integer> mUriEventMap;
3280 final private Context mContext;
3281 final private Handler mHandler;
3282
3283 SettingsObserver(Context context, Handler handler) {
3284 super(null);
3285 mUriEventMap = new HashMap<Uri, Integer>();
3286 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003287 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003288 }
3289
Erik Klineda4bfa82015-04-30 12:58:40 +09003290 void observe(Uri uri, int what) {
3291 mUriEventMap.put(uri, what);
3292 final ContentResolver resolver = mContext.getContentResolver();
3293 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003294 }
3295
3296 @Override
3297 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003298 Slog.wtf(TAG, "Should never be reached.");
3299 }
3300
3301 @Override
3302 public void onChange(boolean selfChange, Uri uri) {
3303 final Integer what = mUriEventMap.get(uri);
3304 if (what != null) {
3305 mHandler.obtainMessage(what.intValue()).sendToTarget();
3306 } else {
3307 loge("No matching event to send for URI=" + uri);
3308 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003309 }
3310 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003311
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003312 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003313 Slog.d(TAG, s);
3314 }
3315
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003316 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003317 Slog.e(TAG, s);
3318 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003319
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003320 private static <T> T checkNotNull(T value, String message) {
3321 if (value == null) {
3322 throw new NullPointerException(message);
3323 }
3324 return value;
3325 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003326
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003327 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003328 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003329 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3330 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3331 *
3332 * @param oldPackage Package name of the application which currently controls VPN, which will
3333 * be replaced. If there is no such application, this should should either be
3334 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3335 * @param newPackage Package name of the application which should gain control of VPN, or
3336 * {@code null} to disable.
3337 * @param userId User for whom to prepare the new VPN.
3338 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003339 * @hide
3340 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003341 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003342 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3343 int userId) {
3344 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003345 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003346
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003347 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003348 Vpn vpn = mVpns.get(userId);
3349 if (vpn != null) {
3350 return vpn.prepare(oldPackage, newPackage);
3351 } else {
3352 return false;
3353 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003354 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003355 }
3356
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003357 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003358 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3359 * This method is used by system-privileged apps.
3360 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3361 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3362 *
3363 * @param packageName The package for which authorization state should change.
3364 * @param userId User for whom {@code packageName} is installed.
3365 * @param authorized {@code true} if this app should be able to start a VPN connection without
3366 * explicit user approval, {@code false} if not.
3367 *
Jeff Davidson05542602014-08-11 14:07:27 -07003368 * @hide
3369 */
3370 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003371 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3372 enforceCrossUserPermission(userId);
3373
Jeff Davidson05542602014-08-11 14:07:27 -07003374 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003375 Vpn vpn = mVpns.get(userId);
3376 if (vpn != null) {
3377 vpn.setPackageAuthorization(packageName, authorized);
3378 }
Jeff Davidson05542602014-08-11 14:07:27 -07003379 }
3380 }
3381
3382 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003383 * Configure a TUN interface and return its file descriptor. Parameters
3384 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003385 * and not available in ConnectivityManager. Permissions are checked in
3386 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003387 * @hide
3388 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003389 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003390 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003391 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003392 int user = UserHandle.getUserId(Binder.getCallingUid());
3393 synchronized(mVpns) {
3394 return mVpns.get(user).establish(config);
3395 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003396 }
3397
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003398 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003399 * Start legacy VPN, controlling native daemons as needed. Creates a
3400 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003401 */
3402 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003403 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003404 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003405 final LinkProperties egress = getActiveLinkProperties();
3406 if (egress == null) {
3407 throw new IllegalStateException("Missing active network connection");
3408 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003409 int user = UserHandle.getUserId(Binder.getCallingUid());
3410 synchronized(mVpns) {
3411 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3412 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003413 }
3414
3415 /**
3416 * Return the information of the ongoing legacy VPN. This method is used
3417 * by VpnSettings and not available in ConnectivityManager. Permissions
3418 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003419 */
3420 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003421 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3422 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003423
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003424 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003425 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003426 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003427 }
3428
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003429 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003430 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3431 * and not available in ConnectivityManager.
3432 */
3433 @Override
3434 public VpnInfo[] getAllVpnInfo() {
3435 enforceConnectivityInternalPermission();
3436 if (mLockdownEnabled) {
3437 return new VpnInfo[0];
3438 }
3439
3440 synchronized(mVpns) {
3441 List<VpnInfo> infoList = new ArrayList<>();
3442 for (int i = 0; i < mVpns.size(); i++) {
3443 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3444 if (info != null) {
3445 infoList.add(info);
3446 }
3447 }
3448 return infoList.toArray(new VpnInfo[infoList.size()]);
3449 }
3450 }
3451
3452 /**
3453 * @return VPN information for accounting, or null if we can't retrieve all required
3454 * information, e.g primary underlying iface.
3455 */
3456 @Nullable
3457 private VpnInfo createVpnInfo(Vpn vpn) {
3458 VpnInfo info = vpn.getVpnInfo();
3459 if (info == null) {
3460 return null;
3461 }
3462 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3463 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3464 // the underlyingNetworks list.
3465 if (underlyingNetworks == null) {
3466 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3467 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3468 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3469 }
3470 } else if (underlyingNetworks.length > 0) {
3471 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3472 if (linkProperties != null) {
3473 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3474 }
3475 }
3476 return info.primaryUnderlyingIface == null ? null : info;
3477 }
3478
3479 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003480 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3481 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003482 * Permissions are checked in Vpn class.
3483 * @hide
3484 */
3485 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003486 public VpnConfig getVpnConfig(int userId) {
3487 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003488 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003489 Vpn vpn = mVpns.get(userId);
3490 if (vpn != null) {
3491 return vpn.getVpnConfig();
3492 } else {
3493 return null;
3494 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003495 }
3496 }
3497
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003498 @Override
3499 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003500 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3501 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3502 return false;
3503 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003504
3505 // Tear down existing lockdown if profile was removed
3506 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3507 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003508 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3509 final VpnProfile profile = VpnProfile.decode(
3510 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003511 if (profile == null) {
3512 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3513 setLockdownTracker(null);
3514 return true;
3515 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003516 int user = UserHandle.getUserId(Binder.getCallingUid());
3517 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003518 Vpn vpn = mVpns.get(user);
3519 if (vpn == null) {
3520 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3521 return false;
3522 }
3523 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003524 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003525 } else {
3526 setLockdownTracker(null);
3527 }
3528
3529 return true;
3530 }
3531
3532 /**
3533 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3534 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3535 */
3536 private void setLockdownTracker(LockdownVpnTracker tracker) {
3537 // Shutdown any existing tracker
3538 final LockdownVpnTracker existing = mLockdownTracker;
3539 mLockdownTracker = null;
3540 if (existing != null) {
3541 existing.shutdown();
3542 }
3543
3544 try {
3545 if (tracker != null) {
3546 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003547 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003548 mLockdownTracker = tracker;
3549 mLockdownTracker.init();
3550 } else {
3551 mNetd.setFirewallEnabled(false);
3552 }
3553 } catch (RemoteException e) {
3554 // ignored; NMS lives inside system_server
3555 }
3556 }
3557
3558 private void throwIfLockdownEnabled() {
3559 if (mLockdownEnabled) {
3560 throw new IllegalStateException("Unavailable in lockdown mode");
3561 }
3562 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003563
Robin Lee244ce8e2016-01-05 18:03:46 +00003564 /**
Robin Lee17e61832016-05-09 13:46:28 +01003565 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3566 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003567 *
Robin Lee17e61832016-05-09 13:46:28 +01003568 * @return {@code true} if the service was started, the service was already connected, or there
3569 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003570 */
Robin Lee17e61832016-05-09 13:46:28 +01003571 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003572 synchronized (mVpns) {
3573 Vpn vpn = mVpns.get(userId);
3574 if (vpn == null) {
3575 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3576 // exists already.
3577 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3578 return false;
3579 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003580
Robin Lee812800c2016-05-13 15:38:08 +01003581 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003582 }
3583 }
3584
3585 @Override
Robin Leedc679712016-05-03 13:23:03 +01003586 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003587 enforceConnectivityInternalPermission();
3588 enforceCrossUserPermission(userId);
3589
3590 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3591 if (LockdownVpnTracker.isEnabled()) {
3592 return false;
3593 }
3594
Robin Lee244ce8e2016-01-05 18:03:46 +00003595 synchronized (mVpns) {
3596 Vpn vpn = mVpns.get(userId);
3597 if (vpn == null) {
3598 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3599 return false;
3600 }
Robin Lee17e61832016-05-09 13:46:28 +01003601 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003602 return false;
3603 }
Robin Lee17e61832016-05-09 13:46:28 +01003604 if (!startAlwaysOnVpn(userId)) {
3605 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003606 return false;
3607 }
Robin Lee17e61832016-05-09 13:46:28 +01003608
Robin Lee812800c2016-05-13 15:38:08 +01003609 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003610 }
3611 return true;
3612 }
3613
3614 @Override
3615 public String getAlwaysOnVpnPackage(int userId) {
3616 enforceConnectivityInternalPermission();
3617 enforceCrossUserPermission(userId);
3618
3619 synchronized (mVpns) {
3620 Vpn vpn = mVpns.get(userId);
3621 if (vpn == null) {
3622 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3623 return null;
3624 }
3625 return vpn.getAlwaysOnPackage();
3626 }
3627 }
3628
Wink Savilleab9321d2013-06-29 21:10:57 -07003629 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003630 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003631 // TODO: Remove? Any reason to trigger a provisioning check?
3632 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003633 }
3634
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003635 /** Location to an updatable file listing carrier provisioning urls.
3636 * An example:
3637 *
3638 * <?xml version="1.0" encoding="utf-8"?>
3639 * <provisioningUrls>
3640 * <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 -07003641 * </provisioningUrls>
3642 */
3643 private static final String PROVISIONING_URL_PATH =
3644 "/data/misc/radio/provisioning_urls.xml";
3645 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003646
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003647 /** XML tag for root element. */
3648 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3649 /** XML tag for individual url */
3650 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003651 /** XML attribute for mcc */
3652 private static final String ATTR_MCC = "mcc";
3653 /** XML attribute for mnc */
3654 private static final String ATTR_MNC = "mnc";
3655
Paul Jensen434dde82015-06-11 09:43:30 -04003656 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003657 FileReader fileReader = null;
3658 XmlPullParser parser = null;
3659 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003660
3661 try {
3662 fileReader = new FileReader(mProvisioningUrlFile);
3663 parser = Xml.newPullParser();
3664 parser.setInput(fileReader);
3665 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3666
3667 while (true) {
3668 XmlUtils.nextElement(parser);
3669
3670 String element = parser.getName();
3671 if (element == null) break;
3672
Paul Jensen434dde82015-06-11 09:43:30 -04003673 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003674 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3675 try {
3676 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3677 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3678 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3679 parser.next();
3680 if (parser.getEventType() == XmlPullParser.TEXT) {
3681 return parser.getText();
3682 }
3683 }
3684 }
3685 } catch (NumberFormatException e) {
3686 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3687 }
3688 }
3689 }
3690 return null;
3691 } catch (FileNotFoundException e) {
3692 loge("Carrier Provisioning Urls file not found");
3693 } catch (XmlPullParserException e) {
3694 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3695 } catch (IOException e) {
3696 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3697 } finally {
3698 if (fileReader != null) {
3699 try {
3700 fileReader.close();
3701 } catch (IOException e) {}
3702 }
3703 }
3704 return null;
3705 }
3706
Wink Saville42d4f082013-07-20 20:31:59 -07003707 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003708 public String getMobileProvisioningUrl() {
3709 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003710 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003711 if (TextUtils.isEmpty(url)) {
3712 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003713 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003714 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003715 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003716 }
Wink Saville8cf35602013-07-10 23:00:07 -07003717 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003718 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003719 String phoneNumber = mTelephonyManager.getLine1Number();
3720 if (TextUtils.isEmpty(phoneNumber)) {
3721 phoneNumber = "0000000000";
3722 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003723 url = String.format(url,
3724 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3725 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003726 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003727 }
3728
Wink Savilleab9321d2013-06-29 21:10:57 -07003729 return url;
3730 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003731
Wink Saville948282b2013-08-29 08:55:16 -07003732 @Override
3733 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003734 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003735 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003736 final long ident = Binder.clearCallingIdentity();
3737 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003738 // Concatenate the range of types onto the range of NetIDs.
3739 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3740 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003741 } finally {
3742 Binder.restoreCallingIdentity(ident);
3743 }
Wink Saville948282b2013-08-29 08:55:16 -07003744 }
Wink Saville7788c612013-08-29 14:57:08 -07003745
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003746 @Override
3747 public void setAirplaneMode(boolean enable) {
3748 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003749 final long ident = Binder.clearCallingIdentity();
3750 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003751 final ContentResolver cr = mContext.getContentResolver();
3752 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3753 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3754 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003755 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003756 } finally {
3757 Binder.restoreCallingIdentity(ident);
3758 }
3759 }
3760
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003761 private void onUserStart(int userId) {
3762 synchronized(mVpns) {
3763 Vpn userVpn = mVpns.get(userId);
3764 if (userVpn != null) {
3765 loge("Starting user already has a VPN");
3766 return;
3767 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003768 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003769 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003770
3771 final ContentResolver cr = mContext.getContentResolver();
3772 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3773 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3774 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3775 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3776 if (alwaysOnPackage != null) {
3777 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3778 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003779 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003780 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3781 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003782 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003783 }
3784
3785 private void onUserStop(int userId) {
3786 synchronized(mVpns) {
3787 Vpn userVpn = mVpns.get(userId);
3788 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003789 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003790 return;
3791 }
Robin Lee17e61832016-05-09 13:46:28 +01003792 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003793 mVpns.delete(userId);
3794 }
3795 }
3796
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003797 private void onUserAdded(int userId) {
3798 synchronized(mVpns) {
3799 final int vpnsSize = mVpns.size();
3800 for (int i = 0; i < vpnsSize; i++) {
3801 Vpn vpn = mVpns.valueAt(i);
3802 vpn.onUserAdded(userId);
3803 }
3804 }
3805 }
3806
3807 private void onUserRemoved(int userId) {
3808 synchronized(mVpns) {
3809 final int vpnsSize = mVpns.size();
3810 for (int i = 0; i < vpnsSize; i++) {
3811 Vpn vpn = mVpns.valueAt(i);
3812 vpn.onUserRemoved(userId);
3813 }
3814 }
3815 }
3816
Robin Lee89e7a692016-02-29 14:38:17 +00003817 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003818 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3819 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3820 updateLockdownVpn();
3821 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003822 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003823 }
3824 }
3825
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003826 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3827 @Override
3828 public void onReceive(Context context, Intent intent) {
3829 final String action = intent.getAction();
3830 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3831 if (userId == UserHandle.USER_NULL) return;
3832
Robin Lee323f29d2016-05-04 16:38:06 +01003833 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003834 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003835 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003836 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003837 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3838 onUserAdded(userId);
3839 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3840 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003841 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3842 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003843 }
3844 }
3845 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003846
Robert Greenwalta67be032014-05-16 15:49:14 -07003847 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3848 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003849 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3850 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003851
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003852 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3853 // Map from UID to number of NetworkRequests that UID has filed.
3854 @GuardedBy("mUidToNetworkRequestCount")
3855 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3856
Robert Greenwalta67be032014-05-16 15:49:14 -07003857 private static class NetworkFactoryInfo {
3858 public final String name;
3859 public final Messenger messenger;
3860 public final AsyncChannel asyncChannel;
3861
3862 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3863 this.name = name;
3864 this.messenger = messenger;
3865 this.asyncChannel = asyncChannel;
3866 }
3867 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003868
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003869 private void ensureNetworkRequestHasType(NetworkRequest request) {
3870 if (request.type == NetworkRequest.Type.NONE) {
3871 throw new IllegalArgumentException(
3872 "All NetworkRequests in ConnectivityService must have a type");
3873 }
3874 }
3875
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003876 /**
3877 * Tracks info about the requester.
3878 * Also used to notice when the calling process dies so we can self-expire
3879 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003880 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003881 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003882 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003883 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003884 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003885 final int mPid;
3886 final int mUid;
3887 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003888
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003889 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003890 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003891 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003892 mPendingIntent = pi;
3893 messenger = null;
3894 mBinder = null;
3895 mPid = getCallingPid();
3896 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003897 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003898 }
3899
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003900 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003901 super();
3902 messenger = m;
3903 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003904 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003905 mBinder = binder;
3906 mPid = getCallingPid();
3907 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003908 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003909 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003910
3911 try {
3912 mBinder.linkToDeath(this, 0);
3913 } catch (RemoteException e) {
3914 binderDied();
3915 }
3916 }
3917
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003918 private void enforceRequestCountLimit() {
3919 synchronized (mUidToNetworkRequestCount) {
3920 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3921 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3922 throw new IllegalArgumentException("Too many NetworkRequests filed");
3923 }
3924 mUidToNetworkRequestCount.put(mUid, networkRequests);
3925 }
3926 }
3927
Robert Greenwalt9258c642014-03-26 16:47:06 -07003928 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003929 if (mBinder != null) {
3930 mBinder.unlinkToDeath(this, 0);
3931 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003932 }
3933
3934 public void binderDied() {
3935 log("ConnectivityService NetworkRequestInfo binderDied(" +
3936 request + ", " + mBinder + ")");
3937 releaseNetworkRequest(request);
3938 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003939
3940 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003941 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003942 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003943 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003944 }
3945
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003946 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3947 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3948 if (badCapability != null) {
3949 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003950 }
3951 }
3952
Erik Kline9d598e12015-07-13 16:37:51 +09003953 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003954 final SortedSet<Integer> thresholds = new TreeSet();
3955 synchronized (nai) {
3956 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3957 if (nri.request.networkCapabilities.hasSignalStrength() &&
3958 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3959 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3960 }
3961 }
3962 }
Erik Kline9d598e12015-07-13 16:37:51 +09003963 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003964 }
3965
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003966 private void updateSignalStrengthThresholds(
3967 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3968 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003969 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003970 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3971
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003972 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003973 String detail;
3974 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3975 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3976 } else {
3977 detail = reason;
3978 }
3979 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3980 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3981 }
3982
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003983 nai.asyncChannel.sendMessage(
3984 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003985 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003986 }
3987
Robert Greenwalt9258c642014-03-26 16:47:06 -07003988 @Override
3989 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003990 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003991 final NetworkRequest.Type type = (networkCapabilities == null)
3992 ? NetworkRequest.Type.TRACK_DEFAULT
3993 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003994 // If the requested networkCapabilities is null, take them instead from
3995 // the default network request. This allows callers to keep track of
3996 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003997 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003998 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3999 enforceAccessPermission();
4000 } else {
4001 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4002 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004003 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4004 // of the app when the request is filed, but we never change the request if the app
4005 // changes network state. http://b/29964605
4006 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004007 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004008 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004009
Robert Greenwalt6078b502014-06-11 16:05:07 -07004010 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004011 throw new IllegalArgumentException("Bad timeout specified");
4012 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004013
Etan Cohenddb9ef02015-11-18 10:56:15 -08004014 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4015 .equals(networkCapabilities.getNetworkSpecifier())) {
4016 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4017 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4018 }
4019
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004020 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004021 nextNetworkRequestId(), type);
4022 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004023 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004024
4025 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004026 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004027 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004028 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004029 }
4030 return networkRequest;
4031 }
4032
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004033 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004034 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004035 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004036 } else {
4037 enforceChangePermission();
4038 }
4039 }
4040
fenglub15e72b2015-03-20 11:29:56 -07004041 @Override
fengludb571472015-04-21 17:12:05 -07004042 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004043 enforceAccessPermission();
4044 NetworkAgentInfo nai = null;
4045 if (network == null) {
4046 return false;
4047 }
4048 synchronized (mNetworkForNetId) {
4049 nai = mNetworkForNetId.get(network.netId);
4050 }
4051 if (nai != null) {
4052 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4053 return true;
4054 }
4055 return false;
4056 }
4057
Felipe Lemeee27cab2016-06-20 16:36:29 -07004058 private boolean isSystem(int uid) {
4059 return uid < Process.FIRST_APPLICATION_UID;
4060 }
fenglub15e72b2015-03-20 11:29:56 -07004061
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004062 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004063 final int uid = Binder.getCallingUid();
4064 if (isSystem(uid)) {
4065 return;
4066 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004067 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004068 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004069 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004070 synchronized(mRulesLock) {
4071 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4072 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004073 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4074 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004075 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004076 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004077 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004078 }
4079 }
4080 }
4081
Robert Greenwalt9258c642014-03-26 16:47:06 -07004082 @Override
4083 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4084 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004085 checkNotNull(operation, "PendingIntent cannot be null.");
4086 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4087 enforceNetworkRequestPermissions(networkCapabilities);
4088 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004089 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004090
4091 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004092 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4093 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004094 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004095 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4096 nri));
4097 return networkRequest;
4098 }
4099
Jeremy Joslin79294842014-12-03 17:15:28 -08004100 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4101 mHandler.sendMessageDelayed(
4102 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4103 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4104 }
4105
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004106 @Override
4107 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004108 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004109 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4110 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004111 }
4112
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004113 // In order to implement the compatibility measure for pre-M apps that call
4114 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4115 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4116 // This ensures it has permission to do so.
4117 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4118 if (nc == null) {
4119 return false;
4120 }
4121 int[] transportTypes = nc.getTransportTypes();
4122 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4123 return false;
4124 }
4125 try {
4126 mContext.enforceCallingOrSelfPermission(
4127 android.Manifest.permission.ACCESS_WIFI_STATE,
4128 "ConnectivityService");
4129 } catch (SecurityException e) {
4130 return false;
4131 }
4132 return true;
4133 }
4134
Robert Greenwalt9258c642014-03-26 16:47:06 -07004135 @Override
4136 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4137 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004138 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4139 enforceAccessPermission();
4140 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004141
Erik Kline7523eb32015-07-09 18:24:03 +09004142 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004143 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4144 NetworkRequest.Type.LISTEN);
4145 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004146 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004147
4148 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4149 return networkRequest;
4150 }
4151
4152 @Override
4153 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4154 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004155 checkNotNull(operation, "PendingIntent cannot be null.");
4156 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4157 enforceAccessPermission();
4158 }
4159
Erik Kline7523eb32015-07-09 18:24:03 +09004160 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004161 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4162 NetworkRequest.Type.LISTEN);
4163 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004164 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004165
4166 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004167 }
4168
4169 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004170 public void requestLinkProperties(NetworkRequest networkRequest) {
4171 ensureNetworkRequestHasType(networkRequest);
4172 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4173 mHandler.sendMessage(mHandler.obtainMessage(
4174 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4175 }
4176
4177 @Override
4178 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4179 ensureNetworkRequestHasType(networkRequest);
4180 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4181 mHandler.sendMessage(mHandler.obtainMessage(
4182 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4183 }
4184
4185 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004186 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004187 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004188 mHandler.sendMessage(mHandler.obtainMessage(
4189 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004190 }
4191
4192 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004193 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004194 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004195 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4196 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004197 }
4198
Robert Greenwalta67be032014-05-16 15:49:14 -07004199 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004200 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004201 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4202 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4203 }
4204
4205 @Override
4206 public void unregisterNetworkFactory(Messenger messenger) {
4207 enforceConnectivityInternalPermission();
4208 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4209 }
4210
4211 private void handleUnregisterNetworkFactory(Messenger messenger) {
4212 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4213 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004214 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004215 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004216 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004217 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004218 }
4219
Robert Greenwalt7b816022014-04-18 15:25:25 -07004220 /**
4221 * NetworkAgentInfo supporting a request by requestId.
4222 * These have already been vetted (their Capabilities satisfy the request)
4223 * and the are the highest scored network available.
4224 * the are keyed off the Requests requestId.
4225 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004226 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004227 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4228 new SparseArray<NetworkAgentInfo>();
4229
Paul Jensen31a94f42015-02-13 14:18:39 -05004230 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4231 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004232 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4233 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004234 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4235 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4236 // there may not be a strict 1:1 correlation between the two.
4237 @GuardedBy("mNetworkForNetId")
4238 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004239
Robert Greenwalt7b816022014-04-18 15:25:25 -07004240 // NetworkAgentInfo keyed off its connecting messenger
4241 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004242 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004243 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4244 new HashMap<Messenger, NetworkAgentInfo>();
4245
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004246 @GuardedBy("mBlockedAppUids")
4247 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4248
Paul Jensen2c311d62014-11-17 12:34:51 -05004249 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004250 private final NetworkRequest mDefaultRequest;
4251
Erik Klineda4bfa82015-04-30 12:58:40 +09004252 // Request used to optionally keep mobile data active even when higher
4253 // priority networks like Wi-Fi are active.
4254 private final NetworkRequest mDefaultMobileDataRequest;
4255
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004256 private NetworkAgentInfo getDefaultNetwork() {
4257 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4258 }
4259
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004260 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004261 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004262 }
4263
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004264 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4265 return nri.request.requestId == mDefaultRequest.requestId;
4266 }
4267
Paul Jensen31a94f42015-02-13 14:18:39 -05004268 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004269 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004270 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004271 enforceConnectivityInternalPermission();
4272
Paul Jensen2c311d62014-11-17 12:34:51 -05004273 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4274 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004275 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004276 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4277 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004278 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004279 synchronized (this) {
4280 nai.networkMonitor.systemReady = mSystemReady;
4281 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004282 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4283 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004284 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004285 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004286 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004287 }
4288
4289 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4290 if (VDBG) log("Got NetworkAgent Messenger");
4291 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004292 synchronized (mNetworkForNetId) {
4293 mNetworkForNetId.put(na.network.netId, na);
4294 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004295 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4296 NetworkInfo networkInfo = na.networkInfo;
4297 na.networkInfo = null;
4298 updateNetworkInfo(na, networkInfo);
4299 }
4300
4301 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4302 LinkProperties newLp = networkAgent.linkProperties;
4303 int netId = networkAgent.network.netId;
4304
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004305 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4306 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004307 if (networkAgent.clatd != null) {
4308 networkAgent.clatd.fixupLinkProperties(oldLp);
4309 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004310
Paul Jensen992f2522014-04-28 10:33:11 -04004311 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004312 updateMtu(newLp, oldLp);
4313 // TODO - figure out what to do for clat
4314// for (LinkProperties lp : newLp.getStackedLinks()) {
4315// updateMtu(lp, null);
4316// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004317 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004318
Erik Kline94887872016-04-05 13:30:49 +09004319 updateRoutes(newLp, oldLp, netId);
4320 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004321
Paul Jensen3b759822014-05-13 11:44:01 -04004322 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004323 if (isDefaultNetwork(networkAgent)) {
4324 handleApplyDefaultProxy(newLp.getHttpProxy());
4325 } else {
4326 updateProxy(newLp, oldLp, networkAgent);
4327 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004328 // TODO - move this check to cover the whole function
4329 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004330 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004331 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4332 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004333
4334 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004335 }
4336
Lorenzo Colitti95439462014-10-09 13:44:48 +09004337 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4338 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4339 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004340
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004341 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004342 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4343 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004344 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004345 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004346 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004347 }
Paul Jensen992f2522014-04-28 10:33:11 -04004348
4349 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4350 CompareResult<String> interfaceDiff = new CompareResult<String>();
4351 if (oldLp != null) {
4352 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4353 } else if (newLp != null) {
4354 interfaceDiff.added = newLp.getAllInterfaceNames();
4355 }
4356 for (String iface : interfaceDiff.added) {
4357 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004358 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004359 mNetd.addInterfaceToNetwork(iface, netId);
4360 } catch (Exception e) {
4361 loge("Exception adding interface: " + e);
4362 }
4363 }
4364 for (String iface : interfaceDiff.removed) {
4365 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004366 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004367 mNetd.removeInterfaceFromNetwork(iface, netId);
4368 } catch (Exception e) {
4369 loge("Exception removing interface: " + e);
4370 }
4371 }
4372 }
4373
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004374 /**
4375 * Have netd update routes from oldLp to newLp.
4376 * @return true if routes changed between oldLp and newLp
4377 */
4378 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004379 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4380 if (oldLp != null) {
4381 routeDiff = oldLp.compareAllRoutes(newLp);
4382 } else if (newLp != null) {
4383 routeDiff.added = newLp.getAllRoutes();
4384 }
4385
4386 // add routes before removing old in case it helps with continuous connectivity
4387
4388 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4389 for (RouteInfo route : routeDiff.added) {
4390 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004391 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004392 try {
4393 mNetd.addRoute(netId, route);
4394 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004395 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4396 loge("Exception in addRoute for non-gateway: " + e);
4397 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004398 }
4399 }
4400 for (RouteInfo route : routeDiff.added) {
4401 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004402 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004403 try {
4404 mNetd.addRoute(netId, route);
4405 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004406 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4407 loge("Exception in addRoute for gateway: " + e);
4408 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004409 }
4410 }
4411
4412 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004413 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004414 try {
4415 mNetd.removeRoute(netId, route);
4416 } catch (Exception e) {
4417 loge("Exception in removeRoute: " + e);
4418 }
4419 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004420 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004421 }
Erik Kline41368502015-06-17 13:19:54 +09004422
Erik Kline94887872016-04-05 13:30:49 +09004423 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4424 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4425 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004426 }
Erik Kline94887872016-04-05 13:30:49 +09004427
4428 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004429 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004430 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004431 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004432 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4433 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004434 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004435 }
4436 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4437 if (defaultNai != null && defaultNai.network.netId == netId) {
4438 setDefaultDnsSystemProperties(dnses);
4439 }
4440 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004441 }
4442
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004443 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4444 int last = 0;
4445 for (InetAddress dns : dnses) {
4446 ++last;
4447 String key = "net.dns" + last;
4448 String value = dns.getHostAddress();
4449 SystemProperties.set(key, value);
4450 }
4451 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4452 String key = "net.dns" + i;
4453 SystemProperties.set(key, "");
4454 }
4455 mNumDnsEntries = last;
4456 }
4457
Paul Jensen3d194ea2015-06-16 14:27:36 -04004458 /**
4459 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4460 * augmented with any stateful capabilities implied from {@code networkAgent}
4461 * (e.g., validated status and captive portal status).
4462 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004463 * @param oldScore score of the network before any of the changes that prompted us
4464 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004465 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004466 * @param networkCapabilities the new network capabilities.
4467 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004468 private void updateCapabilities(
4469 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004470 // Don't modify caller's NetworkCapabilities.
4471 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004472 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004473 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4474 } else {
4475 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4476 }
Paul Jensene0988542015-06-25 15:30:08 -04004477 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004478 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4479 } else {
4480 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4481 }
Paul Jensene0988542015-06-25 15:30:08 -04004482 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
Paul Jensen487ffe72015-07-24 15:57:11 -04004483 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4484 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4485 try {
4486 mNetd.setNetworkPermission(nai.network.netId,
4487 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4488 null : NetworkManagementService.PERMISSION_SYSTEM);
4489 } catch (RemoteException e) {
4490 loge("Exception in setNetworkPermission: " + e);
4491 }
4492 }
Paul Jensene0988542015-06-25 15:30:08 -04004493 synchronized (nai) {
4494 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004495 }
Paul Jensene0988542015-06-25 15:30:08 -04004496 rematchAllNetworksAndRequests(nai, oldScore);
4497 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004498 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004499 }
4500
Paul Jensenc8b9a742014-09-30 15:37:41 -04004501 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004502 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4503 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004504 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004505 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004506 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4507 }
4508 }
4509
Robert Greenwalt7b816022014-04-18 15:25:25 -07004510 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4511 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004512 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004513 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4514 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004515 }
4516 }
4517
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004518 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4519 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004520 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004521 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004522 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4523 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004524 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004525 sendIntent(nri.mPendingIntent, intent);
4526 }
4527 // else not handled
4528 }
4529
4530 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4531 mPendingIntentWakeLock.acquire();
4532 try {
4533 if (DBG) log("Sending " + pendingIntent);
4534 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4535 } catch (PendingIntent.CanceledException e) {
4536 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4537 mPendingIntentWakeLock.release();
4538 releasePendingNetworkRequest(pendingIntent);
4539 }
4540 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4541 }
4542
4543 @Override
4544 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4545 String resultData, Bundle resultExtras) {
4546 if (DBG) log("Finished sending " + pendingIntent);
4547 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004548 // Release with a delay so the receiving client has an opportunity to put in its
4549 // own request.
4550 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004551 }
4552
Robert Greenwalt9258c642014-03-26 16:47:06 -07004553 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004554 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004555 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004556 Bundle bundle = new Bundle();
4557 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4558 new NetworkRequest(nri.request));
4559 Message msg = Message.obtain();
4560 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4561 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4562 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4563 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004564 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004565 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004566 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004567 break;
4568 }
4569 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4570 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4571 new NetworkCapabilities(networkAgent.networkCapabilities));
4572 break;
4573 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004574 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004575 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4576 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004577 break;
4578 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004579 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004580 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004581 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004582 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004583 if (VDBG) {
4584 log("sending notification " + notifyTypeToName(notificationType) +
4585 " for " + nri.request);
4586 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004587 nri.messenger.send(msg);
4588 } catch (RemoteException e) {
4589 // may occur naturally in the race of binder death.
4590 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4591 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004592 }
4593
Paul Jensenc8b9a742014-09-30 15:37:41 -04004594 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004595 if (nai.numRequestNetworkRequests() != 0) {
4596 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4597 NetworkRequest nr = nai.requestAt(i);
4598 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004599 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004600 loge("Dead network still had at least " + nr);
4601 break;
4602 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004603 }
4604 nai.asyncChannel.disconnect();
4605 }
4606
Robert Greenwalt7b816022014-04-18 15:25:25 -07004607 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4608 if (oldNetwork == null) {
4609 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4610 return;
4611 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004612 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004613
4614 // If we get here it means that the last linger timeout for this network expired. So there
4615 // must be no other active linger timers, and we must stop lingering.
4616 oldNetwork.clearLingerState();
4617
4618 if (unneeded(oldNetwork)) {
4619 teardownUnneededNetwork(oldNetwork);
4620 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004621 }
4622
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004623 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004624 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004625 setupDataActivityTracking(newNetwork);
4626 try {
4627 mNetd.setDefaultNetId(newNetwork.network.netId);
4628 } catch (Exception e) {
4629 loge("Exception setting default network :" + e);
4630 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004631 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004632 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004633 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004634 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004635 }
4636
Paul Jensen2161a8e2014-09-11 11:00:39 -04004637 // Handles a network appearing or improving its score.
4638 //
4639 // - Evaluates all current NetworkRequests that can be
4640 // satisfied by newNetwork, and reassigns to newNetwork
4641 // any such requests for which newNetwork is the best.
4642 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004643 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004644 // needed. A network is needed if it is the best network for
4645 // one or more NetworkRequests, or if it is a VPN.
4646 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004647 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004648 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004649 //
4650 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4651 // networks that have no chance (i.e. even if validated)
4652 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004653 //
4654 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4655 // it does not remove NetworkRequests that other Networks could better satisfy.
4656 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4657 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4658 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004659 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004660 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004661 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4662 // performed to tear down unvalidated networks that have no chance (i.e. even if
4663 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004664 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004665 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004666 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004667 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004668 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004669 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004670 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004671 // Find and migrate to this Network any NetworkRequests for
4672 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004673 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004674 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004675 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004676 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004677 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4678 final boolean satisfies = newNetwork.satisfies(nri.request);
4679 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004680 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004681 log("Network " + newNetwork.name() + " was already satisfying" +
4682 " request " + nri.request.requestId + ". No change.");
4683 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004684 keep = true;
4685 continue;
4686 }
4687
4688 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004689 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004690 if (satisfies) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004691 if (nri.request.isListen()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004692 // This is not a request, it's a callback listener.
4693 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004694 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004695 continue;
4696 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004697
Robert Greenwalt7b816022014-04-18 15:25:25 -07004698 // next check if it's better than any current network we're using for
4699 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004700 if (VDBG) {
4701 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004702 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4703 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004704 }
4705 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004706 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004707 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004708 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004709 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004710 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004711 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004712 affectedNetworks.add(currentNetwork);
4713 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004714 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004715 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004716 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004717 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004718 if (!newNetwork.addRequest(nri.request)) {
4719 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4720 }
4721 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004722 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004723 // Tell NetworkFactories about the new score, so they can stop
4724 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004725 // TODO - this could get expensive if we have alot of requests for this
4726 // network. Think about if there is a way to reduce this. Push
4727 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004728 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004729 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004730 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004731 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004732 if (currentNetwork != null) {
4733 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4734 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004735 }
4736 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004737 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004738 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4739 // mark it as no longer satisfying "nri". Because networks are processed by
4740 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4741 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4742 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4743 // This means this code doesn't have to handle the case where "currentNetwork" no
4744 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4745 if (DBG) {
4746 log("Network " + newNetwork.name() + " stopped satisfying" +
4747 " request " + nri.request.requestId);
4748 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004749 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004750 if (currentNetwork == newNetwork) {
4751 mNetworkForRequestId.remove(nri.request.requestId);
4752 sendUpdatedScoreToFactories(nri.request, 0);
4753 } else {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004754 if (nri.request.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004755 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4756 newNetwork.name() +
4757 " without updating mNetworkForRequestId or factories!");
4758 }
4759 }
4760 // TODO: technically, sending CALLBACK_LOST here is
4761 // incorrect if nri is a request (not a listen) and there
4762 // is a replacement network currently connected that can
4763 // satisfy it. However, the only capability that can both
4764 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4765 // so this code is only incorrect for a network that loses
4766 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004767 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004768 }
4769 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004770 if (isNewDefault) {
4771 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004772 makeDefault(newNetwork);
4773 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4774 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004775 synchronized (ConnectivityService.this) {
4776 // have a new default network, release the transition wakelock in
4777 // a second if it's held. The second pause is to allow apps
4778 // to reconnect over the new network
4779 if (mNetTransitionWakeLock.isHeld()) {
4780 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4781 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4782 mNetTransitionWakeLockSerialNumber, 0),
4783 1000);
4784 }
4785 }
4786 }
4787
4788 // do this after the default net is switched, but
4789 // before LegacyTypeTracker sends legacy broadcasts
4790 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4791
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004792 // Linger any networks that are no longer needed. This should be done after sending the
4793 // available callback for newNetwork.
4794 for (NetworkAgentInfo nai : affectedNetworks) {
4795 updateLingerState(nai, now);
4796 }
4797 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4798 // does not need to be done in any particular order.
4799 updateLingerState(newNetwork, now);
4800
Paul Jensencf4c2c62015-07-01 14:16:32 -04004801 if (isNewDefault) {
4802 // Maintain the illusion: since the legacy API only
4803 // understands one network at a time, we must pretend
4804 // that the current default network disconnected before
4805 // the new one connected.
4806 if (oldDefaultNetwork != null) {
4807 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4808 oldDefaultNetwork, true);
4809 }
4810 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4811 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4812 notifyLockdownVpn(newNetwork);
4813 }
4814
Robert Greenwalt7b816022014-04-18 15:25:25 -07004815 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004816 // Notify battery stats service about this network, both the normal
4817 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004818 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004819 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004820 final IBatteryStats bs = BatteryStatsService.getService();
4821 final int type = newNetwork.networkInfo.getType();
4822
4823 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4824 bs.noteNetworkInterfaceType(baseIface, type);
4825 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4826 final String stackedIface = stacked.getInterfaceName();
4827 bs.noteNetworkInterfaceType(stackedIface, type);
4828 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4829 }
4830 } catch (RemoteException ignored) {
4831 }
4832
Robert Greenwalt152ed372014-12-17 17:19:53 -08004833 // This has to happen after the notifyNetworkCallbacks as that tickles each
4834 // ConnectivityManager instance so that legacy requests correctly bind dns
4835 // requests to this network. The legacy users are listening for this bcast
4836 // and will generally do a dns request so they can ensureRouteToHost and if
4837 // they do that before the callbacks happen they'll use the default network.
4838 //
4839 // TODO: Is there still a race here? We send the broadcast
4840 // after sending the callback, but if the app can receive the
4841 // broadcast before the callback, it might still break.
4842 //
4843 // This *does* introduce a race where if the user uses the new api
4844 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4845 // they may get old info. Reverse this after the old startUsing api is removed.
4846 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004847 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4848 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004849 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004850 // legacy type tracker filters out repeat adds
4851 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4852 }
4853 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004854
4855 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4856 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4857 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4858 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4859 if (newNetwork.isVPN()) {
4860 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4861 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004862 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004863 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4864 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004865 if (unneeded(nai)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004866 if (nai.getLingerExpiry() > 0) {
4867 // This network has active linger timers and no requests, but is not
4868 // lingering. Linger it.
4869 //
4870 // One way (the only way?) this can happen if this network is unvalidated
4871 // and became unneeded due to another network improving its score to the
4872 // point where this network will no longer be able to satisfy any requests
4873 // even if it validates.
4874 updateLingerState(nai, now);
4875 } else {
4876 if (DBG) log("Reaping " + nai.name());
4877 teardownUnneededNetwork(nai);
4878 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004879 }
4880 }
4881 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004882 }
4883
Paul Jensen1c7ba022015-06-16 14:27:36 -04004884 /**
4885 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4886 * being disconnected.
4887 * @param changed If only one Network's score or capabilities have been modified since the last
4888 * time this function was called, pass this Network in this argument, otherwise pass
4889 * null.
4890 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4891 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4892 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4893 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4894 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004895 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004896 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004897 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4898 // to avoid the slowness. It is not simply enough to process just "changed", for
4899 // example in the case where "changed"'s score decreases and another network should begin
4900 // satifying a NetworkRequest that "changed" currently satisfies.
4901
4902 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4903 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4904 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004905 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04004906 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004907 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004908 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004909 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4910 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4911 // Rematch higher scoring networks first to prevent requests first matching a lower
4912 // scoring network and then a higher scoring network, which could produce multiple
4913 // callbacks and inadvertently unlinger networks.
4914 Arrays.sort(nais);
4915 for (NetworkAgentInfo nai : nais) {
4916 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004917 // Only reap the last time through the loop. Reaping before all rematching
4918 // is complete could incorrectly teardown a network that hasn't yet been
4919 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004920 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004921 : ReapUnvalidatedNetworks.REAP,
4922 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004923 }
4924 }
4925 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004926
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004927 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004928 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004929 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004930 // For now only update icons for default connection.
4931 // TODO: Update WiFi and cellular icons separately. b/17237507
4932 if (!isDefaultNetwork(nai)) return;
4933
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004934 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004935 // Don't repeat publish.
4936 if (newInetCondition == mDefaultInetConditionPublished) return;
4937
4938 mDefaultInetConditionPublished = newInetCondition;
4939 sendInetConditionBroadcast(nai.networkInfo);
4940 }
4941
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004942 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4943 if (mLockdownTracker != null) {
4944 if (nai != null && nai.isVPN()) {
4945 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4946 } else {
4947 mLockdownTracker.onNetworkInfoChanged();
4948 }
4949 }
4950 }
4951
Robert Greenwalt7b816022014-04-18 15:25:25 -07004952 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4953 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004954 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004955 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004956 synchronized (networkAgent) {
4957 oldInfo = networkAgent.networkInfo;
4958 networkAgent.networkInfo = newInfo;
4959 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004960 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004961
4962 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004963 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4964 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4965 notifyIfacesChangedForNetworkStats();
4966 } else if (VDBG) log("ignoring duplicate network state non-change");
4967 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004968 return;
4969 }
4970 if (DBG) {
4971 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4972 (oldInfo == null ? "null" : oldInfo.getState()) +
4973 " to " + state);
4974 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004975
Robin Lee585e2482016-05-01 23:00:00 +01004976 if (!networkAgent.created
4977 && (state == NetworkInfo.State.CONNECTED
4978 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004979 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004980 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004981 if (networkAgent.isVPN()) {
4982 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004983 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4984 (networkAgent.networkMisc == null ||
4985 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004986 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004987 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4988 networkAgent.networkCapabilities.hasCapability(
4989 NET_CAPABILITY_NOT_RESTRICTED) ?
4990 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004991 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004992 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004993 loge("Error creating network " + networkAgent.network.netId + ": "
4994 + e.getMessage());
4995 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004996 }
Paul Jenseneec75412014-08-04 12:21:19 -04004997 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004998 }
4999
5000 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5001 networkAgent.everConnected = true;
5002
Robert Greenwalt7b816022014-04-18 15:25:25 -07005003 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005004 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005005
Paul Jensenca8f16a2014-05-09 12:47:55 -04005006 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005007 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005008
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005009 if (networkAgent.isVPN()) {
5010 // Temporarily disable the default proxy (not global).
5011 synchronized (mProxyLock) {
5012 if (!mDefaultProxyDisabled) {
5013 mDefaultProxyDisabled = true;
5014 if (mGlobalProxy == null && mDefaultProxy != null) {
5015 sendProxyBroadcast(null);
5016 }
5017 }
5018 }
5019 // TODO: support proxy per network.
5020 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005021
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005022 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5023 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5024 // capabilities, so it only needs to be done once on initial connect, not every time the
5025 // network's capabilities change. Note that we do this before rematching the network,
5026 // so we could decide to tear it down immediately afterwards. That's fine though - on
5027 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5028 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005029 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005030
Paul Jensen2161a8e2014-09-11 11:00:39 -04005031 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005032 final long now = SystemClock.elapsedRealtime();
5033 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005034
5035 // This has to happen after matching the requests, because callbacks are just requests.
5036 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005037 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005038 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005039 if (networkAgent.isVPN()) {
5040 synchronized (mProxyLock) {
5041 if (mDefaultProxyDisabled) {
5042 mDefaultProxyDisabled = false;
5043 if (mGlobalProxy == null && mDefaultProxy != null) {
5044 sendProxyBroadcast(mDefaultProxy);
5045 }
5046 }
5047 }
5048 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005049 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5050 state == NetworkInfo.State.SUSPENDED) {
5051 // going into or coming out of SUSPEND: rescore and notify
5052 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005053 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005054 }
5055 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5056 ConnectivityManager.CALLBACK_SUSPENDED :
5057 ConnectivityManager.CALLBACK_RESUMED));
5058 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005059 }
5060 }
5061
Robert Greenwaltac96c522014-06-03 16:43:57 -07005062 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005063 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005064 if (score < 0) {
5065 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5066 "). Bumping score to min of 0");
5067 score = 0;
5068 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005069
Paul Jensen2161a8e2014-09-11 11:00:39 -04005070 final int oldScore = nai.getCurrentScore();
5071 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005072
Paul Jensen85cf78e2015-06-25 13:25:07 -04005073 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005074
Paul Jensenc8b9a742014-09-30 15:37:41 -04005075 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005076 }
5077
Robert Greenwalt9258c642014-03-26 16:47:06 -07005078 // notify only this one new request of the current state
5079 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5080 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005081 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005082 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005083 } else {
5084 sendPendingIntentForRequest(nri, nai, notifyType);
5085 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005086 }
5087
Robert Greenwalt8d482522015-06-24 13:23:42 -07005088 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005089 // The NetworkInfo we actually send out has no bearing on the real
5090 // state of affairs. For example, if the default connection is mobile,
5091 // and a request for HIPRI has just gone away, we need to pretend that
5092 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5093 // the state to DISCONNECTED, even though the network is of type MOBILE
5094 // and is still connected.
5095 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5096 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005097 if (state != DetailedState.DISCONNECTED) {
5098 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005099 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005100 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005101 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005102 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5103 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5104 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5105 if (info.isFailover()) {
5106 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5107 nai.networkInfo.setFailover(false);
5108 }
5109 if (info.getReason() != null) {
5110 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5111 }
5112 if (info.getExtraInfo() != null) {
5113 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5114 }
5115 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005116 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005117 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005118 if (newDefaultAgent != null) {
5119 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5120 newDefaultAgent.networkInfo);
5121 } else {
5122 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5123 }
5124 }
5125 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5126 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005127 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005128 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005129 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005130 }
5131 }
5132 }
5133
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005134 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005135 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005136 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5137 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005138 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5139 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005140 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005141 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005142 } else {
5143 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5144 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005145 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005146 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005147
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005148 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5149 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5150 }
5151
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005152 private String notifyTypeToName(int notifyType) {
5153 switch (notifyType) {
5154 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5155 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5156 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5157 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5158 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5159 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5160 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5161 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5162 }
5163 return "UNKNOWN";
5164 }
5165
Jeff Sharkey69736342014-12-08 14:50:12 -08005166 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005167 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5168 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005169 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005170 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005171 try {
5172 mStatsService.forceUpdateIfaces();
5173 } catch (Exception ignored) {
5174 }
5175 }
5176
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005177 @Override
5178 public boolean addVpnAddress(String address, int prefixLength) {
5179 throwIfLockdownEnabled();
5180 int user = UserHandle.getUserId(Binder.getCallingUid());
5181 synchronized (mVpns) {
5182 return mVpns.get(user).addAddress(address, prefixLength);
5183 }
5184 }
5185
5186 @Override
5187 public boolean removeVpnAddress(String address, int prefixLength) {
5188 throwIfLockdownEnabled();
5189 int user = UserHandle.getUserId(Binder.getCallingUid());
5190 synchronized (mVpns) {
5191 return mVpns.get(user).removeAddress(address, prefixLength);
5192 }
5193 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005194
5195 @Override
5196 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5197 throwIfLockdownEnabled();
5198 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005199 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005200 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005201 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005202 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005203 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005204 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005205 }
5206 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005207 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005208
5209 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005210 public String getCaptivePortalServerUrl() {
5211 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5212 }
5213
5214 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005215 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5216 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5217 enforceKeepalivePermission();
5218 mKeepaliveTracker.startNattKeepalive(
5219 getNetworkAgentInfoForNetwork(network),
5220 intervalSeconds, messenger, binder,
5221 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5222 }
5223
5224 @Override
5225 public void stopKeepalive(Network network, int slot) {
5226 mHandler.sendMessage(mHandler.obtainMessage(
5227 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5228 }
5229
5230 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005231 public void factoryReset() {
5232 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005233
5234 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5235 return;
5236 }
5237
Robin Lee3b3dd942015-05-12 18:14:58 +01005238 final int userId = UserHandle.getCallingUserId();
5239
Stuart Scottf1fb3972015-04-02 18:00:02 -07005240 // Turn airplane mode off
5241 setAirplaneMode(false);
5242
Stuart Scotte3e314d2015-04-20 14:07:45 -07005243 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5244 // Untether
5245 for (String tether : getTetheredIfaces()) {
5246 untether(tether);
5247 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005248 }
5249
Stuart Scotte3e314d2015-04-20 14:07:45 -07005250 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005251 // Remove always-on package
5252 synchronized (mVpns) {
5253 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5254 if (alwaysOnPackage != null) {
5255 setAlwaysOnVpnPackage(userId, null, false);
5256 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5257 }
5258 }
5259
Stuart Scotte3e314d2015-04-20 14:07:45 -07005260 // Turn VPN off
5261 VpnConfig vpnConfig = getVpnConfig(userId);
5262 if (vpnConfig != null) {
5263 if (vpnConfig.legacy) {
5264 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5265 } else {
5266 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5267 // in the future without user intervention.
5268 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005269
Victor Changb04a5ea2016-05-30 20:36:30 +01005270 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005271 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005272 }
5273 }
5274 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005275
5276 @VisibleForTesting
5277 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5278 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5279 return new NetworkMonitor(context, handler, nai, defaultRequest);
5280 }
Erik Kline48f12f22016-04-14 17:30:59 +09005281
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005282 @VisibleForTesting
5283 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5284 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5285 }
5286
Hugo Benichicfddd682016-05-31 16:28:06 +09005287 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005288 int newNetid = NETID_UNSET;
5289 int prevNetid = NETID_UNSET;
5290 int[] transports = new int[0];
5291 boolean hadIPv4 = false;
5292 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005293
Hugo Benichi5f16f762016-04-20 12:09:33 +09005294 if (newNai != null) {
5295 newNetid = newNai.network.netId;
5296 transports = newNai.networkCapabilities.getTransportTypes();
5297 }
5298 if (prevNai != null) {
5299 prevNetid = prevNai.network.netId;
5300 final LinkProperties lp = prevNai.linkProperties;
5301 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5302 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5303 }
5304
Hugo Benichicfddd682016-05-31 16:28:06 +09005305 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5306 }
5307
5308 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5309 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005311}