blob: 4c30dc2661ec89aa3f0391b9fb35deb3db8ebba4 [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
Hugo Benichic8e9e122016-09-14 23:23:08 +00002707 @VisibleForTesting
2708 public boolean avoidBadWifi() {
2709 int defaultAvoidBadWifi =
2710 mContext.getResources().getInteger(R.integer.config_networkAvoidBadWifi);
2711 int avoid = Settings.Global.getInt(mContext.getContentResolver(),
2712 Settings.Global.NETWORK_AVOID_BAD_WIFI, defaultAvoidBadWifi);
2713 return avoid == 1;
2714 }
2715
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002716 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002717 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002718 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2719
2720 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2721 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002722 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002723 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002724 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2725 return;
2726 }
2727
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002728 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002729 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002730 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2731 intent.setClassName("com.android.settings",
2732 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002733
2734 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2735 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
fionaxu1bf6ec22016-05-23 16:33:16 -07002736
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002737 mNotifier.showNotification(nai.network.netId, NotificationType.NO_INTERNET, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002738 pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002739 }
2740
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002741 private class InternalHandler extends Handler {
2742 public InternalHandler(Looper looper) {
2743 super(looper);
2744 }
2745
2746 @Override
2747 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002748 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002749 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002750 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002751 String causedBy = null;
2752 synchronized (ConnectivityService.this) {
2753 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2754 mNetTransitionWakeLock.isHeld()) {
2755 mNetTransitionWakeLock.release();
2756 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002757 } else {
2758 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002759 }
2760 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002761 if (VDBG) {
2762 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2763 log("Failed to find a new network - expiring NetTransition Wakelock");
2764 } else {
2765 log("NetTransition Wakelock (" +
2766 (causedBy == null ? "unknown" : causedBy) +
2767 " cleared because we found a replacement network");
2768 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002769 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002770 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002771 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002772 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002773 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002774 break;
2775 }
Jason Monkdecd2952013-10-10 14:02:51 -04002776 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002777 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002778 break;
2779 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002780 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002781 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2782 break;
2783 }
2784 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2785 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002786 break;
2787 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002788 case EVENT_REGISTER_NETWORK_AGENT: {
2789 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2790 break;
2791 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002792 case EVENT_REGISTER_NETWORK_REQUEST:
2793 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002794 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002795 break;
2796 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002797 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2798 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002799 handleRegisterNetworkRequestWithIntent(msg);
2800 break;
2801 }
2802 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2803 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2804 break;
2805 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002806 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002807 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002808 break;
2809 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002810 case EVENT_SET_ACCEPT_UNVALIDATED: {
2811 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2812 break;
2813 }
2814 case EVENT_PROMPT_UNVALIDATED: {
2815 handlePromptUnvalidated((Network) msg.obj);
2816 break;
2817 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002818 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2819 handleMobileDataAlwaysOn();
2820 break;
2821 }
Erik Klineacdd6392016-07-07 16:50:58 +09002822 case EVENT_REQUEST_LINKPROPERTIES:
2823 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2824 break;
2825 case EVENT_REQUEST_NETCAPABILITIES:
2826 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2827 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002828 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2829 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2830 mKeepaliveTracker.handleStartKeepalive(msg);
2831 break;
2832 }
2833 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2834 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2835 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2836 int slot = msg.arg1;
2837 int reason = msg.arg2;
2838 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2839 break;
2840 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002841 case EVENT_SYSTEM_READY: {
2842 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2843 nai.networkMonitor.systemReady = true;
2844 }
2845 break;
2846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 }
2848 }
2849 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002850
2851 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002852 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002853 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002854 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002855 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002856 final int status = mTethering.tether(iface);
2857 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2858 try {
2859 mPolicyManager.onTetheringChanged(iface, true);
2860 } catch (RemoteException e) {
2861 }
2862 }
2863 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002864 } else {
2865 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2866 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002867 }
2868
2869 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002870 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002871 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002872 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002873
2874 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002875 final int status = mTethering.untether(iface);
2876 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2877 try {
2878 mPolicyManager.onTetheringChanged(iface, false);
2879 } catch (RemoteException e) {
2880 }
2881 }
2882 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002883 } else {
2884 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2885 }
2886 }
2887
2888 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002889 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002890 public int getLastTetherError(String iface) {
2891 enforceTetherAccessPermission();
2892
2893 if (isTetheringSupported()) {
2894 return mTethering.getLastTetherError(iface);
2895 } else {
2896 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2897 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002898 }
2899
2900 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002901 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002902 public String[] getTetherableUsbRegexs() {
2903 enforceTetherAccessPermission();
2904 if (isTetheringSupported()) {
2905 return mTethering.getTetherableUsbRegexs();
2906 } else {
2907 return new String[0];
2908 }
2909 }
2910
Lorenzo Colitti18660282016-07-04 12:55:44 +09002911 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002912 public String[] getTetherableWifiRegexs() {
2913 enforceTetherAccessPermission();
2914 if (isTetheringSupported()) {
2915 return mTethering.getTetherableWifiRegexs();
2916 } else {
2917 return new String[0];
2918 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002919 }
2920
Lorenzo Colitti18660282016-07-04 12:55:44 +09002921 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002922 public String[] getTetherableBluetoothRegexs() {
2923 enforceTetherAccessPermission();
2924 if (isTetheringSupported()) {
2925 return mTethering.getTetherableBluetoothRegexs();
2926 } else {
2927 return new String[0];
2928 }
2929 }
2930
Lorenzo Colitti18660282016-07-04 12:55:44 +09002931 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002932 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002933 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002934 if (isTetheringSupported()) {
2935 return mTethering.setUsbTethering(enable);
2936 } else {
2937 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2938 }
2939 }
2940
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002941 // TODO - move iface listing, queries, etc to new module
2942 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002943 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002944 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002945 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002946 return mTethering.getTetherableIfaces();
2947 }
2948
Lorenzo Colitti18660282016-07-04 12:55:44 +09002949 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002950 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002951 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002952 return mTethering.getTetheredIfaces();
2953 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002954
Lorenzo Colitti18660282016-07-04 12:55:44 +09002955 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002956 public String[] getTetheringErroredIfaces() {
2957 enforceTetherAccessPermission();
2958 return mTethering.getErroredIfaces();
2959 }
2960
Lorenzo Colitti18660282016-07-04 12:55:44 +09002961 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002962 public String[] getTetheredDhcpRanges() {
2963 enforceConnectivityInternalPermission();
2964 return mTethering.getTetheredDhcpRanges();
2965 }
2966
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002967 // if ro.tether.denied = true we default to no tethering
2968 // gservices could set the secure setting to 1 though to enable it on a build where it
2969 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002970 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002971 public boolean isTetheringSupported() {
2972 enforceTetherAccessPermission();
2973 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002974 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002975 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2976 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002977 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2978 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002979 mTethering.getTetherableWifiRegexs().length != 0 ||
2980 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2981 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002982 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002983
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002984 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002985 public void startTethering(int type, ResultReceiver receiver,
2986 boolean showProvisioningUi) {
2987 ConnectivityManager.enforceTetherChangePermission(mContext);
2988 if (!isTetheringSupported()) {
2989 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2990 return;
2991 }
2992 mTethering.startTethering(type, receiver, showProvisioningUi);
2993 }
2994
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002995 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002996 public void stopTethering(int type) {
2997 ConnectivityManager.enforceTetherChangePermission(mContext);
2998 mTethering.stopTethering(type);
2999 }
3000
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003001 // Called when we lose the default network and have no replacement yet.
3002 // This will automatically be cleared after X seconds or a new default network
3003 // becomes CONNECTED, whichever happens first. The timer is started by the
3004 // first caller and not restarted by subsequent callers.
3005 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003006 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003007 synchronized (this) {
3008 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003009 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003010 mNetTransitionWakeLock.acquire();
3011 mNetTransitionWakeLockCausedBy = forWhom;
3012 }
3013 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003014 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003015 mNetTransitionWakeLockTimeout);
3016 return;
3017 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003018
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003019 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003020 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003021 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003022 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003023 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003024 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003025 }
3026
Lorenzo Colitti18660282016-07-04 12:55:44 +09003027 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003028 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003029 enforceAccessPermission();
3030 enforceInternetPermission();
3031
Paul Jensenbfd17b72015-04-07 12:43:13 -04003032 NetworkAgentInfo nai;
3033 if (network == null) {
3034 nai = getDefaultNetwork();
3035 } else {
3036 nai = getNetworkAgentInfoForNetwork(network);
3037 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003038 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3039 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3040 return;
3041 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003042 // Revalidate if the app report does not match our current validated state.
3043 if (hasConnectivity == nai.lastValidated) return;
3044 final int uid = Binder.getCallingUid();
3045 if (DBG) {
3046 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3047 ") by " + uid);
3048 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003049 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003050 // Validating a network that has not yet connected could result in a call to
3051 // rematchNetworkAndRequests() which is not meant to work on such networks.
3052 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003053
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003054 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003055
3056 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3057 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003058 }
3059
Paul Jensencee9b512015-05-06 07:32:40 -04003060 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003061 // this information is already available as a world read/writable jvm property
3062 // so this API change wouldn't have a benifit. It also breaks the passing
3063 // of proxy info to all the JVMs.
3064 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003065 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003066 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003067 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3068 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003069 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003070 }
3071
Lorenzo Colitti18660282016-07-04 12:55:44 +09003072 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003073 public ProxyInfo getProxyForNetwork(Network network) {
3074 if (network == null) return getDefaultProxy();
3075 final ProxyInfo globalProxy = getGlobalProxy();
3076 if (globalProxy != null) return globalProxy;
3077 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3078 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3079 // caller may not have.
3080 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3081 if (nai == null) return null;
3082 synchronized (nai) {
3083 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3084 if (proxyInfo == null) return null;
3085 return new ProxyInfo(proxyInfo);
3086 }
3087 }
3088
Paul Jensene0bef712014-12-10 15:12:18 -05003089 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3090 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3091 // proxy is null then there is no proxy in place).
3092 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3093 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3094 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3095 proxy = null;
3096 }
3097 return proxy;
3098 }
3099
3100 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3101 // better for determining if a new proxy broadcast is necessary:
3102 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3103 // avoid unnecessary broadcasts.
3104 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3105 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3106 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3107 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3108 // all set.
3109 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3110 a = canonicalizeProxyInfo(a);
3111 b = canonicalizeProxyInfo(b);
3112 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3113 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3114 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3115 }
3116
Jason Monk207900c2014-04-25 15:00:09 -04003117 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003118 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003119
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003120 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003121 if (proxyProperties == mGlobalProxy) return;
3122 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3123 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3124
3125 String host = "";
3126 int port = 0;
3127 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003128 String pacFileUrl = "";
3129 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003130 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003131 if (!proxyProperties.isValid()) {
3132 if (DBG)
3133 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3134 return;
3135 }
Jason Monk207900c2014-04-25 15:00:09 -04003136 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003137 host = mGlobalProxy.getHost();
3138 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003139 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003140 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003141 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003142 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003143 } else {
3144 mGlobalProxy = null;
3145 }
3146 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003147 final long token = Binder.clearCallingIdentity();
3148 try {
3149 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3150 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3151 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3152 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003153 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003154 } finally {
3155 Binder.restoreCallingIdentity(token);
3156 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003157
Jason Monkcf0f97a2014-10-02 15:39:38 -04003158 if (mGlobalProxy == null) {
3159 proxyProperties = mDefaultProxy;
3160 }
3161 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003162 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003163 }
3164
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003165 private void loadGlobalProxy() {
3166 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003167 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3168 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3169 String exclList = Settings.Global.getString(res,
3170 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003171 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3172 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003173 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003174 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003175 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003176 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003177 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003178 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003179 if (!proxyProperties.isValid()) {
3180 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3181 return;
3182 }
3183
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003184 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003185 mGlobalProxy = proxyProperties;
3186 }
3187 }
3188 }
3189
Jason Monk207900c2014-04-25 15:00:09 -04003190 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003191 // this information is already available as a world read/writable jvm property
3192 // so this API change wouldn't have a benifit. It also breaks the passing
3193 // of proxy info to all the JVMs.
3194 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003195 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003196 return mGlobalProxy;
3197 }
3198 }
3199
Jason Monk207900c2014-04-25 15:00:09 -04003200 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003201 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003202 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003203 proxy = null;
3204 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003205 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003206 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003207 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003208 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003209 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3210 return;
3211 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003212
3213 // This call could be coming from the PacManager, containing the port of the local
3214 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3215 // global (to get the correct local port), and send a broadcast.
3216 // TODO: Switch PacManager to have its own message to send back rather than
3217 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003218 if ((mGlobalProxy != null) && (proxy != null)
3219 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003220 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3221 mGlobalProxy = proxy;
3222 sendProxyBroadcast(mGlobalProxy);
3223 return;
3224 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003225 mDefaultProxy = proxy;
3226
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003227 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003228 if (!mDefaultProxyDisabled) {
3229 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003230 }
3231 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003232 }
3233
Paul Jensene0bef712014-12-10 15:12:18 -05003234 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3235 // This method gets called when any network changes proxy, but the broadcast only ever contains
3236 // the default proxy (even if it hasn't changed).
3237 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3238 // world where an app might be bound to a non-default network.
3239 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3240 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3241 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3242
3243 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3244 sendProxyBroadcast(getDefaultProxy());
3245 }
3246 }
3247
Robert Greenwalt434203a2010-10-11 16:00:27 -07003248 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003249 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3250 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003251 if (!TextUtils.isEmpty(proxy)) {
3252 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003253 if (data.length == 0) {
3254 return;
3255 }
3256
Robert Greenwalt434203a2010-10-11 16:00:27 -07003257 String proxyHost = data[0];
3258 int proxyPort = 8080;
3259 if (data.length > 1) {
3260 try {
3261 proxyPort = Integer.parseInt(data[1]);
3262 } catch (NumberFormatException e) {
3263 return;
3264 }
3265 }
Jason Monk207900c2014-04-25 15:00:09 -04003266 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003267 setGlobalProxy(p);
3268 }
3269 }
3270
Jason Monk207900c2014-04-25 15:00:09 -04003271 private void sendProxyBroadcast(ProxyInfo proxy) {
3272 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003273 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003274 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003275 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003276 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3277 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003278 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003279 final long ident = Binder.clearCallingIdentity();
3280 try {
3281 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3282 } finally {
3283 Binder.restoreCallingIdentity(ident);
3284 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003285 }
3286
3287 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003288 final private HashMap<Uri, Integer> mUriEventMap;
3289 final private Context mContext;
3290 final private Handler mHandler;
3291
3292 SettingsObserver(Context context, Handler handler) {
3293 super(null);
3294 mUriEventMap = new HashMap<Uri, Integer>();
3295 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003296 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003297 }
3298
Erik Klineda4bfa82015-04-30 12:58:40 +09003299 void observe(Uri uri, int what) {
3300 mUriEventMap.put(uri, what);
3301 final ContentResolver resolver = mContext.getContentResolver();
3302 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003303 }
3304
3305 @Override
3306 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003307 Slog.wtf(TAG, "Should never be reached.");
3308 }
3309
3310 @Override
3311 public void onChange(boolean selfChange, Uri uri) {
3312 final Integer what = mUriEventMap.get(uri);
3313 if (what != null) {
3314 mHandler.obtainMessage(what.intValue()).sendToTarget();
3315 } else {
3316 loge("No matching event to send for URI=" + uri);
3317 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003318 }
3319 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003320
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003321 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003322 Slog.d(TAG, s);
3323 }
3324
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003325 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003326 Slog.e(TAG, s);
3327 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003328
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003329 private static <T> T checkNotNull(T value, String message) {
3330 if (value == null) {
3331 throw new NullPointerException(message);
3332 }
3333 return value;
3334 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003335
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003336 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003337 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003338 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3339 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3340 *
3341 * @param oldPackage Package name of the application which currently controls VPN, which will
3342 * be replaced. If there is no such application, this should should either be
3343 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3344 * @param newPackage Package name of the application which should gain control of VPN, or
3345 * {@code null} to disable.
3346 * @param userId User for whom to prepare the new VPN.
3347 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003348 * @hide
3349 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003350 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003351 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3352 int userId) {
3353 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003354 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003355
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003356 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003357 Vpn vpn = mVpns.get(userId);
3358 if (vpn != null) {
3359 return vpn.prepare(oldPackage, newPackage);
3360 } else {
3361 return false;
3362 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003363 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003364 }
3365
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003366 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003367 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3368 * This method is used by system-privileged apps.
3369 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3370 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3371 *
3372 * @param packageName The package for which authorization state should change.
3373 * @param userId User for whom {@code packageName} is installed.
3374 * @param authorized {@code true} if this app should be able to start a VPN connection without
3375 * explicit user approval, {@code false} if not.
3376 *
Jeff Davidson05542602014-08-11 14:07:27 -07003377 * @hide
3378 */
3379 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003380 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3381 enforceCrossUserPermission(userId);
3382
Jeff Davidson05542602014-08-11 14:07:27 -07003383 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003384 Vpn vpn = mVpns.get(userId);
3385 if (vpn != null) {
3386 vpn.setPackageAuthorization(packageName, authorized);
3387 }
Jeff Davidson05542602014-08-11 14:07:27 -07003388 }
3389 }
3390
3391 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003392 * Configure a TUN interface and return its file descriptor. Parameters
3393 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003394 * and not available in ConnectivityManager. Permissions are checked in
3395 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003396 * @hide
3397 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003398 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003399 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003400 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003401 int user = UserHandle.getUserId(Binder.getCallingUid());
3402 synchronized(mVpns) {
3403 return mVpns.get(user).establish(config);
3404 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003405 }
3406
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003407 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003408 * Start legacy VPN, controlling native daemons as needed. Creates a
3409 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003410 */
3411 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003412 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003413 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003414 final LinkProperties egress = getActiveLinkProperties();
3415 if (egress == null) {
3416 throw new IllegalStateException("Missing active network connection");
3417 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003418 int user = UserHandle.getUserId(Binder.getCallingUid());
3419 synchronized(mVpns) {
3420 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3421 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003422 }
3423
3424 /**
3425 * Return the information of the ongoing legacy VPN. This method is used
3426 * by VpnSettings and not available in ConnectivityManager. Permissions
3427 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003428 */
3429 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003430 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3431 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003432
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003433 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003434 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003435 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003436 }
3437
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003438 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003439 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3440 * and not available in ConnectivityManager.
3441 */
3442 @Override
3443 public VpnInfo[] getAllVpnInfo() {
3444 enforceConnectivityInternalPermission();
3445 if (mLockdownEnabled) {
3446 return new VpnInfo[0];
3447 }
3448
3449 synchronized(mVpns) {
3450 List<VpnInfo> infoList = new ArrayList<>();
3451 for (int i = 0; i < mVpns.size(); i++) {
3452 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3453 if (info != null) {
3454 infoList.add(info);
3455 }
3456 }
3457 return infoList.toArray(new VpnInfo[infoList.size()]);
3458 }
3459 }
3460
3461 /**
3462 * @return VPN information for accounting, or null if we can't retrieve all required
3463 * information, e.g primary underlying iface.
3464 */
3465 @Nullable
3466 private VpnInfo createVpnInfo(Vpn vpn) {
3467 VpnInfo info = vpn.getVpnInfo();
3468 if (info == null) {
3469 return null;
3470 }
3471 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3472 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3473 // the underlyingNetworks list.
3474 if (underlyingNetworks == null) {
3475 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3476 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3477 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3478 }
3479 } else if (underlyingNetworks.length > 0) {
3480 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3481 if (linkProperties != null) {
3482 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3483 }
3484 }
3485 return info.primaryUnderlyingIface == null ? null : info;
3486 }
3487
3488 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003489 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3490 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003491 * Permissions are checked in Vpn class.
3492 * @hide
3493 */
3494 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003495 public VpnConfig getVpnConfig(int userId) {
3496 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003497 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003498 Vpn vpn = mVpns.get(userId);
3499 if (vpn != null) {
3500 return vpn.getVpnConfig();
3501 } else {
3502 return null;
3503 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003504 }
3505 }
3506
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003507 @Override
3508 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003509 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3510 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3511 return false;
3512 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003513
3514 // Tear down existing lockdown if profile was removed
3515 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3516 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003517 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3518 final VpnProfile profile = VpnProfile.decode(
3519 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003520 if (profile == null) {
3521 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3522 setLockdownTracker(null);
3523 return true;
3524 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003525 int user = UserHandle.getUserId(Binder.getCallingUid());
3526 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003527 Vpn vpn = mVpns.get(user);
3528 if (vpn == null) {
3529 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3530 return false;
3531 }
3532 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003533 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003534 } else {
3535 setLockdownTracker(null);
3536 }
3537
3538 return true;
3539 }
3540
3541 /**
3542 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3543 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3544 */
3545 private void setLockdownTracker(LockdownVpnTracker tracker) {
3546 // Shutdown any existing tracker
3547 final LockdownVpnTracker existing = mLockdownTracker;
3548 mLockdownTracker = null;
3549 if (existing != null) {
3550 existing.shutdown();
3551 }
3552
3553 try {
3554 if (tracker != null) {
3555 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003556 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003557 mLockdownTracker = tracker;
3558 mLockdownTracker.init();
3559 } else {
3560 mNetd.setFirewallEnabled(false);
3561 }
3562 } catch (RemoteException e) {
3563 // ignored; NMS lives inside system_server
3564 }
3565 }
3566
3567 private void throwIfLockdownEnabled() {
3568 if (mLockdownEnabled) {
3569 throw new IllegalStateException("Unavailable in lockdown mode");
3570 }
3571 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003572
Robin Lee244ce8e2016-01-05 18:03:46 +00003573 /**
Robin Lee17e61832016-05-09 13:46:28 +01003574 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3575 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003576 *
Robin Lee17e61832016-05-09 13:46:28 +01003577 * @return {@code true} if the service was started, the service was already connected, or there
3578 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003579 */
Robin Lee17e61832016-05-09 13:46:28 +01003580 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003581 synchronized (mVpns) {
3582 Vpn vpn = mVpns.get(userId);
3583 if (vpn == null) {
3584 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3585 // exists already.
3586 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3587 return false;
3588 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003589
Robin Lee812800c2016-05-13 15:38:08 +01003590 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003591 }
3592 }
3593
3594 @Override
Robin Leedc679712016-05-03 13:23:03 +01003595 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003596 enforceConnectivityInternalPermission();
3597 enforceCrossUserPermission(userId);
3598
3599 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3600 if (LockdownVpnTracker.isEnabled()) {
3601 return false;
3602 }
3603
Robin Lee244ce8e2016-01-05 18:03:46 +00003604 synchronized (mVpns) {
3605 Vpn vpn = mVpns.get(userId);
3606 if (vpn == null) {
3607 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3608 return false;
3609 }
Robin Lee17e61832016-05-09 13:46:28 +01003610 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003611 return false;
3612 }
Robin Lee17e61832016-05-09 13:46:28 +01003613 if (!startAlwaysOnVpn(userId)) {
3614 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003615 return false;
3616 }
Robin Lee17e61832016-05-09 13:46:28 +01003617
Robin Lee812800c2016-05-13 15:38:08 +01003618 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003619 }
3620 return true;
3621 }
3622
3623 @Override
3624 public String getAlwaysOnVpnPackage(int userId) {
3625 enforceConnectivityInternalPermission();
3626 enforceCrossUserPermission(userId);
3627
3628 synchronized (mVpns) {
3629 Vpn vpn = mVpns.get(userId);
3630 if (vpn == null) {
3631 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3632 return null;
3633 }
3634 return vpn.getAlwaysOnPackage();
3635 }
3636 }
3637
Wink Savilleab9321d2013-06-29 21:10:57 -07003638 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003639 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003640 // TODO: Remove? Any reason to trigger a provisioning check?
3641 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003642 }
3643
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003644 /** Location to an updatable file listing carrier provisioning urls.
3645 * An example:
3646 *
3647 * <?xml version="1.0" encoding="utf-8"?>
3648 * <provisioningUrls>
3649 * <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 -07003650 * </provisioningUrls>
3651 */
3652 private static final String PROVISIONING_URL_PATH =
3653 "/data/misc/radio/provisioning_urls.xml";
3654 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003655
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003656 /** XML tag for root element. */
3657 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3658 /** XML tag for individual url */
3659 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003660 /** XML attribute for mcc */
3661 private static final String ATTR_MCC = "mcc";
3662 /** XML attribute for mnc */
3663 private static final String ATTR_MNC = "mnc";
3664
Paul Jensen434dde82015-06-11 09:43:30 -04003665 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003666 FileReader fileReader = null;
3667 XmlPullParser parser = null;
3668 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003669
3670 try {
3671 fileReader = new FileReader(mProvisioningUrlFile);
3672 parser = Xml.newPullParser();
3673 parser.setInput(fileReader);
3674 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3675
3676 while (true) {
3677 XmlUtils.nextElement(parser);
3678
3679 String element = parser.getName();
3680 if (element == null) break;
3681
Paul Jensen434dde82015-06-11 09:43:30 -04003682 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003683 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3684 try {
3685 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3686 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3687 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3688 parser.next();
3689 if (parser.getEventType() == XmlPullParser.TEXT) {
3690 return parser.getText();
3691 }
3692 }
3693 }
3694 } catch (NumberFormatException e) {
3695 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3696 }
3697 }
3698 }
3699 return null;
3700 } catch (FileNotFoundException e) {
3701 loge("Carrier Provisioning Urls file not found");
3702 } catch (XmlPullParserException e) {
3703 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3704 } catch (IOException e) {
3705 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3706 } finally {
3707 if (fileReader != null) {
3708 try {
3709 fileReader.close();
3710 } catch (IOException e) {}
3711 }
3712 }
3713 return null;
3714 }
3715
Wink Saville42d4f082013-07-20 20:31:59 -07003716 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003717 public String getMobileProvisioningUrl() {
3718 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003719 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003720 if (TextUtils.isEmpty(url)) {
3721 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003722 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003723 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003724 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003725 }
Wink Saville8cf35602013-07-10 23:00:07 -07003726 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003727 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003728 String phoneNumber = mTelephonyManager.getLine1Number();
3729 if (TextUtils.isEmpty(phoneNumber)) {
3730 phoneNumber = "0000000000";
3731 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003732 url = String.format(url,
3733 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3734 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003735 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003736 }
3737
Wink Savilleab9321d2013-06-29 21:10:57 -07003738 return url;
3739 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003740
Wink Saville948282b2013-08-29 08:55:16 -07003741 @Override
3742 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003743 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003744 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003745 final long ident = Binder.clearCallingIdentity();
3746 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003747 // Concatenate the range of types onto the range of NetIDs.
3748 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3749 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003750 } finally {
3751 Binder.restoreCallingIdentity(ident);
3752 }
Wink Saville948282b2013-08-29 08:55:16 -07003753 }
Wink Saville7788c612013-08-29 14:57:08 -07003754
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003755 @Override
3756 public void setAirplaneMode(boolean enable) {
3757 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003758 final long ident = Binder.clearCallingIdentity();
3759 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003760 final ContentResolver cr = mContext.getContentResolver();
3761 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3762 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3763 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003764 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003765 } finally {
3766 Binder.restoreCallingIdentity(ident);
3767 }
3768 }
3769
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003770 private void onUserStart(int userId) {
3771 synchronized(mVpns) {
3772 Vpn userVpn = mVpns.get(userId);
3773 if (userVpn != null) {
3774 loge("Starting user already has a VPN");
3775 return;
3776 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003777 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003778 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003779
3780 final ContentResolver cr = mContext.getContentResolver();
3781 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3782 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3783 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3784 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3785 if (alwaysOnPackage != null) {
3786 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3787 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003788 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003789 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3790 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003791 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003792 }
3793
3794 private void onUserStop(int userId) {
3795 synchronized(mVpns) {
3796 Vpn userVpn = mVpns.get(userId);
3797 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003798 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003799 return;
3800 }
Robin Lee17e61832016-05-09 13:46:28 +01003801 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003802 mVpns.delete(userId);
3803 }
3804 }
3805
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003806 private void onUserAdded(int userId) {
3807 synchronized(mVpns) {
3808 final int vpnsSize = mVpns.size();
3809 for (int i = 0; i < vpnsSize; i++) {
3810 Vpn vpn = mVpns.valueAt(i);
3811 vpn.onUserAdded(userId);
3812 }
3813 }
3814 }
3815
3816 private void onUserRemoved(int userId) {
3817 synchronized(mVpns) {
3818 final int vpnsSize = mVpns.size();
3819 for (int i = 0; i < vpnsSize; i++) {
3820 Vpn vpn = mVpns.valueAt(i);
3821 vpn.onUserRemoved(userId);
3822 }
3823 }
3824 }
3825
Robin Lee89e7a692016-02-29 14:38:17 +00003826 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003827 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3828 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3829 updateLockdownVpn();
3830 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003831 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003832 }
3833 }
3834
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003835 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3836 @Override
3837 public void onReceive(Context context, Intent intent) {
3838 final String action = intent.getAction();
3839 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3840 if (userId == UserHandle.USER_NULL) return;
3841
Robin Lee323f29d2016-05-04 16:38:06 +01003842 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003843 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003844 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003845 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003846 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3847 onUserAdded(userId);
3848 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3849 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003850 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3851 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003852 }
3853 }
3854 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003855
Robert Greenwalta67be032014-05-16 15:49:14 -07003856 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3857 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003858 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3859 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003860
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003861 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3862 // Map from UID to number of NetworkRequests that UID has filed.
3863 @GuardedBy("mUidToNetworkRequestCount")
3864 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3865
Robert Greenwalta67be032014-05-16 15:49:14 -07003866 private static class NetworkFactoryInfo {
3867 public final String name;
3868 public final Messenger messenger;
3869 public final AsyncChannel asyncChannel;
3870
3871 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3872 this.name = name;
3873 this.messenger = messenger;
3874 this.asyncChannel = asyncChannel;
3875 }
3876 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003877
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003878 private void ensureNetworkRequestHasType(NetworkRequest request) {
3879 if (request.type == NetworkRequest.Type.NONE) {
3880 throw new IllegalArgumentException(
3881 "All NetworkRequests in ConnectivityService must have a type");
3882 }
3883 }
3884
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003885 /**
3886 * Tracks info about the requester.
3887 * Also used to notice when the calling process dies so we can self-expire
3888 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003889 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003890 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003891 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003892 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003893 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003894 final int mPid;
3895 final int mUid;
3896 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003897
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003898 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003899 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003900 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003901 mPendingIntent = pi;
3902 messenger = null;
3903 mBinder = null;
3904 mPid = getCallingPid();
3905 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003906 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003907 }
3908
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003909 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003910 super();
3911 messenger = m;
3912 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003913 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003914 mBinder = binder;
3915 mPid = getCallingPid();
3916 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003917 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003918 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003919
3920 try {
3921 mBinder.linkToDeath(this, 0);
3922 } catch (RemoteException e) {
3923 binderDied();
3924 }
3925 }
3926
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003927 private void enforceRequestCountLimit() {
3928 synchronized (mUidToNetworkRequestCount) {
3929 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3930 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3931 throw new IllegalArgumentException("Too many NetworkRequests filed");
3932 }
3933 mUidToNetworkRequestCount.put(mUid, networkRequests);
3934 }
3935 }
3936
Robert Greenwalt9258c642014-03-26 16:47:06 -07003937 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003938 if (mBinder != null) {
3939 mBinder.unlinkToDeath(this, 0);
3940 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003941 }
3942
3943 public void binderDied() {
3944 log("ConnectivityService NetworkRequestInfo binderDied(" +
3945 request + ", " + mBinder + ")");
3946 releaseNetworkRequest(request);
3947 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003948
3949 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003950 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003951 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003952 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003953 }
3954
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003955 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3956 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3957 if (badCapability != null) {
3958 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003959 }
3960 }
3961
Erik Kline9d598e12015-07-13 16:37:51 +09003962 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003963 final SortedSet<Integer> thresholds = new TreeSet();
3964 synchronized (nai) {
3965 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3966 if (nri.request.networkCapabilities.hasSignalStrength() &&
3967 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3968 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3969 }
3970 }
3971 }
Erik Kline9d598e12015-07-13 16:37:51 +09003972 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003973 }
3974
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003975 private void updateSignalStrengthThresholds(
3976 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3977 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003978 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003979 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3980
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003981 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003982 String detail;
3983 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3984 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3985 } else {
3986 detail = reason;
3987 }
3988 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3989 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3990 }
3991
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003992 nai.asyncChannel.sendMessage(
3993 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003994 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003995 }
3996
Robert Greenwalt9258c642014-03-26 16:47:06 -07003997 @Override
3998 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003999 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004000 final NetworkRequest.Type type = (networkCapabilities == null)
4001 ? NetworkRequest.Type.TRACK_DEFAULT
4002 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004003 // If the requested networkCapabilities is null, take them instead from
4004 // the default network request. This allows callers to keep track of
4005 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004006 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004007 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4008 enforceAccessPermission();
4009 } else {
4010 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4011 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004012 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4013 // of the app when the request is filed, but we never change the request if the app
4014 // changes network state. http://b/29964605
4015 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004016 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004017 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004018
Robert Greenwalt6078b502014-06-11 16:05:07 -07004019 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004020 throw new IllegalArgumentException("Bad timeout specified");
4021 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004022
Etan Cohenddb9ef02015-11-18 10:56:15 -08004023 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4024 .equals(networkCapabilities.getNetworkSpecifier())) {
4025 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4026 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4027 }
4028
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004029 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004030 nextNetworkRequestId(), type);
4031 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004032 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004033
4034 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004035 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004036 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004037 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004038 }
4039 return networkRequest;
4040 }
4041
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004042 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004043 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004044 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004045 } else {
4046 enforceChangePermission();
4047 }
4048 }
4049
fenglub15e72b2015-03-20 11:29:56 -07004050 @Override
fengludb571472015-04-21 17:12:05 -07004051 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004052 enforceAccessPermission();
4053 NetworkAgentInfo nai = null;
4054 if (network == null) {
4055 return false;
4056 }
4057 synchronized (mNetworkForNetId) {
4058 nai = mNetworkForNetId.get(network.netId);
4059 }
4060 if (nai != null) {
4061 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4062 return true;
4063 }
4064 return false;
4065 }
4066
Felipe Lemeee27cab2016-06-20 16:36:29 -07004067 private boolean isSystem(int uid) {
4068 return uid < Process.FIRST_APPLICATION_UID;
4069 }
fenglub15e72b2015-03-20 11:29:56 -07004070
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004071 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004072 final int uid = Binder.getCallingUid();
4073 if (isSystem(uid)) {
4074 return;
4075 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004076 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004077 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004078 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004079 synchronized(mRulesLock) {
4080 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4081 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004082 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4083 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004084 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004085 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004086 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004087 }
4088 }
4089 }
4090
Robert Greenwalt9258c642014-03-26 16:47:06 -07004091 @Override
4092 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4093 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004094 checkNotNull(operation, "PendingIntent cannot be null.");
4095 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4096 enforceNetworkRequestPermissions(networkCapabilities);
4097 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004098 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004099
4100 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004101 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4102 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004103 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004104 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4105 nri));
4106 return networkRequest;
4107 }
4108
Jeremy Joslin79294842014-12-03 17:15:28 -08004109 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4110 mHandler.sendMessageDelayed(
4111 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4112 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4113 }
4114
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004115 @Override
4116 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004117 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004118 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4119 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004120 }
4121
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004122 // In order to implement the compatibility measure for pre-M apps that call
4123 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4124 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4125 // This ensures it has permission to do so.
4126 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4127 if (nc == null) {
4128 return false;
4129 }
4130 int[] transportTypes = nc.getTransportTypes();
4131 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4132 return false;
4133 }
4134 try {
4135 mContext.enforceCallingOrSelfPermission(
4136 android.Manifest.permission.ACCESS_WIFI_STATE,
4137 "ConnectivityService");
4138 } catch (SecurityException e) {
4139 return false;
4140 }
4141 return true;
4142 }
4143
Robert Greenwalt9258c642014-03-26 16:47:06 -07004144 @Override
4145 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4146 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004147 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4148 enforceAccessPermission();
4149 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004150
Erik Kline7523eb32015-07-09 18:24:03 +09004151 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004152 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4153 NetworkRequest.Type.LISTEN);
4154 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004155 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004156
4157 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4158 return networkRequest;
4159 }
4160
4161 @Override
4162 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4163 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004164 checkNotNull(operation, "PendingIntent cannot be null.");
4165 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4166 enforceAccessPermission();
4167 }
4168
Erik Kline7523eb32015-07-09 18:24:03 +09004169 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004170 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4171 NetworkRequest.Type.LISTEN);
4172 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004173 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004174
4175 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004176 }
4177
4178 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004179 public void requestLinkProperties(NetworkRequest networkRequest) {
4180 ensureNetworkRequestHasType(networkRequest);
4181 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4182 mHandler.sendMessage(mHandler.obtainMessage(
4183 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4184 }
4185
4186 @Override
4187 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4188 ensureNetworkRequestHasType(networkRequest);
4189 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4190 mHandler.sendMessage(mHandler.obtainMessage(
4191 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4192 }
4193
4194 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004195 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004196 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004197 mHandler.sendMessage(mHandler.obtainMessage(
4198 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004199 }
4200
4201 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004202 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004203 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004204 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4205 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004206 }
4207
Robert Greenwalta67be032014-05-16 15:49:14 -07004208 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004209 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004210 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4211 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4212 }
4213
4214 @Override
4215 public void unregisterNetworkFactory(Messenger messenger) {
4216 enforceConnectivityInternalPermission();
4217 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4218 }
4219
4220 private void handleUnregisterNetworkFactory(Messenger messenger) {
4221 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4222 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004223 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004224 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004225 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004226 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004227 }
4228
Robert Greenwalt7b816022014-04-18 15:25:25 -07004229 /**
4230 * NetworkAgentInfo supporting a request by requestId.
4231 * These have already been vetted (their Capabilities satisfy the request)
4232 * and the are the highest scored network available.
4233 * the are keyed off the Requests requestId.
4234 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004235 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004236 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4237 new SparseArray<NetworkAgentInfo>();
4238
Paul Jensen31a94f42015-02-13 14:18:39 -05004239 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4240 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004241 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4242 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004243 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4244 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4245 // there may not be a strict 1:1 correlation between the two.
4246 @GuardedBy("mNetworkForNetId")
4247 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004248
Robert Greenwalt7b816022014-04-18 15:25:25 -07004249 // NetworkAgentInfo keyed off its connecting messenger
4250 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004251 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004252 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4253 new HashMap<Messenger, NetworkAgentInfo>();
4254
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004255 @GuardedBy("mBlockedAppUids")
4256 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4257
Paul Jensen2c311d62014-11-17 12:34:51 -05004258 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004259 private final NetworkRequest mDefaultRequest;
4260
Erik Klineda4bfa82015-04-30 12:58:40 +09004261 // Request used to optionally keep mobile data active even when higher
4262 // priority networks like Wi-Fi are active.
4263 private final NetworkRequest mDefaultMobileDataRequest;
4264
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004265 private NetworkAgentInfo getDefaultNetwork() {
4266 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4267 }
4268
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004269 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004270 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004271 }
4272
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004273 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4274 return nri.request.requestId == mDefaultRequest.requestId;
4275 }
4276
Paul Jensen31a94f42015-02-13 14:18:39 -05004277 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004278 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004279 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004280 enforceConnectivityInternalPermission();
4281
Paul Jensen2c311d62014-11-17 12:34:51 -05004282 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4283 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004284 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004285 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4286 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004287 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004288 synchronized (this) {
4289 nai.networkMonitor.systemReady = mSystemReady;
4290 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004291 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4292 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004293 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004294 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004295 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004296 }
4297
4298 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4299 if (VDBG) log("Got NetworkAgent Messenger");
4300 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004301 synchronized (mNetworkForNetId) {
4302 mNetworkForNetId.put(na.network.netId, na);
4303 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004304 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4305 NetworkInfo networkInfo = na.networkInfo;
4306 na.networkInfo = null;
4307 updateNetworkInfo(na, networkInfo);
4308 }
4309
4310 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4311 LinkProperties newLp = networkAgent.linkProperties;
4312 int netId = networkAgent.network.netId;
4313
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004314 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4315 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004316 if (networkAgent.clatd != null) {
4317 networkAgent.clatd.fixupLinkProperties(oldLp);
4318 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004319
Paul Jensen992f2522014-04-28 10:33:11 -04004320 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004321 updateMtu(newLp, oldLp);
4322 // TODO - figure out what to do for clat
4323// for (LinkProperties lp : newLp.getStackedLinks()) {
4324// updateMtu(lp, null);
4325// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004326 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004327
Erik Kline94887872016-04-05 13:30:49 +09004328 updateRoutes(newLp, oldLp, netId);
4329 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004330
Paul Jensen3b759822014-05-13 11:44:01 -04004331 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004332 if (isDefaultNetwork(networkAgent)) {
4333 handleApplyDefaultProxy(newLp.getHttpProxy());
4334 } else {
4335 updateProxy(newLp, oldLp, networkAgent);
4336 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004337 // TODO - move this check to cover the whole function
4338 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004339 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004340 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4341 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004342
4343 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004344 }
4345
Lorenzo Colitti95439462014-10-09 13:44:48 +09004346 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4347 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4348 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004349
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004350 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004351 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4352 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004353 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004354 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004355 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004356 }
Paul Jensen992f2522014-04-28 10:33:11 -04004357
4358 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4359 CompareResult<String> interfaceDiff = new CompareResult<String>();
4360 if (oldLp != null) {
4361 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4362 } else if (newLp != null) {
4363 interfaceDiff.added = newLp.getAllInterfaceNames();
4364 }
4365 for (String iface : interfaceDiff.added) {
4366 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004367 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004368 mNetd.addInterfaceToNetwork(iface, netId);
4369 } catch (Exception e) {
4370 loge("Exception adding interface: " + e);
4371 }
4372 }
4373 for (String iface : interfaceDiff.removed) {
4374 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004375 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004376 mNetd.removeInterfaceFromNetwork(iface, netId);
4377 } catch (Exception e) {
4378 loge("Exception removing interface: " + e);
4379 }
4380 }
4381 }
4382
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004383 /**
4384 * Have netd update routes from oldLp to newLp.
4385 * @return true if routes changed between oldLp and newLp
4386 */
4387 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004388 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4389 if (oldLp != null) {
4390 routeDiff = oldLp.compareAllRoutes(newLp);
4391 } else if (newLp != null) {
4392 routeDiff.added = newLp.getAllRoutes();
4393 }
4394
4395 // add routes before removing old in case it helps with continuous connectivity
4396
4397 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4398 for (RouteInfo route : routeDiff.added) {
4399 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004400 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004401 try {
4402 mNetd.addRoute(netId, route);
4403 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004404 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4405 loge("Exception in addRoute for non-gateway: " + e);
4406 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004407 }
4408 }
4409 for (RouteInfo route : routeDiff.added) {
4410 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004411 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004412 try {
4413 mNetd.addRoute(netId, route);
4414 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004415 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4416 loge("Exception in addRoute for gateway: " + e);
4417 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004418 }
4419 }
4420
4421 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004422 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004423 try {
4424 mNetd.removeRoute(netId, route);
4425 } catch (Exception e) {
4426 loge("Exception in removeRoute: " + e);
4427 }
4428 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004429 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004430 }
Erik Kline41368502015-06-17 13:19:54 +09004431
Erik Kline94887872016-04-05 13:30:49 +09004432 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4433 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4434 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004435 }
Erik Kline94887872016-04-05 13:30:49 +09004436
4437 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004438 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004439 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004440 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004441 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4442 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004443 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004444 }
4445 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4446 if (defaultNai != null && defaultNai.network.netId == netId) {
4447 setDefaultDnsSystemProperties(dnses);
4448 }
4449 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004450 }
4451
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004452 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4453 int last = 0;
4454 for (InetAddress dns : dnses) {
4455 ++last;
4456 String key = "net.dns" + last;
4457 String value = dns.getHostAddress();
4458 SystemProperties.set(key, value);
4459 }
4460 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4461 String key = "net.dns" + i;
4462 SystemProperties.set(key, "");
4463 }
4464 mNumDnsEntries = last;
4465 }
4466
Paul Jensen3d194ea2015-06-16 14:27:36 -04004467 /**
4468 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4469 * augmented with any stateful capabilities implied from {@code networkAgent}
4470 * (e.g., validated status and captive portal status).
4471 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004472 * @param oldScore score of the network before any of the changes that prompted us
4473 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004474 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004475 * @param networkCapabilities the new network capabilities.
4476 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004477 private void updateCapabilities(
4478 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004479 // Don't modify caller's NetworkCapabilities.
4480 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004481 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004482 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4483 } else {
4484 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4485 }
Paul Jensene0988542015-06-25 15:30:08 -04004486 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004487 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4488 } else {
4489 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4490 }
Paul Jensene0988542015-06-25 15:30:08 -04004491 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
Paul Jensen487ffe72015-07-24 15:57:11 -04004492 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4493 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4494 try {
4495 mNetd.setNetworkPermission(nai.network.netId,
4496 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4497 null : NetworkManagementService.PERMISSION_SYSTEM);
4498 } catch (RemoteException e) {
4499 loge("Exception in setNetworkPermission: " + e);
4500 }
4501 }
Paul Jensene0988542015-06-25 15:30:08 -04004502 synchronized (nai) {
4503 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004504 }
Paul Jensene0988542015-06-25 15:30:08 -04004505 rematchAllNetworksAndRequests(nai, oldScore);
4506 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004507 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004508 }
4509
Paul Jensenc8b9a742014-09-30 15:37:41 -04004510 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004511 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4512 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004513 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004514 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004515 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4516 }
4517 }
4518
Robert Greenwalt7b816022014-04-18 15:25:25 -07004519 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4520 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004521 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004522 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4523 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004524 }
4525 }
4526
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004527 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4528 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004529 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004530 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004531 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4532 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004533 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004534 sendIntent(nri.mPendingIntent, intent);
4535 }
4536 // else not handled
4537 }
4538
4539 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4540 mPendingIntentWakeLock.acquire();
4541 try {
4542 if (DBG) log("Sending " + pendingIntent);
4543 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4544 } catch (PendingIntent.CanceledException e) {
4545 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4546 mPendingIntentWakeLock.release();
4547 releasePendingNetworkRequest(pendingIntent);
4548 }
4549 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4550 }
4551
4552 @Override
4553 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4554 String resultData, Bundle resultExtras) {
4555 if (DBG) log("Finished sending " + pendingIntent);
4556 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004557 // Release with a delay so the receiving client has an opportunity to put in its
4558 // own request.
4559 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004560 }
4561
Robert Greenwalt9258c642014-03-26 16:47:06 -07004562 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004563 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004564 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004565 Bundle bundle = new Bundle();
4566 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4567 new NetworkRequest(nri.request));
4568 Message msg = Message.obtain();
4569 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4570 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4571 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4572 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004573 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004574 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004575 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004576 break;
4577 }
4578 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4579 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4580 new NetworkCapabilities(networkAgent.networkCapabilities));
4581 break;
4582 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004583 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004584 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4585 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004586 break;
4587 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004588 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004589 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004590 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004591 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004592 if (VDBG) {
4593 log("sending notification " + notifyTypeToName(notificationType) +
4594 " for " + nri.request);
4595 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004596 nri.messenger.send(msg);
4597 } catch (RemoteException e) {
4598 // may occur naturally in the race of binder death.
4599 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4600 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004601 }
4602
Paul Jensenc8b9a742014-09-30 15:37:41 -04004603 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004604 if (nai.numRequestNetworkRequests() != 0) {
4605 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4606 NetworkRequest nr = nai.requestAt(i);
4607 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004608 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004609 loge("Dead network still had at least " + nr);
4610 break;
4611 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004612 }
4613 nai.asyncChannel.disconnect();
4614 }
4615
Robert Greenwalt7b816022014-04-18 15:25:25 -07004616 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4617 if (oldNetwork == null) {
4618 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4619 return;
4620 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004621 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004622
4623 // If we get here it means that the last linger timeout for this network expired. So there
4624 // must be no other active linger timers, and we must stop lingering.
4625 oldNetwork.clearLingerState();
4626
4627 if (unneeded(oldNetwork)) {
4628 teardownUnneededNetwork(oldNetwork);
4629 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004630 }
4631
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004632 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004633 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004634 setupDataActivityTracking(newNetwork);
4635 try {
4636 mNetd.setDefaultNetId(newNetwork.network.netId);
4637 } catch (Exception e) {
4638 loge("Exception setting default network :" + e);
4639 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004640 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004641 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004642 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004643 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004644 }
4645
Paul Jensen2161a8e2014-09-11 11:00:39 -04004646 // Handles a network appearing or improving its score.
4647 //
4648 // - Evaluates all current NetworkRequests that can be
4649 // satisfied by newNetwork, and reassigns to newNetwork
4650 // any such requests for which newNetwork is the best.
4651 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004652 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004653 // needed. A network is needed if it is the best network for
4654 // one or more NetworkRequests, or if it is a VPN.
4655 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004656 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004657 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004658 //
4659 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4660 // networks that have no chance (i.e. even if validated)
4661 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004662 //
4663 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4664 // it does not remove NetworkRequests that other Networks could better satisfy.
4665 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4666 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4667 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004668 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004669 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004670 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4671 // performed to tear down unvalidated networks that have no chance (i.e. even if
4672 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004673 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004674 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004675 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004676 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004677 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004678 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004679 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004680 // Find and migrate to this Network any NetworkRequests for
4681 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004682 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004683 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004684 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004685 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004686 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4687 final boolean satisfies = newNetwork.satisfies(nri.request);
4688 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004689 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004690 log("Network " + newNetwork.name() + " was already satisfying" +
4691 " request " + nri.request.requestId + ". No change.");
4692 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004693 keep = true;
4694 continue;
4695 }
4696
4697 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004698 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004699 if (satisfies) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004700 if (nri.request.isListen()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004701 // This is not a request, it's a callback listener.
4702 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004703 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004704 continue;
4705 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004706
Robert Greenwalt7b816022014-04-18 15:25:25 -07004707 // next check if it's better than any current network we're using for
4708 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004709 if (VDBG) {
4710 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004711 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4712 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004713 }
4714 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004715 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004716 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004717 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004718 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004719 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004720 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004721 affectedNetworks.add(currentNetwork);
4722 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004723 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004724 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004725 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004726 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004727 if (!newNetwork.addRequest(nri.request)) {
4728 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4729 }
4730 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004731 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004732 // Tell NetworkFactories about the new score, so they can stop
4733 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004734 // TODO - this could get expensive if we have alot of requests for this
4735 // network. Think about if there is a way to reduce this. Push
4736 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004737 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004738 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004739 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004740 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004741 if (currentNetwork != null) {
4742 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4743 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004744 }
4745 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004746 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004747 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4748 // mark it as no longer satisfying "nri". Because networks are processed by
4749 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4750 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4751 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4752 // This means this code doesn't have to handle the case where "currentNetwork" no
4753 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4754 if (DBG) {
4755 log("Network " + newNetwork.name() + " stopped satisfying" +
4756 " request " + nri.request.requestId);
4757 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004758 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004759 if (currentNetwork == newNetwork) {
4760 mNetworkForRequestId.remove(nri.request.requestId);
4761 sendUpdatedScoreToFactories(nri.request, 0);
4762 } else {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004763 if (nri.request.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004764 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4765 newNetwork.name() +
4766 " without updating mNetworkForRequestId or factories!");
4767 }
4768 }
4769 // TODO: technically, sending CALLBACK_LOST here is
4770 // incorrect if nri is a request (not a listen) and there
4771 // is a replacement network currently connected that can
4772 // satisfy it. However, the only capability that can both
4773 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4774 // so this code is only incorrect for a network that loses
4775 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004776 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004777 }
4778 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004779 if (isNewDefault) {
4780 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004781 makeDefault(newNetwork);
4782 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4783 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004784 synchronized (ConnectivityService.this) {
4785 // have a new default network, release the transition wakelock in
4786 // a second if it's held. The second pause is to allow apps
4787 // to reconnect over the new network
4788 if (mNetTransitionWakeLock.isHeld()) {
4789 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4790 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4791 mNetTransitionWakeLockSerialNumber, 0),
4792 1000);
4793 }
4794 }
4795 }
4796
4797 // do this after the default net is switched, but
4798 // before LegacyTypeTracker sends legacy broadcasts
4799 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4800
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004801 // Linger any networks that are no longer needed. This should be done after sending the
4802 // available callback for newNetwork.
4803 for (NetworkAgentInfo nai : affectedNetworks) {
4804 updateLingerState(nai, now);
4805 }
4806 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4807 // does not need to be done in any particular order.
4808 updateLingerState(newNetwork, now);
4809
Paul Jensencf4c2c62015-07-01 14:16:32 -04004810 if (isNewDefault) {
4811 // Maintain the illusion: since the legacy API only
4812 // understands one network at a time, we must pretend
4813 // that the current default network disconnected before
4814 // the new one connected.
4815 if (oldDefaultNetwork != null) {
4816 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4817 oldDefaultNetwork, true);
4818 }
4819 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4820 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4821 notifyLockdownVpn(newNetwork);
4822 }
4823
Robert Greenwalt7b816022014-04-18 15:25:25 -07004824 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004825 // Notify battery stats service about this network, both the normal
4826 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004827 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004828 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004829 final IBatteryStats bs = BatteryStatsService.getService();
4830 final int type = newNetwork.networkInfo.getType();
4831
4832 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4833 bs.noteNetworkInterfaceType(baseIface, type);
4834 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4835 final String stackedIface = stacked.getInterfaceName();
4836 bs.noteNetworkInterfaceType(stackedIface, type);
4837 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4838 }
4839 } catch (RemoteException ignored) {
4840 }
4841
Robert Greenwalt152ed372014-12-17 17:19:53 -08004842 // This has to happen after the notifyNetworkCallbacks as that tickles each
4843 // ConnectivityManager instance so that legacy requests correctly bind dns
4844 // requests to this network. The legacy users are listening for this bcast
4845 // and will generally do a dns request so they can ensureRouteToHost and if
4846 // they do that before the callbacks happen they'll use the default network.
4847 //
4848 // TODO: Is there still a race here? We send the broadcast
4849 // after sending the callback, but if the app can receive the
4850 // broadcast before the callback, it might still break.
4851 //
4852 // This *does* introduce a race where if the user uses the new api
4853 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4854 // they may get old info. Reverse this after the old startUsing api is removed.
4855 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004856 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4857 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004858 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004859 // legacy type tracker filters out repeat adds
4860 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4861 }
4862 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004863
4864 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4865 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4866 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4867 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4868 if (newNetwork.isVPN()) {
4869 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4870 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004871 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004872 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4873 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004874 if (unneeded(nai)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004875 if (nai.getLingerExpiry() > 0) {
4876 // This network has active linger timers and no requests, but is not
4877 // lingering. Linger it.
4878 //
4879 // One way (the only way?) this can happen if this network is unvalidated
4880 // and became unneeded due to another network improving its score to the
4881 // point where this network will no longer be able to satisfy any requests
4882 // even if it validates.
4883 updateLingerState(nai, now);
4884 } else {
4885 if (DBG) log("Reaping " + nai.name());
4886 teardownUnneededNetwork(nai);
4887 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004888 }
4889 }
4890 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004891 }
4892
Paul Jensen1c7ba022015-06-16 14:27:36 -04004893 /**
4894 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4895 * being disconnected.
4896 * @param changed If only one Network's score or capabilities have been modified since the last
4897 * time this function was called, pass this Network in this argument, otherwise pass
4898 * null.
4899 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4900 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4901 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4902 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4903 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004904 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004905 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004906 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4907 // to avoid the slowness. It is not simply enough to process just "changed", for
4908 // example in the case where "changed"'s score decreases and another network should begin
4909 // satifying a NetworkRequest that "changed" currently satisfies.
4910
4911 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4912 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4913 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004914 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04004915 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004916 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004917 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004918 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4919 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4920 // Rematch higher scoring networks first to prevent requests first matching a lower
4921 // scoring network and then a higher scoring network, which could produce multiple
4922 // callbacks and inadvertently unlinger networks.
4923 Arrays.sort(nais);
4924 for (NetworkAgentInfo nai : nais) {
4925 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004926 // Only reap the last time through the loop. Reaping before all rematching
4927 // is complete could incorrectly teardown a network that hasn't yet been
4928 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004929 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004930 : ReapUnvalidatedNetworks.REAP,
4931 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004932 }
4933 }
4934 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004935
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004936 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004937 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004938 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004939 // For now only update icons for default connection.
4940 // TODO: Update WiFi and cellular icons separately. b/17237507
4941 if (!isDefaultNetwork(nai)) return;
4942
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004943 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004944 // Don't repeat publish.
4945 if (newInetCondition == mDefaultInetConditionPublished) return;
4946
4947 mDefaultInetConditionPublished = newInetCondition;
4948 sendInetConditionBroadcast(nai.networkInfo);
4949 }
4950
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004951 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4952 if (mLockdownTracker != null) {
4953 if (nai != null && nai.isVPN()) {
4954 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4955 } else {
4956 mLockdownTracker.onNetworkInfoChanged();
4957 }
4958 }
4959 }
4960
Robert Greenwalt7b816022014-04-18 15:25:25 -07004961 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4962 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004963 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004964 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004965 synchronized (networkAgent) {
4966 oldInfo = networkAgent.networkInfo;
4967 networkAgent.networkInfo = newInfo;
4968 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004969 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004970
4971 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004972 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4973 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4974 notifyIfacesChangedForNetworkStats();
4975 } else if (VDBG) log("ignoring duplicate network state non-change");
4976 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004977 return;
4978 }
4979 if (DBG) {
4980 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4981 (oldInfo == null ? "null" : oldInfo.getState()) +
4982 " to " + state);
4983 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004984
Robin Lee585e2482016-05-01 23:00:00 +01004985 if (!networkAgent.created
4986 && (state == NetworkInfo.State.CONNECTED
4987 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004988 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004989 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004990 if (networkAgent.isVPN()) {
4991 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004992 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4993 (networkAgent.networkMisc == null ||
4994 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004995 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004996 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4997 networkAgent.networkCapabilities.hasCapability(
4998 NET_CAPABILITY_NOT_RESTRICTED) ?
4999 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005000 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005001 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005002 loge("Error creating network " + networkAgent.network.netId + ": "
5003 + e.getMessage());
5004 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005005 }
Paul Jenseneec75412014-08-04 12:21:19 -04005006 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005007 }
5008
5009 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5010 networkAgent.everConnected = true;
5011
Robert Greenwalt7b816022014-04-18 15:25:25 -07005012 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005013 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005014
Paul Jensenca8f16a2014-05-09 12:47:55 -04005015 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005016 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005017
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005018 if (networkAgent.isVPN()) {
5019 // Temporarily disable the default proxy (not global).
5020 synchronized (mProxyLock) {
5021 if (!mDefaultProxyDisabled) {
5022 mDefaultProxyDisabled = true;
5023 if (mGlobalProxy == null && mDefaultProxy != null) {
5024 sendProxyBroadcast(null);
5025 }
5026 }
5027 }
5028 // TODO: support proxy per network.
5029 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005030
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005031 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5032 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5033 // capabilities, so it only needs to be done once on initial connect, not every time the
5034 // network's capabilities change. Note that we do this before rematching the network,
5035 // so we could decide to tear it down immediately afterwards. That's fine though - on
5036 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5037 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005038 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005039
Paul Jensen2161a8e2014-09-11 11:00:39 -04005040 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005041 final long now = SystemClock.elapsedRealtime();
5042 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005043
5044 // This has to happen after matching the requests, because callbacks are just requests.
5045 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005046 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005047 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005048 if (networkAgent.isVPN()) {
5049 synchronized (mProxyLock) {
5050 if (mDefaultProxyDisabled) {
5051 mDefaultProxyDisabled = false;
5052 if (mGlobalProxy == null && mDefaultProxy != null) {
5053 sendProxyBroadcast(mDefaultProxy);
5054 }
5055 }
5056 }
5057 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005058 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5059 state == NetworkInfo.State.SUSPENDED) {
5060 // going into or coming out of SUSPEND: rescore and notify
5061 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005062 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005063 }
5064 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5065 ConnectivityManager.CALLBACK_SUSPENDED :
5066 ConnectivityManager.CALLBACK_RESUMED));
5067 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005068 }
5069 }
5070
Robert Greenwaltac96c522014-06-03 16:43:57 -07005071 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005072 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005073 if (score < 0) {
5074 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5075 "). Bumping score to min of 0");
5076 score = 0;
5077 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005078
Paul Jensen2161a8e2014-09-11 11:00:39 -04005079 final int oldScore = nai.getCurrentScore();
5080 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005081
Paul Jensen85cf78e2015-06-25 13:25:07 -04005082 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005083
Paul Jensenc8b9a742014-09-30 15:37:41 -04005084 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005085 }
5086
Robert Greenwalt9258c642014-03-26 16:47:06 -07005087 // notify only this one new request of the current state
5088 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5089 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005090 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005091 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005092 } else {
5093 sendPendingIntentForRequest(nri, nai, notifyType);
5094 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005095 }
5096
Robert Greenwalt8d482522015-06-24 13:23:42 -07005097 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005098 // The NetworkInfo we actually send out has no bearing on the real
5099 // state of affairs. For example, if the default connection is mobile,
5100 // and a request for HIPRI has just gone away, we need to pretend that
5101 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5102 // the state to DISCONNECTED, even though the network is of type MOBILE
5103 // and is still connected.
5104 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5105 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005106 if (state != DetailedState.DISCONNECTED) {
5107 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005108 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005109 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005110 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005111 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5112 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5113 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5114 if (info.isFailover()) {
5115 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5116 nai.networkInfo.setFailover(false);
5117 }
5118 if (info.getReason() != null) {
5119 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5120 }
5121 if (info.getExtraInfo() != null) {
5122 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5123 }
5124 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005125 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005126 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005127 if (newDefaultAgent != null) {
5128 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5129 newDefaultAgent.networkInfo);
5130 } else {
5131 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5132 }
5133 }
5134 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5135 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005136 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005137 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005138 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005139 }
5140 }
5141 }
5142
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005143 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005144 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005145 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5146 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005147 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5148 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005149 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005150 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005151 } else {
5152 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5153 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005154 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005155 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005156
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005157 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5158 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5159 }
5160
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005161 private String notifyTypeToName(int notifyType) {
5162 switch (notifyType) {
5163 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5164 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5165 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5166 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5167 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5168 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5169 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5170 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5171 }
5172 return "UNKNOWN";
5173 }
5174
Jeff Sharkey69736342014-12-08 14:50:12 -08005175 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005176 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5177 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005178 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005179 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005180 try {
5181 mStatsService.forceUpdateIfaces();
5182 } catch (Exception ignored) {
5183 }
5184 }
5185
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005186 @Override
5187 public boolean addVpnAddress(String address, int prefixLength) {
5188 throwIfLockdownEnabled();
5189 int user = UserHandle.getUserId(Binder.getCallingUid());
5190 synchronized (mVpns) {
5191 return mVpns.get(user).addAddress(address, prefixLength);
5192 }
5193 }
5194
5195 @Override
5196 public boolean removeVpnAddress(String address, int prefixLength) {
5197 throwIfLockdownEnabled();
5198 int user = UserHandle.getUserId(Binder.getCallingUid());
5199 synchronized (mVpns) {
5200 return mVpns.get(user).removeAddress(address, prefixLength);
5201 }
5202 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005203
5204 @Override
5205 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5206 throwIfLockdownEnabled();
5207 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005208 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005209 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005210 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005211 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005212 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005213 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005214 }
5215 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005216 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005217
5218 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005219 public String getCaptivePortalServerUrl() {
5220 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5221 }
5222
5223 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005224 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5225 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5226 enforceKeepalivePermission();
5227 mKeepaliveTracker.startNattKeepalive(
5228 getNetworkAgentInfoForNetwork(network),
5229 intervalSeconds, messenger, binder,
5230 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5231 }
5232
5233 @Override
5234 public void stopKeepalive(Network network, int slot) {
5235 mHandler.sendMessage(mHandler.obtainMessage(
5236 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5237 }
5238
5239 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005240 public void factoryReset() {
5241 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005242
5243 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5244 return;
5245 }
5246
Robin Lee3b3dd942015-05-12 18:14:58 +01005247 final int userId = UserHandle.getCallingUserId();
5248
Stuart Scottf1fb3972015-04-02 18:00:02 -07005249 // Turn airplane mode off
5250 setAirplaneMode(false);
5251
Stuart Scotte3e314d2015-04-20 14:07:45 -07005252 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5253 // Untether
5254 for (String tether : getTetheredIfaces()) {
5255 untether(tether);
5256 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005257 }
5258
Stuart Scotte3e314d2015-04-20 14:07:45 -07005259 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005260 // Remove always-on package
5261 synchronized (mVpns) {
5262 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5263 if (alwaysOnPackage != null) {
5264 setAlwaysOnVpnPackage(userId, null, false);
5265 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5266 }
5267 }
5268
Stuart Scotte3e314d2015-04-20 14:07:45 -07005269 // Turn VPN off
5270 VpnConfig vpnConfig = getVpnConfig(userId);
5271 if (vpnConfig != null) {
5272 if (vpnConfig.legacy) {
5273 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5274 } else {
5275 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5276 // in the future without user intervention.
5277 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005278
Victor Changb04a5ea2016-05-30 20:36:30 +01005279 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005280 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005281 }
5282 }
5283 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005284
5285 @VisibleForTesting
5286 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5287 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5288 return new NetworkMonitor(context, handler, nai, defaultRequest);
5289 }
Erik Kline48f12f22016-04-14 17:30:59 +09005290
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005291 @VisibleForTesting
5292 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5293 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5294 }
5295
Hugo Benichicfddd682016-05-31 16:28:06 +09005296 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005297 int newNetid = NETID_UNSET;
5298 int prevNetid = NETID_UNSET;
5299 int[] transports = new int[0];
5300 boolean hadIPv4 = false;
5301 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005302
Hugo Benichi5f16f762016-04-20 12:09:33 +09005303 if (newNai != null) {
5304 newNetid = newNai.network.netId;
5305 transports = newNai.networkCapabilities.getTransportTypes();
5306 }
5307 if (prevNai != null) {
5308 prevNetid = prevNai.network.netId;
5309 final LinkProperties lp = prevNai.linkProperties;
5310 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5311 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5312 }
5313
Hugo Benichicfddd682016-05-31 16:28:06 +09005314 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5315 }
5316
5317 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5318 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320}