blob: b08549f7d3f835cabe72338880e0a184ffcbb407 [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
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001541 public void onUidPoliciesChanged(int uid, int uidPolicies) {
1542 // caller is NPMS, since we only register with them
Felipe Leme019fcd22016-04-19 10:24:39 -07001543 if (LOGD_RULES) {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001544 log("onUidRulesChanged(uid=" + uid + ", uidPolicies=" + uidPolicies + ")");
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001545 }
1546 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001547 };
1548
Robin Lee3b3dd942015-05-12 18:14:58 +01001549 /**
1550 * Require that the caller is either in the same user or has appropriate permission to interact
1551 * across users.
1552 *
1553 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1554 */
1555 private void enforceCrossUserPermission(int userId) {
1556 if (userId == UserHandle.getCallingUserId()) {
1557 // Not a cross-user call.
1558 return;
1559 }
1560 mContext.enforceCallingOrSelfPermission(
1561 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1562 "ConnectivityService");
1563 }
1564
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001565 private void enforceInternetPermission() {
1566 mContext.enforceCallingOrSelfPermission(
1567 android.Manifest.permission.INTERNET,
1568 "ConnectivityService");
1569 }
1570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001572 mContext.enforceCallingOrSelfPermission(
1573 android.Manifest.permission.ACCESS_NETWORK_STATE,
1574 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
1576
1577 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001578 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001581 private void enforceTetherAccessPermission() {
1582 mContext.enforceCallingOrSelfPermission(
1583 android.Manifest.permission.ACCESS_NETWORK_STATE,
1584 "ConnectivityService");
1585 }
1586
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001587 private void enforceConnectivityInternalPermission() {
1588 mContext.enforceCallingOrSelfPermission(
1589 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1590 "ConnectivityService");
1591 }
1592
Hugo Benichi514da602016-07-19 15:59:27 +09001593 private void enforceConnectivityRestrictedNetworksPermission() {
1594 try {
1595 mContext.enforceCallingOrSelfPermission(
1596 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1597 "ConnectivityService");
1598 return;
1599 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1600 enforceConnectivityInternalPermission();
1601 }
1602
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001603 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001604 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001605 }
1606
Lorenzo Colitti18660282016-07-04 12:55:44 +09001607 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001608 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001609 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001610 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001611 }
1612
1613 private void sendInetConditionBroadcast(NetworkInfo info) {
1614 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1615 }
1616
Wink Saville628b0852011-08-04 15:01:58 -07001617 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001618 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001619 info = new NetworkInfo(info);
1620 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001621 }
1622
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001623 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001624 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001625 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 if (info.isFailover()) {
1627 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1628 info.setFailover(false);
1629 }
1630 if (info.getReason() != null) {
1631 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1632 }
1633 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001634 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1635 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001637 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001638 return intent;
1639 }
1640
1641 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1642 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1643 }
1644
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001645 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001646 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1647 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1648 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001649 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001650 final long ident = Binder.clearCallingIdentity();
1651 try {
1652 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1653 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1654 } finally {
1655 Binder.restoreCallingIdentity(ident);
1656 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001657 }
1658
Mike Lockwood0f79b542009-08-14 14:18:49 -04001659 private void sendStickyBroadcast(Intent intent) {
1660 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001661 if (!mSystemReady) {
1662 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001663 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001664 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001665 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001666 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001667 }
1668
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001669 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001670 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001671 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001672 final NetworkInfo ni = intent.getParcelableExtra(
1673 ConnectivityManager.EXTRA_NETWORK_INFO);
1674 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1675 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1676 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001677 } else {
1678 BroadcastOptions opts = BroadcastOptions.makeBasic();
1679 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1680 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001681 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001682 final IBatteryStats bs = BatteryStatsService.getService();
1683 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001684 bs.noteConnectivityChanged(intent.getIntExtra(
1685 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1686 ni != null ? ni.getState().toString() : "?");
1687 } catch (RemoteException e) {
1688 }
1689 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001690 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001691 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001692 } finally {
1693 Binder.restoreCallingIdentity(ident);
1694 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001695 }
1696 }
1697
1698 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001699 loadGlobalProxy();
1700
Mike Lockwood0f79b542009-08-14 14:18:49 -04001701 synchronized(this) {
1702 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001703 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001704 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001705 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001706 }
1707 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001708 // load the global proxy at startup
1709 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001710
Robin Lee244ce8e2016-01-05 18:03:46 +00001711 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1712 // for user to unlock device too.
1713 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001714
Erik Klineda4bfa82015-04-30 12:58:40 +09001715 // Configure whether mobile data is always on.
1716 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1717
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001718 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001719
1720 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 }
1722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001724 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001725 *
1726 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001727 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001728 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001729 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1730 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001731
1732 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001733 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001734
Robert Greenwalt7b816022014-04-18 15:25:25 -07001735 if (networkAgent.networkCapabilities.hasTransport(
1736 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001737 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1738 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001739 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001740 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001741 } else if (networkAgent.networkCapabilities.hasTransport(
1742 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001743 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1744 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001745 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001746 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001747 } else {
1748 // do not track any other networks
1749 timeout = 0;
1750 }
1751
Robert Greenwalt7b816022014-04-18 15:25:25 -07001752 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001753 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001754 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001755 } catch (Exception e) {
1756 // You shall not crash!
1757 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001758 }
1759 }
1760 }
1761
1762 /**
1763 * Remove data activity tracking when network disconnects.
1764 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001765 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1766 final String iface = networkAgent.linkProperties.getInterfaceName();
1767 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001768
Robert Greenwalt7b816022014-04-18 15:25:25 -07001769 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1770 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001771 try {
1772 // the call fails silently if no idletimer setup for this interface
1773 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001774 } catch (Exception e) {
1775 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001776 }
1777 }
1778 }
1779
1780 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001781 * Reads the network specific MTU size from reources.
1782 * and set it on it's iface.
1783 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001784 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1785 final String iface = newLp.getInterfaceName();
1786 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001787 if (oldLp == null && mtu == 0) {
1788 // Silently ignore unset MTU value.
1789 return;
1790 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001791 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1792 if (VDBG) log("identical MTU - not setting");
1793 return;
1794 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001795 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001796 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001797 return;
1798 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001799
w1997615afd812014-08-05 15:18:11 -07001800 // Cannot set MTU without interface name
1801 if (TextUtils.isEmpty(iface)) {
1802 loge("Setting MTU size with null iface.");
1803 return;
1804 }
1805
Robert Greenwalt7b816022014-04-18 15:25:25 -07001806 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001807 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001808 mNetd.setMtu(iface, mtu);
1809 } catch (Exception e) {
1810 Slog.e(TAG, "exception in setMtu()" + e);
1811 }
1812 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001813
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001814 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001815 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1816
1817 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001818 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001819 protected int getDefaultTcpRwnd() {
1820 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1821 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001822
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001823 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1824 if (isDefaultNetwork(nai) == false) {
1825 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001826 }
1827
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001828 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1829 String[] values = null;
1830 if (tcpBufferSizes != null) {
1831 values = tcpBufferSizes.split(",");
1832 }
1833
1834 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001835 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001836 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1837 values = tcpBufferSizes.split(",");
1838 }
1839
1840 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1841
1842 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001843 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001844
1845 final String prefix = "/sys/kernel/ipv4/tcp_";
1846 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1847 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1848 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1849 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1850 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1851 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1852 mCurrentTcpBufferSizes = tcpBufferSizes;
1853 } catch (IOException e) {
1854 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001855 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001856
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001857 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001858 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001859 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1860 if (rwndValue != 0) {
1861 SystemProperties.set(sysctlKey, rwndValue.toString());
1862 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001863 }
1864
Mattias Falk8b47b362011-08-23 14:15:13 +02001865 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001866 /*
1867 * Tell the VMs to toss their DNS caches
1868 */
1869 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1870 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001871 /*
1872 * Connectivity events can happen before boot has completed ...
1873 */
1874 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001875 final long ident = Binder.clearCallingIdentity();
1876 try {
1877 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1878 } finally {
1879 Binder.restoreCallingIdentity(ident);
1880 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001881 }
1882
Robert Greenwalt562cc542014-05-15 18:07:26 -07001883 @Override
1884 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001885 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1886 NETWORK_RESTORE_DELAY_PROP_NAME);
1887 if(restoreDefaultNetworkDelayStr != null &&
1888 restoreDefaultNetworkDelayStr.length() != 0) {
1889 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001890 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001891 } catch (NumberFormatException e) {
1892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001894 // if the system property isn't set, use the value for the apn type
1895 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1896
1897 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1898 (mNetConfigs[networkType] != null)) {
1899 ret = mNetConfigs[networkType].restoreTime;
1900 }
1901 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001904 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001905 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001906 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001907 }
1908 return false;
1909 }
1910
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001911 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1912 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1913 final long DIAG_TIME_MS = 5000;
1914 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1915 // Start gathering diagnostic information.
1916 netDiags.add(new NetworkDiagnostics(
1917 nai.network,
1918 new LinkProperties(nai.linkProperties), // Must be a copy.
1919 DIAG_TIME_MS));
1920 }
1921
1922 for (NetworkDiagnostics netDiag : netDiags) {
1923 pw.println();
1924 netDiag.waitForMeasurements();
1925 netDiag.dump(pw);
1926 }
1927 }
1928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001930 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1931 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001932 if (mContext.checkCallingOrSelfPermission(
1933 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001935 pw.println("Permission Denial: can't dump ConnectivityService " +
1936 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1937 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 return;
1939 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001940
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001941 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001942 dumpNetworkDiagnostics(pw);
1943 return;
1944 }
Erik Kline379747a2015-06-05 17:47:34 +09001945
Lorenzo Colittie3805462015-06-03 11:18:24 +09001946 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001947 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001948 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001949 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001950 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001951 pw.println();
1952
Paul Jensen85cf78e2015-06-25 13:25:07 -04001953 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001954 pw.print("Active default network: ");
1955 if (defaultNai == null) {
1956 pw.println("none");
1957 } else {
1958 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001960 pw.println();
1961
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001962 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001963 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001964 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1965 pw.println(nai.toString());
1966 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001967 pw.println(String.format("Requests: %d request/%d total",
1968 nai.numRequestNetworkRequests(), nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001969 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001970 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1971 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001972 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001973 pw.decreaseIndent();
1974 pw.println("Lingered:");
1975 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001976 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001977 pw.decreaseIndent();
1978 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001979 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001980 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001981 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001982
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001983 pw.println("Metered Interfaces:");
1984 pw.increaseIndent();
1985 for (String value : mMeteredIfaces) {
1986 pw.println(value);
1987 }
1988 pw.decreaseIndent();
1989 pw.println();
1990
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001991 pw.print("Restrict background: ");
1992 pw.println(mRestrictBackground);
1993 pw.println();
1994
Felipe Leme46c4fc32016-05-04 09:21:43 -07001995 pw.println("Status for known UIDs:");
1996 pw.increaseIndent();
1997 final int size = mUidRules.size();
1998 for (int i = 0; i < size; i++) {
1999 final int uid = mUidRules.keyAt(i);
2000 pw.print("UID=");
2001 pw.print(uid);
2002 final int uidRules = mUidRules.get(uid, RULE_NONE);
2003 pw.print(" rules=");
2004 pw.print(uidRulesToString(uidRules));
2005 pw.println();
2006 }
2007 pw.println();
2008 pw.decreaseIndent();
2009
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002010 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002011 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002012 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2013 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002014 }
2015 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002016 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002017
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002018 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002019
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002020 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002021 pw.print("mNetTransitionWakeLock: currently " +
2022 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2023 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2024 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2025 } else {
2026 pw.println(", last requested never");
2027 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002028 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002029
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002030 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002031 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002032
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002033 pw.println();
2034 mKeepaliveTracker.dump(pw);
2035
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002036 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002037
Lorenzo Colittie3805462015-06-03 11:18:24 +09002038 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002039 pw.println();
2040 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002041 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002042 for(int i = 0; i < mInetLog.size(); i++) {
2043 pw.println(mInetLog.get(i));
2044 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002045 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002046 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002047
2048 if (argsContain(args, "--short") == false) {
2049 pw.println();
2050 synchronized (mValidationLogs) {
2051 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002052 for (ValidationLog p : mValidationLogs) {
2053 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002054 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002055 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002056 pw.decreaseIndent();
2057 }
2058 }
Erik Kline7523eb32015-07-09 18:24:03 +09002059
2060 pw.println();
2061 pw.println("mNetworkRequestInfoLogs (most recent first):");
2062 pw.increaseIndent();
2063 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2064 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002065
2066 pw.println();
2067 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2068 pw.increaseIndent();
2069 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2070 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002074 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002075 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002076 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002077 if (officialNai != null && officialNai.equals(nai)) return true;
2078 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002079 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002080 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002081 " - " + nai);
2082 }
2083 return false;
2084 }
2085
Robert Greenwalt42acef32009-08-12 16:08:25 -07002086 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002087 private class NetworkStateTrackerHandler extends Handler {
2088 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002089 super(looper);
2090 }
2091
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002092 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002094 default:
2095 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002096 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002097 handleAsyncChannelHalfConnect(msg);
2098 break;
2099 }
2100 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2101 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2102 if (nai != null) nai.asyncChannel.disconnect();
2103 break;
2104 }
2105 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2106 handleAsyncChannelDisconnected(msg);
2107 break;
2108 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002109 }
2110 return true;
2111 }
2112
2113 private void maybeHandleNetworkAgentMessage(Message msg) {
2114 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2115 if (nai == null) {
2116 if (VDBG) {
2117 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2118 log(String.format("%s from unknown NetworkAgent", what));
2119 }
2120 return;
2121 }
2122
2123 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002124 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002125 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2126 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2127 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2128 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002129 }
Robin Lee585e2482016-05-01 23:00:00 +01002130 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002131 networkCapabilities)) {
2132 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2133 + nai.networkCapabilities + " -> " + networkCapabilities);
2134 }
2135 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002136 break;
2137 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002138 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002139 if (VDBG) {
2140 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002141 "; created=" + nai.created +
2142 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002144 LinkProperties oldLp = nai.linkProperties;
2145 synchronized (nai) {
2146 nai.linkProperties = (LinkProperties)msg.obj;
2147 }
Robin Lee585e2482016-05-01 23:00:00 +01002148 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002149 break;
2150 }
2151 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002152 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002153 updateNetworkInfo(nai, info);
2154 break;
2155 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002156 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002157 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002158 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002159 break;
2160 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002161 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002162 try {
2163 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002164 } catch (Exception e) {
2165 // Never crash!
2166 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002167 }
2168 break;
2169 }
2170 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002171 try {
2172 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002173 } catch (Exception e) {
2174 // Never crash!
2175 loge("Exception in removeVpnUidRanges: " + e);
2176 }
2177 break;
2178 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002179 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002180 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2181 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002182 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002183 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002184 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002185 break;
2186 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002187 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002188 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2189 break;
2190 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002191 }
2192 }
2193
2194 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2195 switch (msg.what) {
2196 default:
2197 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002198 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002199 final NetworkAgentInfo nai;
2200 synchronized (mNetworkForNetId) {
2201 nai = mNetworkForNetId.get(msg.arg2);
2202 }
2203 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002204 final boolean valid =
2205 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002206 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2207 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002208 if (valid != nai.lastValidated) {
2209 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002210 nai.lastValidated = valid;
2211 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002212 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002213 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2214 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002215 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002216 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002217 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002218 Bundle redirectUrlBundle = new Bundle();
2219 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002220 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002221 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002222 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002223 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002224 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002225 break;
2226 }
Paul Jensen869868be2014-05-15 10:33:05 -04002227 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002228 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002229 final boolean visible = (msg.arg1 != 0);
2230 final NetworkAgentInfo nai;
2231 synchronized (mNetworkForNetId) {
2232 nai = mNetworkForNetId.get(netId);
2233 }
2234 // If captive portal status has changed, update capabilities.
2235 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2236 nai.lastCaptivePortalDetected = visible;
2237 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002238 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002239 }
2240 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002241 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002242 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002243 if (nai == null) {
2244 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2245 break;
2246 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002247 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002248 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002249 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002250 }
Paul Jensen869868be2014-05-15 10:33:05 -04002251 }
Paul Jensen869868be2014-05-15 10:33:05 -04002252 break;
2253 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002254 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002255 return true;
2256 }
2257
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002258 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2259 switch (msg.what) {
2260 default:
2261 return false;
2262 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2263 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2264 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2265 handleLingerComplete(nai);
2266 }
2267 break;
2268 }
2269 }
2270 return true;
2271 }
2272
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002273 @Override
2274 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002275 if (!maybeHandleAsyncChannelMessage(msg) &&
2276 !maybeHandleNetworkMonitorMessage(msg) &&
2277 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002278 maybeHandleNetworkAgentMessage(msg);
2279 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002280 }
2281 }
2282
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002283 private void updateLingerState(NetworkAgentInfo nai, long now) {
2284 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2285 // 2. If the network was lingering and there are now requests, unlinger it.
2286 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2287 // one lingered request, start lingering.
2288 nai.updateLingerTimer();
2289 if (nai.isLingering() && nai.numRequestNetworkRequests() > 0) {
2290 if (DBG) log("Unlingering " + nai.name());
2291 nai.unlinger();
2292 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
2293 } else if (unneeded(nai) && nai.getLingerExpiry() > 0) { // unneeded() calls isLingering()
2294 int lingerTime = (int) (nai.getLingerExpiry() - now);
2295 if (DBG) {
2296 Log.d(TAG, "Lingering " + nai.name() + " for " + lingerTime + "ms");
2297 }
2298 nai.linger();
2299 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2300 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2301 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002302 }
2303
Robert Greenwalt7b816022014-04-18 15:25:25 -07002304 private void handleAsyncChannelHalfConnect(Message msg) {
2305 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002306 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002307 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2308 if (VDBG) log("NetworkFactory connected");
2309 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002310 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002311 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002312 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002313 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002314 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002315 }
2316 } else {
2317 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002318 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002319 }
2320 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2321 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2322 if (VDBG) log("NetworkAgent connected");
2323 // A network agent has requested a connection. Establish the connection.
2324 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2325 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2326 } else {
2327 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002328 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002329 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002330 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002331 synchronized (mNetworkForNetId) {
2332 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002333 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002334 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002335 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002336 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002337 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002338 }
2339 }
2340 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002341
Robert Greenwalt7b816022014-04-18 15:25:25 -07002342 private void handleAsyncChannelDisconnected(Message msg) {
2343 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2344 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002345 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002346 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002347 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002348 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002349 // TODO - if we move the logic to the network agent (have them disconnect
2350 // because they lost all their requests or because their score isn't good)
2351 // then they would disconnect organically, report their new state and then
2352 // disconnect the channel.
2353 if (nai.networkInfo.isConnected()) {
2354 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2355 null, null);
2356 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002357 final boolean wasDefault = isDefaultNetwork(nai);
2358 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002359 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002360 // Log default network disconnection before required book-keeping.
2361 // Let rematchAllNetworksAndRequests() below record a new default network event
2362 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2363 // whose timestamps tell how long it takes to recover a default network.
2364 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002365 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002366 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002367 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2368 // by other networks that are already connected. Perhaps that can be done by
2369 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2370 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002371 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002372 mKeepaliveTracker.handleStopAllKeepalives(nai,
2373 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002374 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002375 mNetworkAgentInfos.remove(msg.replyTo);
2376 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002377 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002378 // Remove the NetworkAgent, but don't mark the netId as
2379 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002380 mNetworkForNetId.remove(nai.network.netId);
2381 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002382 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002383 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2384 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002385 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2386 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2387 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002388 sendUpdatedScoreToFactories(request, 0);
2389 }
2390 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002391 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002392 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002393 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002394 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002395 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002396 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002397 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002398 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002399 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002400 if (nai.created) {
2401 // Tell netd to clean up the configuration for this network
2402 // (routing rules, DNS, etc).
2403 // This may be slow as it requires a lot of netd shelling out to ip and
2404 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2405 // after we've rematched networks with requests which should make a potential
2406 // fallback network the default or requested a new network from the
2407 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2408 // long time.
2409 try {
2410 mNetd.removeNetwork(nai.network.netId);
2411 } catch (Exception e) {
2412 loge("Exception removing network: " + e);
2413 }
2414 }
2415 synchronized (mNetworkForNetId) {
2416 mNetIdInUse.delete(nai.network.netId);
2417 }
2418 } else {
2419 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2420 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002421 }
2422 }
2423
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002424 // If this method proves to be too slow then we can maintain a separate
2425 // pendingIntent => NetworkRequestInfo map.
2426 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2427 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2428 Intent intent = pendingIntent.getIntent();
2429 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2430 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2431 if (existingPendingIntent != null &&
2432 existingPendingIntent.getIntent().filterEquals(intent)) {
2433 return entry.getValue();
2434 }
2435 }
2436 return null;
2437 }
2438
2439 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2440 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2441
2442 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2443 if (existingRequest != null) { // remove the existing request.
2444 if (DBG) log("Replacing " + existingRequest.request + " with "
2445 + nri.request + " because their intents matched.");
2446 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2447 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002448 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002449 }
2450
Erik Klineda4bfa82015-04-30 12:58:40 +09002451 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002452 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002453 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002454 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002455 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002456 if (nri.request.networkCapabilities.hasSignalStrength() &&
2457 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2458 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002459 }
2460 }
2461 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002462 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002463 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002464 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002465 }
2466 }
2467
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002468 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2469 int callingUid) {
2470 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2471 if (nri != null) {
2472 handleReleaseNetworkRequest(nri.request, callingUid);
2473 }
2474 }
2475
Paul Jensen99364842014-12-09 11:43:45 -05002476 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002477 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2478 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002479 private boolean unneeded(NetworkAgentInfo nai) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002480 if (!nai.everConnected || nai.isVPN() ||
2481 nai.isLingering() || nai.numRequestNetworkRequests() > 0) {
2482 return false;
2483 }
Paul Jensene0988542015-06-25 15:30:08 -04002484 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2485 // If this Network is already the highest scoring Network for a request, or if
2486 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002487 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002488 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002489 // Note that this catches two important cases:
2490 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2491 // is currently satisfying the request. This is desirable when
2492 // cellular ends up validating but WiFi does not.
2493 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002494 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002495 // WiFi ends up validating and out scoring cellular.
2496 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2497 nai.getCurrentScoreAsValidated())) {
2498 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002499 }
2500 }
Paul Jensene0988542015-06-25 15:30:08 -04002501 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002502 }
2503
Erik Klineacdd6392016-07-07 16:50:58 +09002504 private NetworkRequestInfo getNriForAppRequest(
2505 NetworkRequest request, int callingUid, String requestedOperation) {
2506 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2507
Robert Greenwalt9258c642014-03-26 16:47:06 -07002508 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002509 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002510 log(String.format("UID %d attempted to %s for unowned request %s",
2511 callingUid, requestedOperation, nri));
2512 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002513 }
Erik Klineacdd6392016-07-07 16:50:58 +09002514 }
2515
2516 return nri;
2517 }
2518
2519 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2520 String description, int callbackType) {
2521 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2522 if (nri == null) return;
2523
2524 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2525 // The network that is satisfying this request may have changed since
2526 // the application requested the update.
2527 //
2528 // - If the request is no longer satisfied, don't send any updates.
2529 // - If the request is satisfied by a different network, it is the
2530 // caller's responsibility to check that the Network object in the
2531 // callback matches the network that was returned in the last
2532 // onAvailable() callback for this request.
2533 if (nai == null) return;
2534 callCallbackForRequest(nri, nai, callbackType, 0);
2535 }
2536
2537 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2538 handleRequestCallbackUpdate(request, callingUid,
2539 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2540 }
2541
2542 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2543 handleRequestCallbackUpdate(request, callingUid,
2544 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2545 }
2546
Erik Kline57faba92015-11-25 12:49:38 +09002547 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2548 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2549 nri.request.requestId) == null) {
2550 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2551 }
2552 }
2553
Erik Klineacdd6392016-07-07 16:50:58 +09002554 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2555 final NetworkRequestInfo nri = getNriForAppRequest(
2556 request, callingUid, "release NetworkRequest");
Erik Kline57faba92015-11-25 12:49:38 +09002557 if (nri != null) {
2558 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2559 }
2560 }
Erik Klineacdd6392016-07-07 16:50:58 +09002561
Erik Kline57faba92015-11-25 12:49:38 +09002562 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2563 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2564 if (VDBG || (DBG && nri.request.isRequest())) {
2565 log("releasing " + nri.request + " (" + logCallbackType + ")");
2566 }
Erik Klineacdd6392016-07-07 16:50:58 +09002567 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002568 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002569 synchronized (mUidToNetworkRequestCount) {
2570 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2571 if (requests < 1) {
2572 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2573 nri.mUid);
2574 } else if (requests == 1) {
2575 mUidToNetworkRequestCount.removeAt(
2576 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2577 } else {
2578 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2579 }
2580 }
2581 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2582 if (nri.request.isRequest()) {
2583 boolean wasKept = false;
2584 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2585 if (nai != null) {
2586 nai.removeRequest(nri.request.requestId);
2587 if (VDBG) {
2588 log(" Removing from current network " + nai.name() +
2589 ", leaving " + nai.numNetworkRequests() + " requests.");
2590 }
2591 // If there are still lingered requests on this network, don't tear it down,
2592 // but resume lingering instead.
2593 updateLingerState(nai, SystemClock.elapsedRealtime());
2594 if (unneeded(nai)) {
2595 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2596 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002597 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002598 wasKept = true;
2599 }
2600 mNetworkForRequestId.remove(nri.request.requestId);
2601 }
2602
2603 // TODO: remove this code once we know that the Slog.wtf is never hit.
2604 //
2605 // Find all networks that are satisfying this request and remove the request
2606 // from their request lists.
2607 // TODO - it's my understanding that for a request there is only a single
2608 // network satisfying it, so this loop is wasteful
2609 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2610 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2611 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2612 otherNai.name() + ", but mNetworkAgentInfos says " +
2613 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002614 }
2615 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002616
Erik Klineacdd6392016-07-07 16:50:58 +09002617 // Maintain the illusion. When this request arrived, we might have pretended
2618 // that a network connected to serve it, even though the network was already
2619 // connected. Now that this request has gone away, we might have to pretend
2620 // that the network disconnected. LegacyTypeTracker will generate that
2621 // phantom disconnect for this type.
2622 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2623 boolean doRemove = true;
2624 if (wasKept) {
2625 // check if any of the remaining requests for this network are for the
2626 // same legacy type - if so, don't remove the nai
2627 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2628 NetworkRequest otherRequest = nai.requestAt(i);
2629 if (otherRequest.legacyType == nri.request.legacyType &&
2630 otherRequest.isRequest()) {
2631 if (DBG) log(" still have other legacy request - leaving");
2632 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002633 }
2634 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002635 }
2636
Erik Klineacdd6392016-07-07 16:50:58 +09002637 if (doRemove) {
2638 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002639 }
2640 }
Erik Klineacdd6392016-07-07 16:50:58 +09002641
2642 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2643 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2644 nri.request);
2645 }
2646 } else {
2647 // listens don't have a singular affectedNetwork. Check all networks to see
2648 // if this listen request applies and remove it.
2649 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2650 nai.removeRequest(nri.request.requestId);
2651 if (nri.request.networkCapabilities.hasSignalStrength() &&
2652 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2653 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2654 }
2655 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002656 }
Erik Kline57faba92015-11-25 12:49:38 +09002657 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002658 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002659
Lorenzo Colitti18660282016-07-04 12:55:44 +09002660 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002661 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2662 enforceConnectivityInternalPermission();
2663 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2664 accept ? 1 : 0, always ? 1: 0, network));
2665 }
2666
2667 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2668 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2669 " accept=" + accept + " always=" + always);
2670
2671 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2672 if (nai == null) {
2673 // Nothing to do.
2674 return;
2675 }
2676
2677 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002678 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002679 return;
2680 }
2681
2682 if (!nai.networkMisc.explicitlySelected) {
2683 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2684 }
2685
2686 if (accept != nai.networkMisc.acceptUnvalidated) {
2687 int oldScore = nai.getCurrentScore();
2688 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002689 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002690 sendUpdatedScoreToFactories(nai);
2691 }
2692
2693 if (always) {
2694 nai.asyncChannel.sendMessage(
2695 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2696 }
2697
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002698 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002699 // Tell the NetworkAgent to not automatically reconnect to the network.
2700 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2701 // Teardown the nework.
2702 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002703 }
2704
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002705 }
2706
2707 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002708 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002709 mHandler.sendMessageDelayed(
2710 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2711 PROMPT_UNVALIDATED_DELAY_MS);
2712 }
2713
2714 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002715 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002716 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2717
2718 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2719 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002720 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002721 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002722 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2723 return;
2724 }
2725
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002726 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002727 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002728 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2729 intent.setClassName("com.android.settings",
2730 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002731
2732 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2733 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
fionaxu1bf6ec22016-05-23 16:33:16 -07002734
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002735 mNotifier.showNotification(nai.network.netId, NotificationType.NO_INTERNET, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002736 pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002737 }
2738
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002739 private class InternalHandler extends Handler {
2740 public InternalHandler(Looper looper) {
2741 super(looper);
2742 }
2743
2744 @Override
2745 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002746 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002747 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002748 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002749 String causedBy = null;
2750 synchronized (ConnectivityService.this) {
2751 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2752 mNetTransitionWakeLock.isHeld()) {
2753 mNetTransitionWakeLock.release();
2754 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002755 } else {
2756 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002757 }
2758 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002759 if (VDBG) {
2760 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2761 log("Failed to find a new network - expiring NetTransition Wakelock");
2762 } else {
2763 log("NetTransition Wakelock (" +
2764 (causedBy == null ? "unknown" : causedBy) +
2765 " cleared because we found a replacement network");
2766 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002767 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002768 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002769 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002770 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002771 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002772 break;
2773 }
Jason Monkdecd2952013-10-10 14:02:51 -04002774 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002775 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002776 break;
2777 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002778 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002779 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2780 break;
2781 }
2782 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2783 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002784 break;
2785 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002786 case EVENT_REGISTER_NETWORK_AGENT: {
2787 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2788 break;
2789 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002790 case EVENT_REGISTER_NETWORK_REQUEST:
2791 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002792 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002793 break;
2794 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002795 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2796 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002797 handleRegisterNetworkRequestWithIntent(msg);
2798 break;
2799 }
Erik Kline57faba92015-11-25 12:49:38 +09002800 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2801 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2802 handleTimedOutNetworkRequest(nri);
2803 break;
2804 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002805 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2806 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2807 break;
2808 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002809 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002810 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002811 break;
2812 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002813 case EVENT_SET_ACCEPT_UNVALIDATED: {
2814 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2815 break;
2816 }
2817 case EVENT_PROMPT_UNVALIDATED: {
2818 handlePromptUnvalidated((Network) msg.obj);
2819 break;
2820 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002821 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2822 handleMobileDataAlwaysOn();
2823 break;
2824 }
Erik Klineacdd6392016-07-07 16:50:58 +09002825 case EVENT_REQUEST_LINKPROPERTIES:
2826 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2827 break;
2828 case EVENT_REQUEST_NETCAPABILITIES:
2829 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2830 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002831 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2832 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2833 mKeepaliveTracker.handleStartKeepalive(msg);
2834 break;
2835 }
2836 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2837 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2838 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2839 int slot = msg.arg1;
2840 int reason = msg.arg2;
2841 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2842 break;
2843 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002844 case EVENT_SYSTEM_READY: {
2845 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2846 nai.networkMonitor.systemReady = true;
2847 }
2848 break;
2849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 }
2851 }
2852 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002853
2854 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002855 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002856 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002857 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002858 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002859 final int status = mTethering.tether(iface);
2860 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2861 try {
2862 mPolicyManager.onTetheringChanged(iface, true);
2863 } catch (RemoteException e) {
2864 }
2865 }
2866 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002867 } else {
2868 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2869 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002870 }
2871
2872 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002873 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002874 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002875 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002876
2877 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002878 final int status = mTethering.untether(iface);
2879 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2880 try {
2881 mPolicyManager.onTetheringChanged(iface, false);
2882 } catch (RemoteException e) {
2883 }
2884 }
2885 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002886 } else {
2887 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2888 }
2889 }
2890
2891 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002892 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002893 public int getLastTetherError(String iface) {
2894 enforceTetherAccessPermission();
2895
2896 if (isTetheringSupported()) {
2897 return mTethering.getLastTetherError(iface);
2898 } else {
2899 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2900 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002901 }
2902
2903 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002904 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002905 public String[] getTetherableUsbRegexs() {
2906 enforceTetherAccessPermission();
2907 if (isTetheringSupported()) {
2908 return mTethering.getTetherableUsbRegexs();
2909 } else {
2910 return new String[0];
2911 }
2912 }
2913
Lorenzo Colitti18660282016-07-04 12:55:44 +09002914 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002915 public String[] getTetherableWifiRegexs() {
2916 enforceTetherAccessPermission();
2917 if (isTetheringSupported()) {
2918 return mTethering.getTetherableWifiRegexs();
2919 } else {
2920 return new String[0];
2921 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002922 }
2923
Lorenzo Colitti18660282016-07-04 12:55:44 +09002924 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002925 public String[] getTetherableBluetoothRegexs() {
2926 enforceTetherAccessPermission();
2927 if (isTetheringSupported()) {
2928 return mTethering.getTetherableBluetoothRegexs();
2929 } else {
2930 return new String[0];
2931 }
2932 }
2933
Lorenzo Colitti18660282016-07-04 12:55:44 +09002934 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002935 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002936 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002937 if (isTetheringSupported()) {
2938 return mTethering.setUsbTethering(enable);
2939 } else {
2940 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2941 }
2942 }
2943
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002944 // TODO - move iface listing, queries, etc to new module
2945 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002946 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002947 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002948 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002949 return mTethering.getTetherableIfaces();
2950 }
2951
Lorenzo Colitti18660282016-07-04 12:55:44 +09002952 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002953 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002954 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002955 return mTethering.getTetheredIfaces();
2956 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002957
Lorenzo Colitti18660282016-07-04 12:55:44 +09002958 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002959 public String[] getTetheringErroredIfaces() {
2960 enforceTetherAccessPermission();
2961 return mTethering.getErroredIfaces();
2962 }
2963
Lorenzo Colitti18660282016-07-04 12:55:44 +09002964 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002965 public String[] getTetheredDhcpRanges() {
2966 enforceConnectivityInternalPermission();
2967 return mTethering.getTetheredDhcpRanges();
2968 }
2969
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002970 // if ro.tether.denied = true we default to no tethering
2971 // gservices could set the secure setting to 1 though to enable it on a build where it
2972 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002973 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002974 public boolean isTetheringSupported() {
2975 enforceTetherAccessPermission();
2976 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002977 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002978 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2979 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002980 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2981 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002982 mTethering.getTetherableWifiRegexs().length != 0 ||
2983 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2984 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002985 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002986
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002987 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002988 public void startTethering(int type, ResultReceiver receiver,
2989 boolean showProvisioningUi) {
2990 ConnectivityManager.enforceTetherChangePermission(mContext);
2991 if (!isTetheringSupported()) {
2992 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2993 return;
2994 }
2995 mTethering.startTethering(type, receiver, showProvisioningUi);
2996 }
2997
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002998 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002999 public void stopTethering(int type) {
3000 ConnectivityManager.enforceTetherChangePermission(mContext);
3001 mTethering.stopTethering(type);
3002 }
3003
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003004 // Called when we lose the default network and have no replacement yet.
3005 // This will automatically be cleared after X seconds or a new default network
3006 // becomes CONNECTED, whichever happens first. The timer is started by the
3007 // first caller and not restarted by subsequent callers.
3008 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003009 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003010 synchronized (this) {
3011 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003012 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003013 mNetTransitionWakeLock.acquire();
3014 mNetTransitionWakeLockCausedBy = forWhom;
3015 }
3016 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003017 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003018 mNetTransitionWakeLockTimeout);
3019 return;
3020 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003021
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003022 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003023 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003024 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003025 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003026 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003027 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003028 }
3029
Lorenzo Colitti18660282016-07-04 12:55:44 +09003030 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003031 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003032 enforceAccessPermission();
3033 enforceInternetPermission();
3034
Paul Jensenbfd17b72015-04-07 12:43:13 -04003035 NetworkAgentInfo nai;
3036 if (network == null) {
3037 nai = getDefaultNetwork();
3038 } else {
3039 nai = getNetworkAgentInfoForNetwork(network);
3040 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003041 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3042 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3043 return;
3044 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003045 // Revalidate if the app report does not match our current validated state.
3046 if (hasConnectivity == nai.lastValidated) return;
3047 final int uid = Binder.getCallingUid();
3048 if (DBG) {
3049 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3050 ") by " + uid);
3051 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003052 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003053 // Validating a network that has not yet connected could result in a call to
3054 // rematchNetworkAndRequests() which is not meant to work on such networks.
3055 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003056
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003057 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003058
3059 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3060 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003061 }
3062
Paul Jensencee9b512015-05-06 07:32:40 -04003063 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003064 // this information is already available as a world read/writable jvm property
3065 // so this API change wouldn't have a benifit. It also breaks the passing
3066 // of proxy info to all the JVMs.
3067 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003068 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003069 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003070 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3071 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003072 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003073 }
3074
Lorenzo Colitti18660282016-07-04 12:55:44 +09003075 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003076 public ProxyInfo getProxyForNetwork(Network network) {
3077 if (network == null) return getDefaultProxy();
3078 final ProxyInfo globalProxy = getGlobalProxy();
3079 if (globalProxy != null) return globalProxy;
3080 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3081 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3082 // caller may not have.
3083 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3084 if (nai == null) return null;
3085 synchronized (nai) {
3086 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3087 if (proxyInfo == null) return null;
3088 return new ProxyInfo(proxyInfo);
3089 }
3090 }
3091
Paul Jensene0bef712014-12-10 15:12:18 -05003092 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3093 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3094 // proxy is null then there is no proxy in place).
3095 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3096 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3097 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3098 proxy = null;
3099 }
3100 return proxy;
3101 }
3102
3103 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3104 // better for determining if a new proxy broadcast is necessary:
3105 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3106 // avoid unnecessary broadcasts.
3107 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3108 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3109 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3110 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3111 // all set.
3112 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3113 a = canonicalizeProxyInfo(a);
3114 b = canonicalizeProxyInfo(b);
3115 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3116 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3117 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3118 }
3119
Jason Monk207900c2014-04-25 15:00:09 -04003120 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003121 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003122
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003123 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003124 if (proxyProperties == mGlobalProxy) return;
3125 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3126 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3127
3128 String host = "";
3129 int port = 0;
3130 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003131 String pacFileUrl = "";
3132 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003133 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003134 if (!proxyProperties.isValid()) {
3135 if (DBG)
3136 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3137 return;
3138 }
Jason Monk207900c2014-04-25 15:00:09 -04003139 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003140 host = mGlobalProxy.getHost();
3141 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003142 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003143 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003144 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003145 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003146 } else {
3147 mGlobalProxy = null;
3148 }
3149 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003150 final long token = Binder.clearCallingIdentity();
3151 try {
3152 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3153 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3154 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3155 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003156 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003157 } finally {
3158 Binder.restoreCallingIdentity(token);
3159 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003160
Jason Monkcf0f97a2014-10-02 15:39:38 -04003161 if (mGlobalProxy == null) {
3162 proxyProperties = mDefaultProxy;
3163 }
3164 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003165 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003166 }
3167
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003168 private void loadGlobalProxy() {
3169 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003170 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3171 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3172 String exclList = Settings.Global.getString(res,
3173 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003174 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3175 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003176 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003177 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003178 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003179 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003180 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003181 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003182 if (!proxyProperties.isValid()) {
3183 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3184 return;
3185 }
3186
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003187 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003188 mGlobalProxy = proxyProperties;
3189 }
3190 }
3191 }
3192
Jason Monk207900c2014-04-25 15:00:09 -04003193 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003194 // this information is already available as a world read/writable jvm property
3195 // so this API change wouldn't have a benifit. It also breaks the passing
3196 // of proxy info to all the JVMs.
3197 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003198 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003199 return mGlobalProxy;
3200 }
3201 }
3202
Jason Monk207900c2014-04-25 15:00:09 -04003203 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003204 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003205 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003206 proxy = null;
3207 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003208 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003209 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003210 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003211 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003212 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3213 return;
3214 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003215
3216 // This call could be coming from the PacManager, containing the port of the local
3217 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3218 // global (to get the correct local port), and send a broadcast.
3219 // TODO: Switch PacManager to have its own message to send back rather than
3220 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003221 if ((mGlobalProxy != null) && (proxy != null)
3222 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003223 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3224 mGlobalProxy = proxy;
3225 sendProxyBroadcast(mGlobalProxy);
3226 return;
3227 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003228 mDefaultProxy = proxy;
3229
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003230 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003231 if (!mDefaultProxyDisabled) {
3232 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003233 }
3234 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003235 }
3236
Paul Jensene0bef712014-12-10 15:12:18 -05003237 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3238 // This method gets called when any network changes proxy, but the broadcast only ever contains
3239 // the default proxy (even if it hasn't changed).
3240 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3241 // world where an app might be bound to a non-default network.
3242 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3243 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3244 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3245
3246 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3247 sendProxyBroadcast(getDefaultProxy());
3248 }
3249 }
3250
Robert Greenwalt434203a2010-10-11 16:00:27 -07003251 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003252 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3253 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003254 if (!TextUtils.isEmpty(proxy)) {
3255 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003256 if (data.length == 0) {
3257 return;
3258 }
3259
Robert Greenwalt434203a2010-10-11 16:00:27 -07003260 String proxyHost = data[0];
3261 int proxyPort = 8080;
3262 if (data.length > 1) {
3263 try {
3264 proxyPort = Integer.parseInt(data[1]);
3265 } catch (NumberFormatException e) {
3266 return;
3267 }
3268 }
Jason Monk207900c2014-04-25 15:00:09 -04003269 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003270 setGlobalProxy(p);
3271 }
3272 }
3273
Jason Monk207900c2014-04-25 15:00:09 -04003274 private void sendProxyBroadcast(ProxyInfo proxy) {
3275 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003276 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003277 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003278 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003279 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3280 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003281 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003282 final long ident = Binder.clearCallingIdentity();
3283 try {
3284 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3285 } finally {
3286 Binder.restoreCallingIdentity(ident);
3287 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003288 }
3289
3290 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003291 final private HashMap<Uri, Integer> mUriEventMap;
3292 final private Context mContext;
3293 final private Handler mHandler;
3294
3295 SettingsObserver(Context context, Handler handler) {
3296 super(null);
3297 mUriEventMap = new HashMap<Uri, Integer>();
3298 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003299 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003300 }
3301
Erik Klineda4bfa82015-04-30 12:58:40 +09003302 void observe(Uri uri, int what) {
3303 mUriEventMap.put(uri, what);
3304 final ContentResolver resolver = mContext.getContentResolver();
3305 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003306 }
3307
3308 @Override
3309 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003310 Slog.wtf(TAG, "Should never be reached.");
3311 }
3312
3313 @Override
3314 public void onChange(boolean selfChange, Uri uri) {
3315 final Integer what = mUriEventMap.get(uri);
3316 if (what != null) {
3317 mHandler.obtainMessage(what.intValue()).sendToTarget();
3318 } else {
3319 loge("No matching event to send for URI=" + uri);
3320 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003321 }
3322 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003323
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003324 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003325 Slog.d(TAG, s);
3326 }
3327
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003328 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003329 Slog.e(TAG, s);
3330 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003331
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003332 private static <T> T checkNotNull(T value, String message) {
3333 if (value == null) {
3334 throw new NullPointerException(message);
3335 }
3336 return value;
3337 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003338
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003339 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003340 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003341 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3342 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3343 *
3344 * @param oldPackage Package name of the application which currently controls VPN, which will
3345 * be replaced. If there is no such application, this should should either be
3346 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3347 * @param newPackage Package name of the application which should gain control of VPN, or
3348 * {@code null} to disable.
3349 * @param userId User for whom to prepare the new VPN.
3350 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003351 * @hide
3352 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003353 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003354 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3355 int userId) {
3356 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003357 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003358
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003359 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003360 Vpn vpn = mVpns.get(userId);
3361 if (vpn != null) {
3362 return vpn.prepare(oldPackage, newPackage);
3363 } else {
3364 return false;
3365 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003366 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003367 }
3368
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003369 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003370 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3371 * This method is used by system-privileged apps.
3372 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3373 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3374 *
3375 * @param packageName The package for which authorization state should change.
3376 * @param userId User for whom {@code packageName} is installed.
3377 * @param authorized {@code true} if this app should be able to start a VPN connection without
3378 * explicit user approval, {@code false} if not.
3379 *
Jeff Davidson05542602014-08-11 14:07:27 -07003380 * @hide
3381 */
3382 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003383 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3384 enforceCrossUserPermission(userId);
3385
Jeff Davidson05542602014-08-11 14:07:27 -07003386 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003387 Vpn vpn = mVpns.get(userId);
3388 if (vpn != null) {
3389 vpn.setPackageAuthorization(packageName, authorized);
3390 }
Jeff Davidson05542602014-08-11 14:07:27 -07003391 }
3392 }
3393
3394 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003395 * Configure a TUN interface and return its file descriptor. Parameters
3396 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003397 * and not available in ConnectivityManager. Permissions are checked in
3398 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003399 * @hide
3400 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003401 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003402 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003403 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003404 int user = UserHandle.getUserId(Binder.getCallingUid());
3405 synchronized(mVpns) {
3406 return mVpns.get(user).establish(config);
3407 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003408 }
3409
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003410 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003411 * Start legacy VPN, controlling native daemons as needed. Creates a
3412 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003413 */
3414 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003415 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003416 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003417 final LinkProperties egress = getActiveLinkProperties();
3418 if (egress == null) {
3419 throw new IllegalStateException("Missing active network connection");
3420 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003421 int user = UserHandle.getUserId(Binder.getCallingUid());
3422 synchronized(mVpns) {
3423 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3424 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003425 }
3426
3427 /**
3428 * Return the information of the ongoing legacy VPN. This method is used
3429 * by VpnSettings and not available in ConnectivityManager. Permissions
3430 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003431 */
3432 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003433 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3434 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003435
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003436 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003437 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003438 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003439 }
3440
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003441 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003442 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3443 * and not available in ConnectivityManager.
3444 */
3445 @Override
3446 public VpnInfo[] getAllVpnInfo() {
3447 enforceConnectivityInternalPermission();
3448 if (mLockdownEnabled) {
3449 return new VpnInfo[0];
3450 }
3451
3452 synchronized(mVpns) {
3453 List<VpnInfo> infoList = new ArrayList<>();
3454 for (int i = 0; i < mVpns.size(); i++) {
3455 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3456 if (info != null) {
3457 infoList.add(info);
3458 }
3459 }
3460 return infoList.toArray(new VpnInfo[infoList.size()]);
3461 }
3462 }
3463
3464 /**
3465 * @return VPN information for accounting, or null if we can't retrieve all required
3466 * information, e.g primary underlying iface.
3467 */
3468 @Nullable
3469 private VpnInfo createVpnInfo(Vpn vpn) {
3470 VpnInfo info = vpn.getVpnInfo();
3471 if (info == null) {
3472 return null;
3473 }
3474 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3475 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3476 // the underlyingNetworks list.
3477 if (underlyingNetworks == null) {
3478 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3479 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3480 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3481 }
3482 } else if (underlyingNetworks.length > 0) {
3483 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3484 if (linkProperties != null) {
3485 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3486 }
3487 }
3488 return info.primaryUnderlyingIface == null ? null : info;
3489 }
3490
3491 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003492 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3493 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003494 * Permissions are checked in Vpn class.
3495 * @hide
3496 */
3497 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003498 public VpnConfig getVpnConfig(int userId) {
3499 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003500 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003501 Vpn vpn = mVpns.get(userId);
3502 if (vpn != null) {
3503 return vpn.getVpnConfig();
3504 } else {
3505 return null;
3506 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003507 }
3508 }
3509
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003510 @Override
3511 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003512 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3513 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3514 return false;
3515 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003516
3517 // Tear down existing lockdown if profile was removed
3518 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3519 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003520 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3521 final VpnProfile profile = VpnProfile.decode(
3522 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003523 if (profile == null) {
3524 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3525 setLockdownTracker(null);
3526 return true;
3527 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003528 int user = UserHandle.getUserId(Binder.getCallingUid());
3529 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003530 Vpn vpn = mVpns.get(user);
3531 if (vpn == null) {
3532 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3533 return false;
3534 }
3535 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003536 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003537 } else {
3538 setLockdownTracker(null);
3539 }
3540
3541 return true;
3542 }
3543
3544 /**
3545 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3546 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3547 */
3548 private void setLockdownTracker(LockdownVpnTracker tracker) {
3549 // Shutdown any existing tracker
3550 final LockdownVpnTracker existing = mLockdownTracker;
3551 mLockdownTracker = null;
3552 if (existing != null) {
3553 existing.shutdown();
3554 }
3555
3556 try {
3557 if (tracker != null) {
3558 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003559 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003560 mLockdownTracker = tracker;
3561 mLockdownTracker.init();
3562 } else {
3563 mNetd.setFirewallEnabled(false);
3564 }
3565 } catch (RemoteException e) {
3566 // ignored; NMS lives inside system_server
3567 }
3568 }
3569
3570 private void throwIfLockdownEnabled() {
3571 if (mLockdownEnabled) {
3572 throw new IllegalStateException("Unavailable in lockdown mode");
3573 }
3574 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003575
Robin Lee244ce8e2016-01-05 18:03:46 +00003576 /**
Robin Lee17e61832016-05-09 13:46:28 +01003577 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3578 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003579 *
Robin Lee17e61832016-05-09 13:46:28 +01003580 * @return {@code true} if the service was started, the service was already connected, or there
3581 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003582 */
Robin Lee17e61832016-05-09 13:46:28 +01003583 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003584 synchronized (mVpns) {
3585 Vpn vpn = mVpns.get(userId);
3586 if (vpn == null) {
3587 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3588 // exists already.
3589 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3590 return false;
3591 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003592
Robin Lee812800c2016-05-13 15:38:08 +01003593 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003594 }
3595 }
3596
3597 @Override
Robin Leedc679712016-05-03 13:23:03 +01003598 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003599 enforceConnectivityInternalPermission();
3600 enforceCrossUserPermission(userId);
3601
3602 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3603 if (LockdownVpnTracker.isEnabled()) {
3604 return false;
3605 }
3606
Robin Lee244ce8e2016-01-05 18:03:46 +00003607 synchronized (mVpns) {
3608 Vpn vpn = mVpns.get(userId);
3609 if (vpn == null) {
3610 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3611 return false;
3612 }
Robin Lee17e61832016-05-09 13:46:28 +01003613 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003614 return false;
3615 }
Robin Lee17e61832016-05-09 13:46:28 +01003616 if (!startAlwaysOnVpn(userId)) {
3617 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003618 return false;
3619 }
Robin Lee17e61832016-05-09 13:46:28 +01003620
Robin Lee812800c2016-05-13 15:38:08 +01003621 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003622 }
3623 return true;
3624 }
3625
3626 @Override
3627 public String getAlwaysOnVpnPackage(int userId) {
3628 enforceConnectivityInternalPermission();
3629 enforceCrossUserPermission(userId);
3630
3631 synchronized (mVpns) {
3632 Vpn vpn = mVpns.get(userId);
3633 if (vpn == null) {
3634 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3635 return null;
3636 }
3637 return vpn.getAlwaysOnPackage();
3638 }
3639 }
3640
Wink Savilleab9321d2013-06-29 21:10:57 -07003641 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003642 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003643 // TODO: Remove? Any reason to trigger a provisioning check?
3644 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003645 }
3646
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003647 /** Location to an updatable file listing carrier provisioning urls.
3648 * An example:
3649 *
3650 * <?xml version="1.0" encoding="utf-8"?>
3651 * <provisioningUrls>
3652 * <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 -07003653 * </provisioningUrls>
3654 */
3655 private static final String PROVISIONING_URL_PATH =
3656 "/data/misc/radio/provisioning_urls.xml";
3657 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003658
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003659 /** XML tag for root element. */
3660 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3661 /** XML tag for individual url */
3662 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003663 /** XML attribute for mcc */
3664 private static final String ATTR_MCC = "mcc";
3665 /** XML attribute for mnc */
3666 private static final String ATTR_MNC = "mnc";
3667
Paul Jensen434dde82015-06-11 09:43:30 -04003668 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003669 FileReader fileReader = null;
3670 XmlPullParser parser = null;
3671 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003672
3673 try {
3674 fileReader = new FileReader(mProvisioningUrlFile);
3675 parser = Xml.newPullParser();
3676 parser.setInput(fileReader);
3677 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3678
3679 while (true) {
3680 XmlUtils.nextElement(parser);
3681
3682 String element = parser.getName();
3683 if (element == null) break;
3684
Paul Jensen434dde82015-06-11 09:43:30 -04003685 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003686 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3687 try {
3688 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3689 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3690 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3691 parser.next();
3692 if (parser.getEventType() == XmlPullParser.TEXT) {
3693 return parser.getText();
3694 }
3695 }
3696 }
3697 } catch (NumberFormatException e) {
3698 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3699 }
3700 }
3701 }
3702 return null;
3703 } catch (FileNotFoundException e) {
3704 loge("Carrier Provisioning Urls file not found");
3705 } catch (XmlPullParserException e) {
3706 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3707 } catch (IOException e) {
3708 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3709 } finally {
3710 if (fileReader != null) {
3711 try {
3712 fileReader.close();
3713 } catch (IOException e) {}
3714 }
3715 }
3716 return null;
3717 }
3718
Wink Saville42d4f082013-07-20 20:31:59 -07003719 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003720 public String getMobileProvisioningUrl() {
3721 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003722 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003723 if (TextUtils.isEmpty(url)) {
3724 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003725 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003726 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003727 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003728 }
Wink Saville8cf35602013-07-10 23:00:07 -07003729 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003730 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003731 String phoneNumber = mTelephonyManager.getLine1Number();
3732 if (TextUtils.isEmpty(phoneNumber)) {
3733 phoneNumber = "0000000000";
3734 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003735 url = String.format(url,
3736 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3737 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003738 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003739 }
3740
Wink Savilleab9321d2013-06-29 21:10:57 -07003741 return url;
3742 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003743
Wink Saville948282b2013-08-29 08:55:16 -07003744 @Override
3745 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003746 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003747 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003748 final long ident = Binder.clearCallingIdentity();
3749 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003750 // Concatenate the range of types onto the range of NetIDs.
3751 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3752 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003753 } finally {
3754 Binder.restoreCallingIdentity(ident);
3755 }
Wink Saville948282b2013-08-29 08:55:16 -07003756 }
Wink Saville7788c612013-08-29 14:57:08 -07003757
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003758 @Override
3759 public void setAirplaneMode(boolean enable) {
3760 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003761 final long ident = Binder.clearCallingIdentity();
3762 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003763 final ContentResolver cr = mContext.getContentResolver();
3764 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3765 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3766 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003767 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003768 } finally {
3769 Binder.restoreCallingIdentity(ident);
3770 }
3771 }
3772
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003773 private void onUserStart(int userId) {
3774 synchronized(mVpns) {
3775 Vpn userVpn = mVpns.get(userId);
3776 if (userVpn != null) {
3777 loge("Starting user already has a VPN");
3778 return;
3779 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003780 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003781 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003782
3783 final ContentResolver cr = mContext.getContentResolver();
3784 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3785 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3786 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3787 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3788 if (alwaysOnPackage != null) {
3789 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3790 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003791 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003792 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3793 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003794 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003795 }
3796
3797 private void onUserStop(int userId) {
3798 synchronized(mVpns) {
3799 Vpn userVpn = mVpns.get(userId);
3800 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003801 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003802 return;
3803 }
Robin Lee17e61832016-05-09 13:46:28 +01003804 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003805 mVpns.delete(userId);
3806 }
3807 }
3808
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003809 private void onUserAdded(int userId) {
3810 synchronized(mVpns) {
3811 final int vpnsSize = mVpns.size();
3812 for (int i = 0; i < vpnsSize; i++) {
3813 Vpn vpn = mVpns.valueAt(i);
3814 vpn.onUserAdded(userId);
3815 }
3816 }
3817 }
3818
3819 private void onUserRemoved(int userId) {
3820 synchronized(mVpns) {
3821 final int vpnsSize = mVpns.size();
3822 for (int i = 0; i < vpnsSize; i++) {
3823 Vpn vpn = mVpns.valueAt(i);
3824 vpn.onUserRemoved(userId);
3825 }
3826 }
3827 }
3828
Robin Lee89e7a692016-02-29 14:38:17 +00003829 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003830 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3831 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3832 updateLockdownVpn();
3833 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003834 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003835 }
3836 }
3837
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003838 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3839 @Override
3840 public void onReceive(Context context, Intent intent) {
3841 final String action = intent.getAction();
3842 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3843 if (userId == UserHandle.USER_NULL) return;
3844
Robin Lee323f29d2016-05-04 16:38:06 +01003845 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003846 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003847 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003848 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003849 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3850 onUserAdded(userId);
3851 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3852 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003853 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3854 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003855 }
3856 }
3857 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003858
Robert Greenwalta67be032014-05-16 15:49:14 -07003859 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3860 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003861 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3862 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003863
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003864 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3865 // Map from UID to number of NetworkRequests that UID has filed.
3866 @GuardedBy("mUidToNetworkRequestCount")
3867 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3868
Robert Greenwalta67be032014-05-16 15:49:14 -07003869 private static class NetworkFactoryInfo {
3870 public final String name;
3871 public final Messenger messenger;
3872 public final AsyncChannel asyncChannel;
3873
3874 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3875 this.name = name;
3876 this.messenger = messenger;
3877 this.asyncChannel = asyncChannel;
3878 }
3879 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003880
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003881 private void ensureNetworkRequestHasType(NetworkRequest request) {
3882 if (request.type == NetworkRequest.Type.NONE) {
3883 throw new IllegalArgumentException(
3884 "All NetworkRequests in ConnectivityService must have a type");
3885 }
3886 }
3887
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003888 /**
3889 * Tracks info about the requester.
3890 * Also used to notice when the calling process dies so we can self-expire
3891 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003892 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003893 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003894 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003895 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003896 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003897 final int mPid;
3898 final int mUid;
3899 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003900
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003901 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003902 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003903 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003904 mPendingIntent = pi;
3905 messenger = null;
3906 mBinder = null;
3907 mPid = getCallingPid();
3908 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003909 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003910 }
3911
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003912 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003913 super();
3914 messenger = m;
3915 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003916 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003917 mBinder = binder;
3918 mPid = getCallingPid();
3919 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003920 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003921 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003922
3923 try {
3924 mBinder.linkToDeath(this, 0);
3925 } catch (RemoteException e) {
3926 binderDied();
3927 }
3928 }
3929
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003930 private void enforceRequestCountLimit() {
3931 synchronized (mUidToNetworkRequestCount) {
3932 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3933 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3934 throw new IllegalArgumentException("Too many NetworkRequests filed");
3935 }
3936 mUidToNetworkRequestCount.put(mUid, networkRequests);
3937 }
3938 }
3939
Robert Greenwalt9258c642014-03-26 16:47:06 -07003940 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003941 if (mBinder != null) {
3942 mBinder.unlinkToDeath(this, 0);
3943 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003944 }
3945
3946 public void binderDied() {
3947 log("ConnectivityService NetworkRequestInfo binderDied(" +
3948 request + ", " + mBinder + ")");
3949 releaseNetworkRequest(request);
3950 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003951
3952 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003953 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003954 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003955 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003956 }
3957
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003958 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3959 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3960 if (badCapability != null) {
3961 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003962 }
3963 }
3964
Erik Kline9d598e12015-07-13 16:37:51 +09003965 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003966 final SortedSet<Integer> thresholds = new TreeSet();
3967 synchronized (nai) {
3968 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3969 if (nri.request.networkCapabilities.hasSignalStrength() &&
3970 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3971 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3972 }
3973 }
3974 }
Erik Kline9d598e12015-07-13 16:37:51 +09003975 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003976 }
3977
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003978 private void updateSignalStrengthThresholds(
3979 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3980 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003981 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003982 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3983
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003984 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003985 String detail;
3986 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3987 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3988 } else {
3989 detail = reason;
3990 }
3991 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3992 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3993 }
3994
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003995 nai.asyncChannel.sendMessage(
3996 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003997 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003998 }
3999
Robert Greenwalt9258c642014-03-26 16:47:06 -07004000 @Override
4001 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004002 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004003 final NetworkRequest.Type type = (networkCapabilities == null)
4004 ? NetworkRequest.Type.TRACK_DEFAULT
4005 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004006 // If the requested networkCapabilities is null, take them instead from
4007 // the default network request. This allows callers to keep track of
4008 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004009 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004010 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4011 enforceAccessPermission();
4012 } else {
4013 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4014 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004015 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4016 // of the app when the request is filed, but we never change the request if the app
4017 // changes network state. http://b/29964605
4018 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004019 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004020 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004021
Robert Greenwalt6078b502014-06-11 16:05:07 -07004022 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004023 throw new IllegalArgumentException("Bad timeout specified");
4024 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004025
Etan Cohenddb9ef02015-11-18 10:56:15 -08004026 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4027 .equals(networkCapabilities.getNetworkSpecifier())) {
4028 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4029 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4030 }
4031
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004032 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004033 nextNetworkRequestId(), type);
4034 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004035 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004036
4037 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004038 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004039 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004040 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004041 }
4042 return networkRequest;
4043 }
4044
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004045 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004046 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004047 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004048 } else {
4049 enforceChangePermission();
4050 }
4051 }
4052
fenglub15e72b2015-03-20 11:29:56 -07004053 @Override
fengludb571472015-04-21 17:12:05 -07004054 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004055 enforceAccessPermission();
4056 NetworkAgentInfo nai = null;
4057 if (network == null) {
4058 return false;
4059 }
4060 synchronized (mNetworkForNetId) {
4061 nai = mNetworkForNetId.get(network.netId);
4062 }
4063 if (nai != null) {
4064 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4065 return true;
4066 }
4067 return false;
4068 }
4069
Felipe Lemeee27cab2016-06-20 16:36:29 -07004070 private boolean isSystem(int uid) {
4071 return uid < Process.FIRST_APPLICATION_UID;
4072 }
fenglub15e72b2015-03-20 11:29:56 -07004073
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004074 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004075 final int uid = Binder.getCallingUid();
4076 if (isSystem(uid)) {
4077 return;
4078 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004079 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004080 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004081 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004082 synchronized(mRulesLock) {
4083 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4084 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004085 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4086 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004087 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004088 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004089 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004090 }
4091 }
4092 }
4093
Robert Greenwalt9258c642014-03-26 16:47:06 -07004094 @Override
4095 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4096 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004097 checkNotNull(operation, "PendingIntent cannot be null.");
4098 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4099 enforceNetworkRequestPermissions(networkCapabilities);
4100 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004101 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004102
4103 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004104 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4105 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004106 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004107 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4108 nri));
4109 return networkRequest;
4110 }
4111
Jeremy Joslin79294842014-12-03 17:15:28 -08004112 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4113 mHandler.sendMessageDelayed(
4114 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4115 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4116 }
4117
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004118 @Override
4119 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004120 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004121 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4122 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004123 }
4124
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004125 // In order to implement the compatibility measure for pre-M apps that call
4126 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4127 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4128 // This ensures it has permission to do so.
4129 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4130 if (nc == null) {
4131 return false;
4132 }
4133 int[] transportTypes = nc.getTransportTypes();
4134 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4135 return false;
4136 }
4137 try {
4138 mContext.enforceCallingOrSelfPermission(
4139 android.Manifest.permission.ACCESS_WIFI_STATE,
4140 "ConnectivityService");
4141 } catch (SecurityException e) {
4142 return false;
4143 }
4144 return true;
4145 }
4146
Robert Greenwalt9258c642014-03-26 16:47:06 -07004147 @Override
4148 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4149 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004150 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4151 enforceAccessPermission();
4152 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004153
Erik Kline7523eb32015-07-09 18:24:03 +09004154 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004155 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4156 NetworkRequest.Type.LISTEN);
4157 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004158 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004159
4160 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4161 return networkRequest;
4162 }
4163
4164 @Override
4165 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4166 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004167 checkNotNull(operation, "PendingIntent cannot be null.");
4168 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4169 enforceAccessPermission();
4170 }
4171
Erik Kline7523eb32015-07-09 18:24:03 +09004172 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004173 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4174 NetworkRequest.Type.LISTEN);
4175 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004176 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004177
4178 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004179 }
4180
4181 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004182 public void requestLinkProperties(NetworkRequest networkRequest) {
4183 ensureNetworkRequestHasType(networkRequest);
4184 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4185 mHandler.sendMessage(mHandler.obtainMessage(
4186 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4187 }
4188
4189 @Override
4190 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4191 ensureNetworkRequestHasType(networkRequest);
4192 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4193 mHandler.sendMessage(mHandler.obtainMessage(
4194 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4195 }
4196
4197 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004198 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004199 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004200 mHandler.sendMessage(mHandler.obtainMessage(
4201 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004202 }
4203
4204 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004205 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004206 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004207 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4208 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004209 }
4210
Robert Greenwalta67be032014-05-16 15:49:14 -07004211 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004212 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004213 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4214 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4215 }
4216
4217 @Override
4218 public void unregisterNetworkFactory(Messenger messenger) {
4219 enforceConnectivityInternalPermission();
4220 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4221 }
4222
4223 private void handleUnregisterNetworkFactory(Messenger messenger) {
4224 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4225 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004226 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004227 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004228 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004229 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004230 }
4231
Robert Greenwalt7b816022014-04-18 15:25:25 -07004232 /**
4233 * NetworkAgentInfo supporting a request by requestId.
4234 * These have already been vetted (their Capabilities satisfy the request)
4235 * and the are the highest scored network available.
4236 * the are keyed off the Requests requestId.
4237 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004238 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004239 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4240 new SparseArray<NetworkAgentInfo>();
4241
Paul Jensen31a94f42015-02-13 14:18:39 -05004242 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4243 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004244 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4245 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004246 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4247 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4248 // there may not be a strict 1:1 correlation between the two.
4249 @GuardedBy("mNetworkForNetId")
4250 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004251
Robert Greenwalt7b816022014-04-18 15:25:25 -07004252 // NetworkAgentInfo keyed off its connecting messenger
4253 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004254 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004255 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4256 new HashMap<Messenger, NetworkAgentInfo>();
4257
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004258 @GuardedBy("mBlockedAppUids")
4259 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4260
Paul Jensen2c311d62014-11-17 12:34:51 -05004261 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004262 private final NetworkRequest mDefaultRequest;
4263
Erik Klineda4bfa82015-04-30 12:58:40 +09004264 // Request used to optionally keep mobile data active even when higher
4265 // priority networks like Wi-Fi are active.
4266 private final NetworkRequest mDefaultMobileDataRequest;
4267
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004268 private NetworkAgentInfo getDefaultNetwork() {
4269 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4270 }
4271
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004272 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004273 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004274 }
4275
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004276 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4277 return nri.request.requestId == mDefaultRequest.requestId;
4278 }
4279
Paul Jensen31a94f42015-02-13 14:18:39 -05004280 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004281 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004282 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004283 enforceConnectivityInternalPermission();
4284
Paul Jensen2c311d62014-11-17 12:34:51 -05004285 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4286 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004287 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004288 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4289 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004290 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004291 synchronized (this) {
4292 nai.networkMonitor.systemReady = mSystemReady;
4293 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004294 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4295 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004296 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004297 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004298 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004299 }
4300
4301 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4302 if (VDBG) log("Got NetworkAgent Messenger");
4303 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004304 synchronized (mNetworkForNetId) {
4305 mNetworkForNetId.put(na.network.netId, na);
4306 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004307 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4308 NetworkInfo networkInfo = na.networkInfo;
4309 na.networkInfo = null;
4310 updateNetworkInfo(na, networkInfo);
4311 }
4312
4313 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4314 LinkProperties newLp = networkAgent.linkProperties;
4315 int netId = networkAgent.network.netId;
4316
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004317 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4318 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004319 if (networkAgent.clatd != null) {
4320 networkAgent.clatd.fixupLinkProperties(oldLp);
4321 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004322
Paul Jensen992f2522014-04-28 10:33:11 -04004323 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004324 updateMtu(newLp, oldLp);
4325 // TODO - figure out what to do for clat
4326// for (LinkProperties lp : newLp.getStackedLinks()) {
4327// updateMtu(lp, null);
4328// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004329 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004330
Erik Kline94887872016-04-05 13:30:49 +09004331 updateRoutes(newLp, oldLp, netId);
4332 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004333
Paul Jensen3b759822014-05-13 11:44:01 -04004334 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004335 if (isDefaultNetwork(networkAgent)) {
4336 handleApplyDefaultProxy(newLp.getHttpProxy());
4337 } else {
4338 updateProxy(newLp, oldLp, networkAgent);
4339 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004340 // TODO - move this check to cover the whole function
4341 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004342 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004343 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4344 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004345
4346 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004347 }
4348
Lorenzo Colitti95439462014-10-09 13:44:48 +09004349 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4350 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4351 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004352
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004353 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004354 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4355 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004356 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004357 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004358 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004359 }
Paul Jensen992f2522014-04-28 10:33:11 -04004360
4361 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4362 CompareResult<String> interfaceDiff = new CompareResult<String>();
4363 if (oldLp != null) {
4364 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4365 } else if (newLp != null) {
4366 interfaceDiff.added = newLp.getAllInterfaceNames();
4367 }
4368 for (String iface : interfaceDiff.added) {
4369 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004370 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004371 mNetd.addInterfaceToNetwork(iface, netId);
4372 } catch (Exception e) {
4373 loge("Exception adding interface: " + e);
4374 }
4375 }
4376 for (String iface : interfaceDiff.removed) {
4377 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004378 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004379 mNetd.removeInterfaceFromNetwork(iface, netId);
4380 } catch (Exception e) {
4381 loge("Exception removing interface: " + e);
4382 }
4383 }
4384 }
4385
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004386 /**
4387 * Have netd update routes from oldLp to newLp.
4388 * @return true if routes changed between oldLp and newLp
4389 */
4390 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004391 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4392 if (oldLp != null) {
4393 routeDiff = oldLp.compareAllRoutes(newLp);
4394 } else if (newLp != null) {
4395 routeDiff.added = newLp.getAllRoutes();
4396 }
4397
4398 // add routes before removing old in case it helps with continuous connectivity
4399
4400 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4401 for (RouteInfo route : routeDiff.added) {
4402 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004403 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004404 try {
4405 mNetd.addRoute(netId, route);
4406 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004407 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4408 loge("Exception in addRoute for non-gateway: " + e);
4409 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004410 }
4411 }
4412 for (RouteInfo route : routeDiff.added) {
4413 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004414 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004415 try {
4416 mNetd.addRoute(netId, route);
4417 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004418 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4419 loge("Exception in addRoute for gateway: " + e);
4420 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004421 }
4422 }
4423
4424 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004425 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004426 try {
4427 mNetd.removeRoute(netId, route);
4428 } catch (Exception e) {
4429 loge("Exception in removeRoute: " + e);
4430 }
4431 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004432 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004433 }
Erik Kline41368502015-06-17 13:19:54 +09004434
Erik Kline94887872016-04-05 13:30:49 +09004435 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4436 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4437 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004438 }
Erik Kline94887872016-04-05 13:30:49 +09004439
4440 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004441 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004442 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004443 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004444 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4445 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004446 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004447 }
4448 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4449 if (defaultNai != null && defaultNai.network.netId == netId) {
4450 setDefaultDnsSystemProperties(dnses);
4451 }
4452 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004453 }
4454
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004455 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4456 int last = 0;
4457 for (InetAddress dns : dnses) {
4458 ++last;
4459 String key = "net.dns" + last;
4460 String value = dns.getHostAddress();
4461 SystemProperties.set(key, value);
4462 }
4463 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4464 String key = "net.dns" + i;
4465 SystemProperties.set(key, "");
4466 }
4467 mNumDnsEntries = last;
4468 }
4469
Paul Jensen3d194ea2015-06-16 14:27:36 -04004470 /**
4471 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4472 * augmented with any stateful capabilities implied from {@code networkAgent}
4473 * (e.g., validated status and captive portal status).
4474 *
Paul Jensene0988542015-06-25 15:30:08 -04004475 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004476 * @param networkCapabilities the new network capabilities.
4477 */
Paul Jensene0988542015-06-25 15:30:08 -04004478 private void updateCapabilities(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)) {
4492 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004493 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4494 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4495 try {
4496 mNetd.setNetworkPermission(nai.network.netId,
4497 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4498 null : NetworkManagementService.PERMISSION_SYSTEM);
4499 } catch (RemoteException e) {
4500 loge("Exception in setNetworkPermission: " + e);
4501 }
4502 }
Paul Jensene0988542015-06-25 15:30:08 -04004503 synchronized (nai) {
4504 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004505 }
Paul Jensene0988542015-06-25 15:30:08 -04004506 rematchAllNetworksAndRequests(nai, oldScore);
4507 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004508 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004509 }
4510
Paul Jensenc8b9a742014-09-30 15:37:41 -04004511 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004512 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4513 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004514 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004515 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004516 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4517 }
4518 }
4519
Robert Greenwalt7b816022014-04-18 15:25:25 -07004520 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4521 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004522 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004523 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4524 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004525 }
4526 }
4527
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004528 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4529 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004530 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004531 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004532 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4533 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004534 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004535 sendIntent(nri.mPendingIntent, intent);
4536 }
4537 // else not handled
4538 }
4539
4540 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4541 mPendingIntentWakeLock.acquire();
4542 try {
4543 if (DBG) log("Sending " + pendingIntent);
4544 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4545 } catch (PendingIntent.CanceledException e) {
4546 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4547 mPendingIntentWakeLock.release();
4548 releasePendingNetworkRequest(pendingIntent);
4549 }
4550 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4551 }
4552
4553 @Override
4554 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4555 String resultData, Bundle resultExtras) {
4556 if (DBG) log("Finished sending " + pendingIntent);
4557 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004558 // Release with a delay so the receiving client has an opportunity to put in its
4559 // own request.
4560 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004561 }
4562
Robert Greenwalt9258c642014-03-26 16:47:06 -07004563 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004564 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004565 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004566 Bundle bundle = new Bundle();
4567 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4568 new NetworkRequest(nri.request));
4569 Message msg = Message.obtain();
4570 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4571 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4572 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4573 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004574 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004575 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004576 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004577 break;
4578 }
4579 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4580 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4581 new NetworkCapabilities(networkAgent.networkCapabilities));
4582 break;
4583 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004584 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004585 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4586 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004587 break;
4588 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004589 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004590 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004591 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004592 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004593 if (VDBG) {
4594 log("sending notification " + notifyTypeToName(notificationType) +
4595 " for " + nri.request);
4596 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004597 nri.messenger.send(msg);
4598 } catch (RemoteException e) {
4599 // may occur naturally in the race of binder death.
4600 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4601 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004602 }
4603
Paul Jensenc8b9a742014-09-30 15:37:41 -04004604 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004605 if (nai.numRequestNetworkRequests() != 0) {
4606 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4607 NetworkRequest nr = nai.requestAt(i);
4608 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004609 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004610 loge("Dead network still had at least " + nr);
4611 break;
4612 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004613 }
4614 nai.asyncChannel.disconnect();
4615 }
4616
Robert Greenwalt7b816022014-04-18 15:25:25 -07004617 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4618 if (oldNetwork == null) {
4619 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4620 return;
4621 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004622 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004623
4624 // If we get here it means that the last linger timeout for this network expired. So there
4625 // must be no other active linger timers, and we must stop lingering.
4626 oldNetwork.clearLingerState();
4627
4628 if (unneeded(oldNetwork)) {
4629 teardownUnneededNetwork(oldNetwork);
4630 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004631 }
4632
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004633 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004634 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004635 setupDataActivityTracking(newNetwork);
4636 try {
4637 mNetd.setDefaultNetId(newNetwork.network.netId);
4638 } catch (Exception e) {
4639 loge("Exception setting default network :" + e);
4640 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004641 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004642 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004643 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004644 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004645 }
4646
Paul Jensen2161a8e2014-09-11 11:00:39 -04004647 // Handles a network appearing or improving its score.
4648 //
4649 // - Evaluates all current NetworkRequests that can be
4650 // satisfied by newNetwork, and reassigns to newNetwork
4651 // any such requests for which newNetwork is the best.
4652 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004653 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004654 // needed. A network is needed if it is the best network for
4655 // one or more NetworkRequests, or if it is a VPN.
4656 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004657 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004658 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004659 //
4660 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4661 // networks that have no chance (i.e. even if validated)
4662 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004663 //
4664 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4665 // it does not remove NetworkRequests that other Networks could better satisfy.
4666 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4667 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4668 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004669 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004670 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004671 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4672 // performed to tear down unvalidated networks that have no chance (i.e. even if
4673 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004674 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004675 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004676 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004677 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004678 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004679 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004680 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004681 // Find and migrate to this Network any NetworkRequests for
4682 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004683 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004684 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004685 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004686 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004687 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4688 final boolean satisfies = newNetwork.satisfies(nri.request);
4689 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004690 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004691 log("Network " + newNetwork.name() + " was already satisfying" +
4692 " request " + nri.request.requestId + ". No change.");
4693 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004694 keep = true;
4695 continue;
4696 }
4697
4698 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004699 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004700 if (satisfies) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004701 if (nri.request.isListen()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004702 // This is not a request, it's a callback listener.
4703 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004704 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004705 continue;
4706 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004707
Robert Greenwalt7b816022014-04-18 15:25:25 -07004708 // next check if it's better than any current network we're using for
4709 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004710 if (VDBG) {
4711 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004712 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4713 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004714 }
4715 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004716 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004717 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004718 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004719 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004720 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004721 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004722 affectedNetworks.add(currentNetwork);
4723 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004724 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004725 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004726 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004727 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004728 if (!newNetwork.addRequest(nri.request)) {
4729 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4730 }
4731 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004732 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004733 // Tell NetworkFactories about the new score, so they can stop
4734 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004735 // TODO - this could get expensive if we have alot of requests for this
4736 // network. Think about if there is a way to reduce this. Push
4737 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004738 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004739 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004740 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004741 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004742 if (currentNetwork != null) {
4743 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4744 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004745 }
4746 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004747 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004748 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4749 // mark it as no longer satisfying "nri". Because networks are processed by
4750 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4751 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4752 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4753 // This means this code doesn't have to handle the case where "currentNetwork" no
4754 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4755 if (DBG) {
4756 log("Network " + newNetwork.name() + " stopped satisfying" +
4757 " request " + nri.request.requestId);
4758 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004759 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004760 if (currentNetwork == newNetwork) {
4761 mNetworkForRequestId.remove(nri.request.requestId);
4762 sendUpdatedScoreToFactories(nri.request, 0);
4763 } else {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004764 if (nri.request.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004765 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4766 newNetwork.name() +
4767 " without updating mNetworkForRequestId or factories!");
4768 }
4769 }
4770 // TODO: technically, sending CALLBACK_LOST here is
4771 // incorrect if nri is a request (not a listen) and there
4772 // is a replacement network currently connected that can
4773 // satisfy it. However, the only capability that can both
4774 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4775 // so this code is only incorrect for a network that loses
4776 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004777 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004778 }
4779 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004780 if (isNewDefault) {
4781 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004782 makeDefault(newNetwork);
4783 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4784 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004785 synchronized (ConnectivityService.this) {
4786 // have a new default network, release the transition wakelock in
4787 // a second if it's held. The second pause is to allow apps
4788 // to reconnect over the new network
4789 if (mNetTransitionWakeLock.isHeld()) {
4790 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4791 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4792 mNetTransitionWakeLockSerialNumber, 0),
4793 1000);
4794 }
4795 }
4796 }
4797
4798 // do this after the default net is switched, but
4799 // before LegacyTypeTracker sends legacy broadcasts
4800 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4801
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004802 // Linger any networks that are no longer needed. This should be done after sending the
4803 // available callback for newNetwork.
4804 for (NetworkAgentInfo nai : affectedNetworks) {
4805 updateLingerState(nai, now);
4806 }
4807 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4808 // does not need to be done in any particular order.
4809 updateLingerState(newNetwork, now);
4810
Paul Jensencf4c2c62015-07-01 14:16:32 -04004811 if (isNewDefault) {
4812 // Maintain the illusion: since the legacy API only
4813 // understands one network at a time, we must pretend
4814 // that the current default network disconnected before
4815 // the new one connected.
4816 if (oldDefaultNetwork != null) {
4817 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4818 oldDefaultNetwork, true);
4819 }
4820 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4821 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4822 notifyLockdownVpn(newNetwork);
4823 }
4824
Robert Greenwalt7b816022014-04-18 15:25:25 -07004825 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004826 // Notify battery stats service about this network, both the normal
4827 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004828 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004829 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004830 final IBatteryStats bs = BatteryStatsService.getService();
4831 final int type = newNetwork.networkInfo.getType();
4832
4833 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4834 bs.noteNetworkInterfaceType(baseIface, type);
4835 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4836 final String stackedIface = stacked.getInterfaceName();
4837 bs.noteNetworkInterfaceType(stackedIface, type);
4838 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4839 }
4840 } catch (RemoteException ignored) {
4841 }
4842
Robert Greenwalt152ed372014-12-17 17:19:53 -08004843 // This has to happen after the notifyNetworkCallbacks as that tickles each
4844 // ConnectivityManager instance so that legacy requests correctly bind dns
4845 // requests to this network. The legacy users are listening for this bcast
4846 // and will generally do a dns request so they can ensureRouteToHost and if
4847 // they do that before the callbacks happen they'll use the default network.
4848 //
4849 // TODO: Is there still a race here? We send the broadcast
4850 // after sending the callback, but if the app can receive the
4851 // broadcast before the callback, it might still break.
4852 //
4853 // This *does* introduce a race where if the user uses the new api
4854 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4855 // they may get old info. Reverse this after the old startUsing api is removed.
4856 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004857 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4858 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004859 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004860 // legacy type tracker filters out repeat adds
4861 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4862 }
4863 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004864
4865 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4866 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4867 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4868 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4869 if (newNetwork.isVPN()) {
4870 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4871 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004872 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004873 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4874 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004875 if (unneeded(nai)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004876 if (nai.getLingerExpiry() > 0) {
4877 // This network has active linger timers and no requests, but is not
4878 // lingering. Linger it.
4879 //
4880 // One way (the only way?) this can happen if this network is unvalidated
4881 // and became unneeded due to another network improving its score to the
4882 // point where this network will no longer be able to satisfy any requests
4883 // even if it validates.
4884 updateLingerState(nai, now);
4885 } else {
4886 if (DBG) log("Reaping " + nai.name());
4887 teardownUnneededNetwork(nai);
4888 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004889 }
4890 }
4891 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004892 }
4893
Paul Jensen1c7ba022015-06-16 14:27:36 -04004894 /**
4895 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4896 * being disconnected.
4897 * @param changed If only one Network's score or capabilities have been modified since the last
4898 * time this function was called, pass this Network in this argument, otherwise pass
4899 * null.
4900 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4901 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4902 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4903 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4904 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004905 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004906 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004907 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4908 // to avoid the slowness. It is not simply enough to process just "changed", for
4909 // example in the case where "changed"'s score decreases and another network should begin
4910 // satifying a NetworkRequest that "changed" currently satisfies.
4911
4912 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4913 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4914 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004915 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04004916 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004917 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004918 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004919 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4920 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4921 // Rematch higher scoring networks first to prevent requests first matching a lower
4922 // scoring network and then a higher scoring network, which could produce multiple
4923 // callbacks and inadvertently unlinger networks.
4924 Arrays.sort(nais);
4925 for (NetworkAgentInfo nai : nais) {
4926 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004927 // Only reap the last time through the loop. Reaping before all rematching
4928 // is complete could incorrectly teardown a network that hasn't yet been
4929 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004930 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004931 : ReapUnvalidatedNetworks.REAP,
4932 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004933 }
4934 }
4935 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004936
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004937 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004938 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004939 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004940 // For now only update icons for default connection.
4941 // TODO: Update WiFi and cellular icons separately. b/17237507
4942 if (!isDefaultNetwork(nai)) return;
4943
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004944 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004945 // Don't repeat publish.
4946 if (newInetCondition == mDefaultInetConditionPublished) return;
4947
4948 mDefaultInetConditionPublished = newInetCondition;
4949 sendInetConditionBroadcast(nai.networkInfo);
4950 }
4951
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004952 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4953 if (mLockdownTracker != null) {
4954 if (nai != null && nai.isVPN()) {
4955 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4956 } else {
4957 mLockdownTracker.onNetworkInfoChanged();
4958 }
4959 }
4960 }
4961
Robert Greenwalt7b816022014-04-18 15:25:25 -07004962 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4963 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004964 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004965 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004966 synchronized (networkAgent) {
4967 oldInfo = networkAgent.networkInfo;
4968 networkAgent.networkInfo = newInfo;
4969 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004970 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004971
4972 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004973 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4974 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4975 notifyIfacesChangedForNetworkStats();
4976 } else if (VDBG) log("ignoring duplicate network state non-change");
4977 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004978 return;
4979 }
4980 if (DBG) {
4981 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4982 (oldInfo == null ? "null" : oldInfo.getState()) +
4983 " to " + state);
4984 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004985
Robin Lee585e2482016-05-01 23:00:00 +01004986 if (!networkAgent.created
4987 && (state == NetworkInfo.State.CONNECTED
4988 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004989 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004990 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004991 if (networkAgent.isVPN()) {
4992 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004993 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4994 (networkAgent.networkMisc == null ||
4995 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004996 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004997 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4998 networkAgent.networkCapabilities.hasCapability(
4999 NET_CAPABILITY_NOT_RESTRICTED) ?
5000 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005001 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005002 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005003 loge("Error creating network " + networkAgent.network.netId + ": "
5004 + e.getMessage());
5005 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005006 }
Paul Jenseneec75412014-08-04 12:21:19 -04005007 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005008 }
5009
5010 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5011 networkAgent.everConnected = true;
5012
Robert Greenwalt7b816022014-04-18 15:25:25 -07005013 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005014 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005015
Paul Jensenca8f16a2014-05-09 12:47:55 -04005016 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005017 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005018
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005019 if (networkAgent.isVPN()) {
5020 // Temporarily disable the default proxy (not global).
5021 synchronized (mProxyLock) {
5022 if (!mDefaultProxyDisabled) {
5023 mDefaultProxyDisabled = true;
5024 if (mGlobalProxy == null && mDefaultProxy != null) {
5025 sendProxyBroadcast(null);
5026 }
5027 }
5028 }
5029 // TODO: support proxy per network.
5030 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005031
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005032 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5033 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5034 // capabilities, so it only needs to be done once on initial connect, not every time the
5035 // network's capabilities change. Note that we do this before rematching the network,
5036 // so we could decide to tear it down immediately afterwards. That's fine though - on
5037 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5038 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005039 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005040
Paul Jensen2161a8e2014-09-11 11:00:39 -04005041 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005042 final long now = SystemClock.elapsedRealtime();
5043 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005044
5045 // This has to happen after matching the requests, because callbacks are just requests.
5046 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005047 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005048 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005049 if (networkAgent.isVPN()) {
5050 synchronized (mProxyLock) {
5051 if (mDefaultProxyDisabled) {
5052 mDefaultProxyDisabled = false;
5053 if (mGlobalProxy == null && mDefaultProxy != null) {
5054 sendProxyBroadcast(mDefaultProxy);
5055 }
5056 }
5057 }
5058 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005059 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5060 state == NetworkInfo.State.SUSPENDED) {
5061 // going into or coming out of SUSPEND: rescore and notify
5062 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005063 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005064 }
5065 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5066 ConnectivityManager.CALLBACK_SUSPENDED :
5067 ConnectivityManager.CALLBACK_RESUMED));
5068 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005069 }
5070 }
5071
Robert Greenwaltac96c522014-06-03 16:43:57 -07005072 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005073 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005074 if (score < 0) {
5075 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5076 "). Bumping score to min of 0");
5077 score = 0;
5078 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005079
Paul Jensen2161a8e2014-09-11 11:00:39 -04005080 final int oldScore = nai.getCurrentScore();
5081 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005082
Paul Jensen85cf78e2015-06-25 13:25:07 -04005083 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005084
Paul Jensenc8b9a742014-09-30 15:37:41 -04005085 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005086 }
5087
Robert Greenwalt9258c642014-03-26 16:47:06 -07005088 // notify only this one new request of the current state
5089 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5090 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005091 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005092 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005093 } else {
5094 sendPendingIntentForRequest(nri, nai, notifyType);
5095 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005096 }
5097
Robert Greenwalt8d482522015-06-24 13:23:42 -07005098 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005099 // The NetworkInfo we actually send out has no bearing on the real
5100 // state of affairs. For example, if the default connection is mobile,
5101 // and a request for HIPRI has just gone away, we need to pretend that
5102 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5103 // the state to DISCONNECTED, even though the network is of type MOBILE
5104 // and is still connected.
5105 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5106 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005107 if (state != DetailedState.DISCONNECTED) {
5108 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005109 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005110 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005111 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005112 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5113 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5114 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5115 if (info.isFailover()) {
5116 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5117 nai.networkInfo.setFailover(false);
5118 }
5119 if (info.getReason() != null) {
5120 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5121 }
5122 if (info.getExtraInfo() != null) {
5123 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5124 }
5125 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005126 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005127 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005128 if (newDefaultAgent != null) {
5129 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5130 newDefaultAgent.networkInfo);
5131 } else {
5132 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5133 }
5134 }
5135 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5136 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005137 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005138 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005139 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005140 }
5141 }
5142 }
5143
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005144 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005145 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005146 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5147 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005148 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5149 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005150 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005151 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005152 } else {
5153 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5154 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005155 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005156 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005157
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005158 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5159 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5160 }
5161
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005162 private String notifyTypeToName(int notifyType) {
5163 switch (notifyType) {
5164 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5165 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5166 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5167 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5168 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5169 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5170 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5171 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5172 }
5173 return "UNKNOWN";
5174 }
5175
Jeff Sharkey69736342014-12-08 14:50:12 -08005176 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005177 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5178 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005179 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005180 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005181 try {
5182 mStatsService.forceUpdateIfaces();
5183 } catch (Exception ignored) {
5184 }
5185 }
5186
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005187 @Override
5188 public boolean addVpnAddress(String address, int prefixLength) {
5189 throwIfLockdownEnabled();
5190 int user = UserHandle.getUserId(Binder.getCallingUid());
5191 synchronized (mVpns) {
5192 return mVpns.get(user).addAddress(address, prefixLength);
5193 }
5194 }
5195
5196 @Override
5197 public boolean removeVpnAddress(String address, int prefixLength) {
5198 throwIfLockdownEnabled();
5199 int user = UserHandle.getUserId(Binder.getCallingUid());
5200 synchronized (mVpns) {
5201 return mVpns.get(user).removeAddress(address, prefixLength);
5202 }
5203 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005204
5205 @Override
5206 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5207 throwIfLockdownEnabled();
5208 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005209 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005210 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005211 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005212 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005213 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005214 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005215 }
5216 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005217 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005218
5219 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005220 public String getCaptivePortalServerUrl() {
5221 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5222 }
5223
5224 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005225 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5226 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5227 enforceKeepalivePermission();
5228 mKeepaliveTracker.startNattKeepalive(
5229 getNetworkAgentInfoForNetwork(network),
5230 intervalSeconds, messenger, binder,
5231 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5232 }
5233
5234 @Override
5235 public void stopKeepalive(Network network, int slot) {
5236 mHandler.sendMessage(mHandler.obtainMessage(
5237 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5238 }
5239
5240 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005241 public void factoryReset() {
5242 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005243
5244 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5245 return;
5246 }
5247
Robin Lee3b3dd942015-05-12 18:14:58 +01005248 final int userId = UserHandle.getCallingUserId();
5249
Stuart Scottf1fb3972015-04-02 18:00:02 -07005250 // Turn airplane mode off
5251 setAirplaneMode(false);
5252
Stuart Scotte3e314d2015-04-20 14:07:45 -07005253 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5254 // Untether
5255 for (String tether : getTetheredIfaces()) {
5256 untether(tether);
5257 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005258 }
5259
Stuart Scotte3e314d2015-04-20 14:07:45 -07005260 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005261 // Remove always-on package
5262 synchronized (mVpns) {
5263 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5264 if (alwaysOnPackage != null) {
5265 setAlwaysOnVpnPackage(userId, null, false);
5266 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5267 }
5268 }
5269
Stuart Scotte3e314d2015-04-20 14:07:45 -07005270 // Turn VPN off
5271 VpnConfig vpnConfig = getVpnConfig(userId);
5272 if (vpnConfig != null) {
5273 if (vpnConfig.legacy) {
5274 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5275 } else {
5276 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5277 // in the future without user intervention.
5278 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005279
Victor Changb04a5ea2016-05-30 20:36:30 +01005280 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005281 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005282 }
5283 }
5284 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005285
5286 @VisibleForTesting
5287 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5288 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5289 return new NetworkMonitor(context, handler, nai, defaultRequest);
5290 }
Erik Kline48f12f22016-04-14 17:30:59 +09005291
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005292 @VisibleForTesting
5293 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5294 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5295 }
5296
Hugo Benichicfddd682016-05-31 16:28:06 +09005297 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005298 int newNetid = NETID_UNSET;
5299 int prevNetid = NETID_UNSET;
5300 int[] transports = new int[0];
5301 boolean hadIPv4 = false;
5302 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005303
Hugo Benichi5f16f762016-04-20 12:09:33 +09005304 if (newNai != null) {
5305 newNetid = newNai.network.netId;
5306 transports = newNai.networkCapabilities.getTransportTypes();
5307 }
5308 if (prevNai != null) {
5309 prevNetid = prevNai.network.netId;
5310 final LinkProperties lp = prevNai.linkProperties;
5311 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5312 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5313 }
5314
Hugo Benichicfddd682016-05-31 16:28:06 +09005315 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5316 }
5317
5318 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5319 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005321}