blob: 8b1be3b607cdb7d5f869408fee4c2ae47bacb6e5 [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 Colitti9be58c52016-09-15 14:02:29 +0900395 /**
396 * Used internally to (re)configure avoid bad wifi setting.
397 */
398 private static final int EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI = 34;
399
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900400 /** Handler thread used for both of the handlers below. */
401 @VisibleForTesting
402 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700403 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700404 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700405 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700406 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700407
Mike Lockwood0f79b542009-08-14 14:18:49 -0400408 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800409 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400410
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700411 private PowerManager.WakeLock mNetTransitionWakeLock;
412 private String mNetTransitionWakeLockCausedBy = "";
413 private int mNetTransitionWakeLockSerialNumber;
414 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800415 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700416
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700417 // used in DBG mode to track inet condition reports
418 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
419 private ArrayList mInetLog;
420
Robert Greenwalt434203a2010-10-11 16:00:27 -0700421 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400422 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700423 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700424 private boolean mDefaultProxyDisabled = false;
425
Robert Greenwalt434203a2010-10-11 16:00:27 -0700426 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400427 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700428
Jason Monk602b2322013-07-03 17:04:33 -0400429 private PacManager mPacManager = null;
430
Erik Klineda4bfa82015-04-30 12:58:40 +0900431 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700432
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400433 private UserManager mUserManager;
434
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700435 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700436 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700437
Robert Greenwalt50393202011-06-21 17:26:14 -0700438 // the set of network types that can only be enabled by system/sig apps
439 List mProtectedNetworks;
440
John Spurlockbf991a82013-06-24 14:20:23 -0400441 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700442
Wink Savilleab9321d2013-06-29 21:10:57 -0700443 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400444
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900445 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900446 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900447 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900448
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700449 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
450 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700451 private final static int MAX_NET_ID = 65535;
452 private int mNextNetId = MIN_NET_ID;
453
Robert Greenwalt34524f02014-05-18 16:22:10 -0700454 // sequence number of NetworkRequests
455 private int mNextNetworkRequestId = 1;
456
Erik Kline7523eb32015-07-09 18:24:03 +0900457 // NetworkRequest activity String log entries.
458 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
459 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
460
Hugo Benichic2ae2872016-07-11 11:05:12 +0900461 // NetworkInfo blocked and unblocked String log entries
462 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
463 private static final int MAX_NETWORK_INFO_LOGS = 100;
464 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
465
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700466 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
467 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400468 private static class ValidationLog {
469 final Network mNetwork;
470 final String mNetworkExtraInfo;
471 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700472
Paul Jensen0808eb82016-06-03 13:51:21 -0400473 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
474 mNetwork = network;
475 mNetworkExtraInfo = networkExtraInfo;
476 mLog = log;
477 }
478 }
479 private final ArrayDeque<ValidationLog> mValidationLogs =
480 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
481
482 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700483 synchronized(mValidationLogs) {
484 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
485 mValidationLogs.removeLast();
486 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400487 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700488 }
489 }
490
Hugo Benichif9fdf872016-07-28 17:53:06 +0900491 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900492
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700493 /**
494 * Implements support for the legacy "one network per network type" model.
495 *
496 * We used to have a static array of NetworkStateTrackers, one for each
497 * network type, but that doesn't work any more now that we can have,
498 * for example, more that one wifi network. This class stores all the
499 * NetworkAgentInfo objects that support a given type, but the legacy
500 * API will only see the first one.
501 *
502 * It serves two main purposes:
503 *
504 * 1. Provide information about "the network for a given type" (since this
505 * API only supports one).
506 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
507 * the first network for a given type changes, or if the default network
508 * changes.
509 */
510 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900511
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900512 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900514
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700515 /**
516 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
517 * Each list holds references to all NetworkAgentInfos that are used to
518 * satisfy requests for that network type.
519 *
520 * This array is built out at startup such that an unsupported network
521 * doesn't get an ArrayList instance, making this a tristate:
522 * unsupported, supported but not active and active.
523 *
524 * The actual lists are populated when we scan the network types that
525 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900526 *
527 * Threading model:
528 * - addSupportedType() is only called in the constructor
529 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
530 * They are therefore not thread-safe with respect to each other.
531 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
532 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
533 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700534 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900535 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700536
537 public LegacyTypeTracker() {
538 mTypeLists = (ArrayList<NetworkAgentInfo>[])
539 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
540 }
541
542 public void addSupportedType(int type) {
543 if (mTypeLists[type] != null) {
544 throw new IllegalStateException(
545 "legacy list for type " + type + "already initialized");
546 }
547 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
548 }
549
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700550 public boolean isTypeSupported(int type) {
551 return isNetworkTypeValid(type) && mTypeLists[type] != null;
552 }
553
554 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900555 synchronized (mTypeLists) {
556 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
557 return mTypeLists[type].get(0);
558 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900560 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
562
Robert Greenwalt8d482522015-06-24 13:23:42 -0700563 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900564 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900565 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700566 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900567 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900568 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900569 }
570 }
571
572 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700573 public void add(int type, NetworkAgentInfo nai) {
574 if (!isTypeSupported(type)) {
575 return; // Invalid network type.
576 }
577 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
578
579 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
580 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700581 return;
582 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900583 synchronized (mTypeLists) {
584 list.add(nai);
585 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900586
587 // 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 +0900588 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900589 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700590 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
591 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700592 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700593 }
594
Lorenzo Colittia793a672014-07-31 23:20:17 +0900595 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900596 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900597 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
598 if (list == null || list.isEmpty()) {
599 return;
600 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900601 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900602
Hugo Benichi78caa2582016-06-21 09:48:07 +0900603 synchronized (mTypeLists) {
604 if (!list.remove(nai)) {
605 return;
606 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900607 }
608
Robert Greenwalt8d482522015-06-24 13:23:42 -0700609 final DetailedState state = DetailedState.DISCONNECTED;
610
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900611 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700612 maybeLogBroadcast(nai, state, type, wasDefault);
613 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900614 }
615
616 if (!list.isEmpty() && wasFirstNetwork) {
617 if (DBG) log("Other network available for type " + type +
618 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900619 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700620 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
621 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900622 }
623 }
624
625 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900626 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
627 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700628 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900629 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 }
631 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700632
Robert Greenwalt8d482522015-06-24 13:23:42 -0700633 // send out another legacy broadcast - currently only used for suspend/unsuspend
634 // toggle
635 public void update(NetworkAgentInfo nai) {
636 final boolean isDefault = isDefaultNetwork(nai);
637 final DetailedState state = nai.networkInfo.getDetailedState();
638 for (int type = 0; type < mTypeLists.length; type++) {
639 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700640 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900641 final boolean isFirst = contains && (nai == list.get(0));
642 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700643 maybeLogBroadcast(nai, state, type, isDefault);
644 sendLegacyNetworkBroadcast(nai, state, type);
645 }
646 }
647 }
648
Lorenzo Colittia793a672014-07-31 23:20:17 +0900649 private String naiToString(NetworkAgentInfo nai) {
650 String name = (nai != null) ? nai.name() : "null";
651 String state = (nai.networkInfo != null) ?
652 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
653 "???/???";
654 return name + " " + state;
655 }
656
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700657 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900658 pw.println("mLegacyTypeTracker:");
659 pw.increaseIndent();
660 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700661 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900662 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700663 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900664 pw.println();
665 pw.println("Current state:");
666 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900667 synchronized (mTypeLists) {
668 for (int type = 0; type < mTypeLists.length; type++) {
669 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
670 for (NetworkAgentInfo nai : mTypeLists[type]) {
671 pw.println(type + " " + naiToString(nai));
672 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900673 }
674 }
675 pw.decreaseIndent();
676 pw.decreaseIndent();
677 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700678 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700679 }
680 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
681
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900682 @VisibleForTesting
683 protected HandlerThread createHandlerThread() {
684 return new HandlerThread("ConnectivityServiceThread");
685 }
686
Jeff Sharkey899223b2012-08-04 15:24:58 -0700687 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700688 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900689 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
690 }
691
692 @VisibleForTesting
693 protected ConnectivityService(Context context, INetworkManagementService netManager,
694 INetworkStatsService statsService, INetworkPolicyManager policyManager,
695 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800696 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800697
Hugo Benichif9fdf872016-07-28 17:53:06 +0900698 mMetricsLog = logger;
Erik Klineda4bfa82015-04-30 12:58:40 +0900699 mDefaultRequest = createInternetRequestForTransport(-1);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900700 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900701 mNetworkRequests.put(mDefaultRequest, defaultNRI);
702 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900703
704 mDefaultMobileDataRequest = createInternetRequestForTransport(
705 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700706
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900707 mHandlerThread = createHandlerThread();
708 mHandlerThread.start();
709 mHandler = new InternalHandler(mHandlerThread.getLooper());
710 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700711
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800712 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800713 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
714 String id = Settings.Secure.getString(context.getContentResolver(),
715 Settings.Secure.ANDROID_ID);
716 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700717 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800718 SystemProperties.set("net.hostname", name);
719 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800720 }
721
Jeremy Joslin79294842014-12-03 17:15:28 -0800722 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
723 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
724
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900725 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
726
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700727 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700728 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800729 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700730 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700731 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700732 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700733
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700734 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600735 mPolicyManager.setConnectivityListener(mPolicyListener);
736 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700737 } catch (RemoteException e) {
738 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700739 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700740 }
741
742 final PowerManager powerManager = (PowerManager) context.getSystemService(
743 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700744 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
745 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
746 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800747 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700748
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700749 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700750
Wink Saville51f456f2013-04-23 14:26:51 -0700751 // TODO: What is the "correct" way to do determine if this is a wifi only device?
752 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
753 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700754 String[] naStrings = context.getResources().getStringArray(
755 com.android.internal.R.array.networkAttributes);
756 for (String naString : naStrings) {
757 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700758 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700759 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700760 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800761 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700762 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700763 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700764 }
Wink Saville51f456f2013-04-23 14:26:51 -0700765 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
766 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
767 n.type);
768 continue;
769 }
Wink Saville975c8482011-04-07 14:23:45 -0700770 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800771 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700772 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700773 continue;
774 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700775 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700776
Wink Saville975c8482011-04-07 14:23:45 -0700777 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700778 mNetworksDefined++;
779 } catch(Exception e) {
780 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700781 }
782 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700783
784 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
785 if (mNetConfigs[TYPE_VPN] == null) {
786 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
787 // don't need to add TYPE_VPN to mNetConfigs.
788 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
789 mNetworksDefined++; // used only in the log() statement below.
790 }
791
Wink Saville5e56bc52013-07-29 15:00:57 -0700792 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700793
Robert Greenwalt50393202011-06-21 17:26:14 -0700794 mProtectedNetworks = new ArrayList<Integer>();
795 int[] protectedNetworks = context.getResources().getIntArray(
796 com.android.internal.R.array.config_protectedNetworks);
797 for (int p : protectedNetworks) {
798 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
799 mProtectedNetworks.add(p);
800 } else {
801 if (DBG) loge("Ignoring protectedNetwork " + p);
802 }
803 }
804
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700805 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
806 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700807
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800808 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800809
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700810 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
811
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700812 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700813 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100814 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700815 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700816 intentFilter.addAction(Intent.ACTION_USER_ADDED);
817 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000818 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700819 mContext.registerReceiverAsUser(
820 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900821
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700822 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700823 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700824 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700825 } catch (RemoteException e) {
826 loge("Error registering observer :" + e);
827 }
828
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700829 if (DBG) {
830 mInetLog = new ArrayList();
831 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700832
Erik Klineda4bfa82015-04-30 12:58:40 +0900833 mSettingsObserver = new SettingsObserver(mContext, mHandler);
834 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800835
John Spurlockbf991a82013-06-24 14:20:23 -0400836 mDataConnectionStats = new DataConnectionStats(mContext);
837 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400838
Jason Monkdecd2952013-10-10 14:02:51 -0400839 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700840
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400841 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900842
843 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900844 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
845 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900846
847 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
848 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
849 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
850 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
851 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
852 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
853 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700855
Erik Klineda4bfa82015-04-30 12:58:40 +0900856 private NetworkRequest createInternetRequestForTransport(int transportType) {
857 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900858 netCap.addCapability(NET_CAPABILITY_INTERNET);
859 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900860 if (transportType > -1) {
861 netCap.addTransportType(transportType);
862 }
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900863 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(),
864 NetworkRequest.Type.REQUEST);
Erik Klineda4bfa82015-04-30 12:58:40 +0900865 }
866
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900867 // Used only for testing.
868 // TODO: Delete this and either:
869 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
870 // changing ContentResolver to make registerContentObserver non-final).
871 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
872 // by subclassing SettingsObserver.
873 @VisibleForTesting
874 void updateMobileDataAlwaysOn() {
875 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
876 }
877
Erik Klineda4bfa82015-04-30 12:58:40 +0900878 private void handleMobileDataAlwaysOn() {
879 final boolean enable = (Settings.Global.getInt(
880 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
881 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
882 if (enable == isEnabled) {
883 return; // Nothing to do.
884 }
885
886 if (enable) {
887 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900888 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900889 } else {
890 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
891 }
892 }
893
894 private void registerSettingsCallbacks() {
895 // Watch for global HTTP proxy changes.
896 mSettingsObserver.observe(
897 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
898 EVENT_APPLY_GLOBAL_HTTP_PROXY);
899
900 // Watch for whether or not to keep mobile data always on.
901 mSettingsObserver.observe(
902 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
903 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900904
905 // Watch for whether to automatically switch away from wifi networks that lose Internet
906 // access.
907 mSettingsObserver.observe(
908 Settings.Global.getUriFor(Settings.Global.NETWORK_AVOID_BAD_WIFI),
909 EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900910 }
911
Robert Greenwalt34524f02014-05-18 16:22:10 -0700912 private synchronized int nextNetworkRequestId() {
913 return mNextNetworkRequestId++;
914 }
915
Paul Jensen67b0b072015-06-10 11:22:17 -0400916 @VisibleForTesting
917 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400918 synchronized (mNetworkForNetId) {
919 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
920 int netId = mNextNetId;
921 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
922 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500923 if (!mNetIdInUse.get(netId)) {
924 mNetIdInUse.put(netId, true);
925 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400926 }
927 }
928 }
929 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700930 }
931
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600932 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800933 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600934 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
935 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800936 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600937 state = nai.getNetworkState();
938 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600940 final NetworkInfo info = new NetworkInfo(networkType, 0,
941 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800942 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
943 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600944 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
945 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800946 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600947 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600948 return state;
949 } else {
950 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800951 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400952 }
953
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800954 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
955 if (network == null) {
956 return null;
957 }
958 synchronized (mNetworkForNetId) {
959 return mNetworkForNetId.get(network.netId);
960 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600961 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800962
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900963 private Network[] getVpnUnderlyingNetworks(int uid) {
964 if (!mLockdownEnabled) {
965 int user = UserHandle.getUserId(uid);
966 synchronized (mVpns) {
967 Vpn vpn = mVpns.get(user);
968 if (vpn != null && vpn.appliesToUid(uid)) {
969 return vpn.getUnderlyingNetworks();
970 }
971 }
972 }
973 return null;
974 }
975
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800976 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400977 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800978
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900979 final Network[] networks = getVpnUnderlyingNetworks(uid);
980 if (networks != null) {
981 // getUnderlyingNetworks() returns:
982 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
983 // empty array => the VPN explicitly said "no default network".
984 // non-empty array => the VPN specified one or more default networks; we use the
985 // first one.
986 if (networks.length > 0) {
987 nai = getNetworkAgentInfoForNetwork(networks[0]);
988 } else {
989 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800990 }
991 }
992
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800993 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600994 return nai.getNetworkState();
995 } else {
996 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800997 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400998 }
999
1000 /**
1001 * Check if UID should be blocked from using the network with the given LinkProperties.
1002 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001003 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1004 boolean ignoreBlocked) {
1005 // Networks aren't blocked when ignoring blocked status
1006 if (ignoreBlocked) return false;
1007 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001008 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001009
1010 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001011 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001012
Robin Lee17e61832016-05-09 13:46:28 +01001013 synchronized (mVpns) {
1014 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1015 if (vpn != null && vpn.isBlockingUid(uid)) {
1016 return true;
1017 }
1018 }
1019
Robert Greenwalt12e67352014-05-13 21:41:06 -07001020 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001021 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001022 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001023 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001024 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001025
Felipe Lemed31a97f2016-05-06 14:53:50 -07001026 boolean allowed = true;
1027 // Check Data Saver Mode first...
1028 if (networkMetered) {
1029 if ((uidRules & RULE_REJECT_METERED) != 0) {
1030 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1031 // Explicitly blacklisted.
1032 allowed = false;
1033 } else {
1034 allowed = !mRestrictBackground
1035 || (uidRules & RULE_ALLOW_METERED) != 0
1036 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1037 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1038 + " mRestrictBackground=" + mRestrictBackground
1039 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1040 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1041 + ": " + allowed);
1042 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001043 }
Felipe Leme781ba142016-05-09 16:24:48 -07001044 // ...then power restrictions.
1045 if (allowed) {
1046 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001047 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001048 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001049 }
1050 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001051 }
1052
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001053 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001054 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1055 return;
1056 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001057 boolean removed = false;
1058 boolean added = false;
1059 synchronized (mBlockedAppUids) {
1060 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1061 added = true;
1062 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1063 removed = true;
1064 }
1065 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001066 if (added) {
1067 log("Returning blocked NetworkInfo to uid=" + uid);
1068 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1069 } else if (removed) {
1070 log("Returning unblocked NetworkInfo to uid=" + uid);
1071 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1072 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001073 }
1074
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001075 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001076 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1077 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1078 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1079 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001080 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001081 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001082 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1083
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001084 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001085 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001086 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001087 if (mLockdownTracker != null) {
1088 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001089 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001090
1091 // TODO: apply metered state closer to NetworkAgentInfo
1092 final long token = Binder.clearCallingIdentity();
1093 try {
1094 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1095 } catch (RemoteException e) {
1096 } finally {
1097 Binder.restoreCallingIdentity(token);
1098 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001099 }
1100
1101 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 * Return NetworkInfo for the active (i.e., connected) network interface.
1103 * It is assumed that at most one network is active at a time. If more
1104 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001105 * @return the info for the active network, or {@code null} if none is
1106 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001108 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001110 enforceAccessPermission();
1111 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001112 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001113 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001114 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1115 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
1117
Paul Jensen31a94f42015-02-13 14:18:39 -05001118 @Override
1119 public Network getActiveNetwork() {
1120 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001121 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001122 }
1123
1124 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001125 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001126 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001127 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001128 }
1129
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001130 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001131 final int user = UserHandle.getUserId(uid);
1132 int vpnNetId = NETID_UNSET;
1133 synchronized (mVpns) {
1134 final Vpn vpn = mVpns.get(user);
1135 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1136 }
1137 NetworkAgentInfo nai;
1138 if (vpnNetId != NETID_UNSET) {
1139 synchronized (mNetworkForNetId) {
1140 nai = mNetworkForNetId.get(vpnNetId);
1141 }
1142 if (nai != null) return nai.network;
1143 }
1144 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001145 if (nai != null
1146 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1147 nai = null;
1148 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001149 return nai != null ? nai.network : null;
1150 }
1151
Lorenzo Colitti18660282016-07-04 12:55:44 +09001152 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001153 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1154 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001155 final int uid = Binder.getCallingUid();
1156 NetworkState state = getUnfilteredActiveNetworkState(uid);
1157 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001158 }
1159
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001160 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001161 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001162 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001163 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001164 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001165 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001166 }
1167
1168 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 public NetworkInfo getNetworkInfo(int networkType) {
1170 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001171 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001172 if (getVpnUnderlyingNetworks(uid) != null) {
1173 // A VPN is active, so we may need to return one of its underlying networks. This
1174 // information is not available in LegacyTypeTracker, so we have to get it from
1175 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001176 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001177 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001178 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001179 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001180 }
1181 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001182 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001183 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001186 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001187 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001188 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001189 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001190 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001191 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001192 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001193 return state.networkInfo;
1194 } else {
1195 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001196 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001197 }
1198
1199 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 public NetworkInfo[] getAllNetworkInfo() {
1201 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001202 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001203 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1204 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001205 NetworkInfo info = getNetworkInfo(networkType);
1206 if (info != null) {
1207 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001210 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 }
1212
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001213 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001214 public Network getNetworkForType(int networkType) {
1215 enforceAccessPermission();
1216 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001217 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1218 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001219 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001220 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001221 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001222 }
1223
1224 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001225 public Network[] getAllNetworks() {
1226 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001227 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001228 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001229 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001230 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001231 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001232 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001233 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001234 }
1235
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001236 @Override
1237 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1238 // The basic principle is: if an app's traffic could possibly go over a
1239 // network, without the app doing anything multinetwork-specific,
1240 // (hence, by "default"), then include that network's capabilities in
1241 // the array.
1242 //
1243 // In the normal case, app traffic only goes over the system's default
1244 // network connection, so that's the only network returned.
1245 //
1246 // With a VPN in force, some app traffic may go into the VPN, and thus
1247 // over whatever underlying networks the VPN specifies, while other app
1248 // traffic may go over the system default network (e.g.: a split-tunnel
1249 // VPN, or an app disallowed by the VPN), so the set of networks
1250 // returned includes the VPN's underlying networks and the system
1251 // default.
1252 enforceAccessPermission();
1253
1254 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1255
1256 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001257 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001258 if (nc != null) {
1259 result.put(nai.network, nc);
1260 }
1261
1262 if (!mLockdownEnabled) {
1263 synchronized (mVpns) {
1264 Vpn vpn = mVpns.get(userId);
1265 if (vpn != null) {
1266 Network[] networks = vpn.getUnderlyingNetworks();
1267 if (networks != null) {
1268 for (Network network : networks) {
1269 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001270 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001271 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001272 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001273 }
1274 }
1275 }
1276 }
1277 }
1278 }
1279
1280 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1281 out = result.values().toArray(out);
1282 return out;
1283 }
1284
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001285 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001286 public boolean isNetworkSupported(int networkType) {
1287 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001288 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001289 }
1290
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001291 /**
1292 * Return LinkProperties for the active (i.e., connected) default
1293 * network interface. It is assumed that at most one default network
1294 * is active at a time. If more than one is active, it is indeterminate
1295 * which will be returned.
1296 * @return the ip properties for the active network, or {@code null} if
1297 * none is active
1298 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001299 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001300 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001301 enforceAccessPermission();
1302 final int uid = Binder.getCallingUid();
1303 NetworkState state = getUnfilteredActiveNetworkState(uid);
1304 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001305 }
1306
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001307 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001308 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001309 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001310 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1311 if (nai != null) {
1312 synchronized (nai) {
1313 return new LinkProperties(nai.linkProperties);
1314 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001315 }
1316 return null;
1317 }
1318
Robert Greenwalt12e67352014-05-13 21:41:06 -07001319 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001320 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001321 public LinkProperties getLinkProperties(Network network) {
1322 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001323 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001324 if (nai != null) {
1325 synchronized (nai) {
1326 return new LinkProperties(nai.linkProperties);
1327 }
1328 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001329 return null;
1330 }
1331
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001332 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001333 if (nai != null) {
1334 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001335 if (nai.networkCapabilities != null) {
1336 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001337 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001338 }
1339 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001340 return null;
1341 }
1342
1343 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001344 public NetworkCapabilities getNetworkCapabilities(Network network) {
1345 enforceAccessPermission();
1346 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1347 }
1348
1349 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001350 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001351 // Require internal since we're handing out IMSI details
1352 enforceConnectivityInternalPermission();
1353
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001354 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001355 for (Network network : getAllNetworks()) {
1356 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1357 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001358 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001359 }
1360 }
1361 return result.toArray(new NetworkState[result.size()]);
1362 }
1363
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001364 @Override
1365 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1366 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001367 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001368 final long token = Binder.clearCallingIdentity();
1369 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001370 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1371 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001372 try {
1373 return mPolicyManager.getNetworkQuotaInfo(state);
1374 } catch (RemoteException e) {
1375 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001376 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001377 return null;
1378 } finally {
1379 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001380 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001381 }
1382
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001383 @Override
1384 public boolean isActiveNetworkMetered() {
1385 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001386
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001387 final NetworkInfo info = getActiveNetworkInfo();
1388 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001389 }
1390
Jeff Sharkey216c1812012-08-05 14:29:23 -07001391 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1392 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001393 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001394 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001395 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001396 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001397 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001398
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001399 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 * Ensure that a network route exists to deliver traffic to the specified
1401 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001402 * @param networkType the type of the network over which traffic to the
1403 * specified host is to be routed
1404 * @param hostAddress the IP address of the host to which the route is
1405 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 * @return {@code true} on success, {@code false} on failure
1407 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001408 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001409 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001411 if (mProtectedNetworks.contains(networkType)) {
1412 enforceConnectivityInternalPermission();
1413 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001414
Chad Brubakerc0234532014-02-14 13:24:29 -08001415 InetAddress addr;
1416 try {
1417 addr = InetAddress.getByAddress(hostAddress);
1418 } catch (UnknownHostException e) {
1419 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1420 return false;
1421 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001424 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 return false;
1426 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001427
1428 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1429 if (nai == null) {
1430 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1431 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1432 } else {
1433 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1434 }
1435 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001436 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001437
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001438 DetailedState netState;
1439 synchronized (nai) {
1440 netState = nai.networkInfo.getDetailedState();
1441 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001442
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001443 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001444 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001445 log("requestRouteToHostAddress on down network "
1446 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001447 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001448 }
1449 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001451
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001452 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001453 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001454 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001455 LinkProperties lp;
1456 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001457 synchronized (nai) {
1458 lp = nai.linkProperties;
1459 netId = nai.network.netId;
1460 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001461 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001462 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1463 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001464 } finally {
1465 Binder.restoreCallingIdentity(token);
1466 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001467 }
1468
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001469 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001470 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001471 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001472 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001473 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001474 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001475 if (bestRoute.getGateway().equals(addr)) {
1476 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001477 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001478 } else {
1479 // if we will connect to this through another route, add a direct route
1480 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001481 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001482 }
1483 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001484 if (DBG) log("Adding legacy route " + bestRoute +
1485 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001486 try {
1487 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1488 } catch (Exception e) {
1489 // never crash - catch them all
1490 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001491 return false;
1492 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001493 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001496 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1497 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001498 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001499 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001500 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001501 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001502 }
1503
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001504 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001505 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001506 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001507 if (oldRules == uidRules) return;
1508
Felipe Leme781ba142016-05-09 16:24:48 -07001509 if (uidRules == RULE_NONE) {
1510 mUidRules.delete(uid);
1511 } else {
1512 mUidRules.put(uid, uidRules);
1513 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001514 }
1515
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001516 // TODO: notify UID when it has requested targeted updates
1517 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001518
1519 @Override
1520 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001521 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001522 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001523 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001524 }
1525
1526 synchronized (mRulesLock) {
1527 mMeteredIfaces.clear();
1528 for (String iface : meteredIfaces) {
1529 mMeteredIfaces.add(iface);
1530 }
1531 }
1532 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001533
1534 @Override
1535 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1536 // caller is NPMS, since we only register with them
1537 if (LOGD_RULES) {
1538 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1539 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001540
1541 synchronized (mRulesLock) {
1542 mRestrictBackground = restrictBackground;
1543 }
1544
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001545 if (restrictBackground) {
1546 log("onRestrictBackgroundChanged(true): disabling tethering");
1547 mTethering.untetherAll();
1548 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001549 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001550
1551 @Override
1552 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1553 if (LOGD_RULES) {
1554 // caller is NPMS, since we only register with them
1555 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1556 + whitelisted + ")");
1557 }
1558 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001559 @Override
1560 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1561 if (LOGD_RULES) {
1562 // caller is NPMS, since we only register with them
1563 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1564 + blacklisted + ")");
1565 }
1566 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001567 };
1568
Robin Lee3b3dd942015-05-12 18:14:58 +01001569 /**
1570 * Require that the caller is either in the same user or has appropriate permission to interact
1571 * across users.
1572 *
1573 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1574 */
1575 private void enforceCrossUserPermission(int userId) {
1576 if (userId == UserHandle.getCallingUserId()) {
1577 // Not a cross-user call.
1578 return;
1579 }
1580 mContext.enforceCallingOrSelfPermission(
1581 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1582 "ConnectivityService");
1583 }
1584
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001585 private void enforceInternetPermission() {
1586 mContext.enforceCallingOrSelfPermission(
1587 android.Manifest.permission.INTERNET,
1588 "ConnectivityService");
1589 }
1590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001592 mContext.enforceCallingOrSelfPermission(
1593 android.Manifest.permission.ACCESS_NETWORK_STATE,
1594 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 }
1596
1597 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001598 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
1600
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001601 private void enforceTetherAccessPermission() {
1602 mContext.enforceCallingOrSelfPermission(
1603 android.Manifest.permission.ACCESS_NETWORK_STATE,
1604 "ConnectivityService");
1605 }
1606
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001607 private void enforceConnectivityInternalPermission() {
1608 mContext.enforceCallingOrSelfPermission(
1609 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1610 "ConnectivityService");
1611 }
1612
Hugo Benichi514da602016-07-19 15:59:27 +09001613 private void enforceConnectivityRestrictedNetworksPermission() {
1614 try {
1615 mContext.enforceCallingOrSelfPermission(
1616 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1617 "ConnectivityService");
1618 return;
1619 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1620 enforceConnectivityInternalPermission();
1621 }
1622
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001623 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001624 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001625 }
1626
Lorenzo Colitti18660282016-07-04 12:55:44 +09001627 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001628 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001629 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001630 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001631 }
1632
1633 private void sendInetConditionBroadcast(NetworkInfo info) {
1634 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1635 }
1636
Wink Saville628b0852011-08-04 15:01:58 -07001637 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001638 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001639 info = new NetworkInfo(info);
1640 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001641 }
1642
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001643 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001644 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001645 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 if (info.isFailover()) {
1647 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1648 info.setFailover(false);
1649 }
1650 if (info.getReason() != null) {
1651 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1652 }
1653 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001654 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1655 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001657 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001658 return intent;
1659 }
1660
1661 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1662 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1663 }
1664
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001665 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001666 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1667 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1668 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001669 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001670 final long ident = Binder.clearCallingIdentity();
1671 try {
1672 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1673 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1674 } finally {
1675 Binder.restoreCallingIdentity(ident);
1676 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001677 }
1678
Mike Lockwood0f79b542009-08-14 14:18:49 -04001679 private void sendStickyBroadcast(Intent intent) {
1680 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001681 if (!mSystemReady) {
1682 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001683 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001684 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001685 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001686 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001687 }
1688
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001689 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001690 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001691 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001692 final NetworkInfo ni = intent.getParcelableExtra(
1693 ConnectivityManager.EXTRA_NETWORK_INFO);
1694 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1695 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1696 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001697 } else {
1698 BroadcastOptions opts = BroadcastOptions.makeBasic();
1699 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1700 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001701 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001702 final IBatteryStats bs = BatteryStatsService.getService();
1703 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001704 bs.noteConnectivityChanged(intent.getIntExtra(
1705 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1706 ni != null ? ni.getState().toString() : "?");
1707 } catch (RemoteException e) {
1708 }
1709 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001710 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001711 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001712 } finally {
1713 Binder.restoreCallingIdentity(ident);
1714 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001715 }
1716 }
1717
1718 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001719 loadGlobalProxy();
1720
Mike Lockwood0f79b542009-08-14 14:18:49 -04001721 synchronized(this) {
1722 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001723 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001724 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001725 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001726 }
1727 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001728 // load the global proxy at startup
1729 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001730
Robin Lee244ce8e2016-01-05 18:03:46 +00001731 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1732 // for user to unlock device too.
1733 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001734
Erik Klineda4bfa82015-04-30 12:58:40 +09001735 // Configure whether mobile data is always on.
1736 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1737
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001738 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001739
1740 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 }
1742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001744 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001745 *
1746 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001747 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001748 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001749 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1750 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001751
1752 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001753 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001754
Robert Greenwalt7b816022014-04-18 15:25:25 -07001755 if (networkAgent.networkCapabilities.hasTransport(
1756 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001757 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1758 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001759 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001760 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001761 } else if (networkAgent.networkCapabilities.hasTransport(
1762 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001763 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1764 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001765 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001766 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001767 } else {
1768 // do not track any other networks
1769 timeout = 0;
1770 }
1771
Robert Greenwalt7b816022014-04-18 15:25:25 -07001772 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001773 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001774 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001775 } catch (Exception e) {
1776 // You shall not crash!
1777 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001778 }
1779 }
1780 }
1781
1782 /**
1783 * Remove data activity tracking when network disconnects.
1784 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001785 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1786 final String iface = networkAgent.linkProperties.getInterfaceName();
1787 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001788
Robert Greenwalt7b816022014-04-18 15:25:25 -07001789 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1790 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001791 try {
1792 // the call fails silently if no idletimer setup for this interface
1793 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001794 } catch (Exception e) {
1795 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001796 }
1797 }
1798 }
1799
1800 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001801 * Reads the network specific MTU size from reources.
1802 * and set it on it's iface.
1803 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001804 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1805 final String iface = newLp.getInterfaceName();
1806 final int mtu = newLp.getMtu();
1807 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1808 if (VDBG) log("identical MTU - not setting");
1809 return;
1810 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001811
Robert Greenwalt43074032014-08-15 17:53:05 -07001812 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001813 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001814 return;
1815 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001816
w1997615afd812014-08-05 15:18:11 -07001817 // Cannot set MTU without interface name
1818 if (TextUtils.isEmpty(iface)) {
1819 loge("Setting MTU size with null iface.");
1820 return;
1821 }
1822
Robert Greenwalt7b816022014-04-18 15:25:25 -07001823 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001824 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001825 mNetd.setMtu(iface, mtu);
1826 } catch (Exception e) {
1827 Slog.e(TAG, "exception in setMtu()" + e);
1828 }
1829 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001830
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001831 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001832 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1833
1834 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001835 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001836 protected int getDefaultTcpRwnd() {
1837 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1838 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001839
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001840 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1841 if (isDefaultNetwork(nai) == false) {
1842 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001843 }
1844
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001845 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1846 String[] values = null;
1847 if (tcpBufferSizes != null) {
1848 values = tcpBufferSizes.split(",");
1849 }
1850
1851 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001852 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001853 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1854 values = tcpBufferSizes.split(",");
1855 }
1856
1857 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1858
1859 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001860 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001861
1862 final String prefix = "/sys/kernel/ipv4/tcp_";
1863 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1864 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1865 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1866 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1867 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1868 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1869 mCurrentTcpBufferSizes = tcpBufferSizes;
1870 } catch (IOException e) {
1871 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001872 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001873
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001874 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001875 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001876 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1877 if (rwndValue != 0) {
1878 SystemProperties.set(sysctlKey, rwndValue.toString());
1879 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001880 }
1881
Mattias Falk8b47b362011-08-23 14:15:13 +02001882 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001883 /*
1884 * Tell the VMs to toss their DNS caches
1885 */
1886 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1887 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001888 /*
1889 * Connectivity events can happen before boot has completed ...
1890 */
1891 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001892 final long ident = Binder.clearCallingIdentity();
1893 try {
1894 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1895 } finally {
1896 Binder.restoreCallingIdentity(ident);
1897 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001898 }
1899
Robert Greenwalt562cc542014-05-15 18:07:26 -07001900 @Override
1901 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001902 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1903 NETWORK_RESTORE_DELAY_PROP_NAME);
1904 if(restoreDefaultNetworkDelayStr != null &&
1905 restoreDefaultNetworkDelayStr.length() != 0) {
1906 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001907 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001908 } catch (NumberFormatException e) {
1909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001911 // if the system property isn't set, use the value for the apn type
1912 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1913
1914 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1915 (mNetConfigs[networkType] != null)) {
1916 ret = mNetConfigs[networkType].restoreTime;
1917 }
1918 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 }
1920
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001921 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001922 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001923 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001924 }
1925 return false;
1926 }
1927
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001928 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1929 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1930 final long DIAG_TIME_MS = 5000;
1931 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1932 // Start gathering diagnostic information.
1933 netDiags.add(new NetworkDiagnostics(
1934 nai.network,
1935 new LinkProperties(nai.linkProperties), // Must be a copy.
1936 DIAG_TIME_MS));
1937 }
1938
1939 for (NetworkDiagnostics netDiag : netDiags) {
1940 pw.println();
1941 netDiag.waitForMeasurements();
1942 netDiag.dump(pw);
1943 }
1944 }
1945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001947 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1948 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001949 if (mContext.checkCallingOrSelfPermission(
1950 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001952 pw.println("Permission Denial: can't dump ConnectivityService " +
1953 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1954 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 return;
1956 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001957
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001958 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001959 dumpNetworkDiagnostics(pw);
1960 return;
1961 }
Erik Kline379747a2015-06-05 17:47:34 +09001962
Lorenzo Colittie3805462015-06-03 11:18:24 +09001963 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001964 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001965 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001966 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001967 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001968 pw.println();
1969
Paul Jensen85cf78e2015-06-25 13:25:07 -04001970 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001971 pw.print("Active default network: ");
1972 if (defaultNai == null) {
1973 pw.println("none");
1974 } else {
1975 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001977 pw.println();
1978
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001979 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001980 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001981 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1982 pw.println(nai.toString());
1983 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001984 pw.println(String.format("Requests: %d request/%d total",
1985 nai.numRequestNetworkRequests(), nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001986 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001987 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1988 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001989 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001990 pw.decreaseIndent();
1991 pw.println("Lingered:");
1992 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001993 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001994 pw.decreaseIndent();
1995 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001996 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001997 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001998 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001999
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002000 pw.println("Metered Interfaces:");
2001 pw.increaseIndent();
2002 for (String value : mMeteredIfaces) {
2003 pw.println(value);
2004 }
2005 pw.decreaseIndent();
2006 pw.println();
2007
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002008 pw.print("Restrict background: ");
2009 pw.println(mRestrictBackground);
2010 pw.println();
2011
Felipe Leme46c4fc32016-05-04 09:21:43 -07002012 pw.println("Status for known UIDs:");
2013 pw.increaseIndent();
2014 final int size = mUidRules.size();
2015 for (int i = 0; i < size; i++) {
2016 final int uid = mUidRules.keyAt(i);
2017 pw.print("UID=");
2018 pw.print(uid);
2019 final int uidRules = mUidRules.get(uid, RULE_NONE);
2020 pw.print(" rules=");
2021 pw.print(uidRulesToString(uidRules));
2022 pw.println();
2023 }
2024 pw.println();
2025 pw.decreaseIndent();
2026
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002027 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002028 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002029 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2030 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002031 }
2032 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002033 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002034
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002035 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002036
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002037 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002038 pw.print("mNetTransitionWakeLock: currently " +
2039 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2040 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2041 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2042 } else {
2043 pw.println(", last requested never");
2044 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002045 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002046
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002047 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002048 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002049
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002050 pw.println();
2051 mKeepaliveTracker.dump(pw);
2052
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002053 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002054
Lorenzo Colittie3805462015-06-03 11:18:24 +09002055 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002056 pw.println();
2057 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002058 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002059 for(int i = 0; i < mInetLog.size(); i++) {
2060 pw.println(mInetLog.get(i));
2061 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002062 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002063 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002064
2065 if (argsContain(args, "--short") == false) {
2066 pw.println();
2067 synchronized (mValidationLogs) {
2068 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002069 for (ValidationLog p : mValidationLogs) {
2070 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002071 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002072 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002073 pw.decreaseIndent();
2074 }
2075 }
Erik Kline7523eb32015-07-09 18:24:03 +09002076
2077 pw.println();
2078 pw.println("mNetworkRequestInfoLogs (most recent first):");
2079 pw.increaseIndent();
2080 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2081 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002082
2083 pw.println();
2084 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2085 pw.increaseIndent();
2086 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2087 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002091 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002092 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002093 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002094 if (officialNai != null && officialNai.equals(nai)) return true;
2095 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002096 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002097 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002098 " - " + nai);
2099 }
2100 return false;
2101 }
2102
Robert Greenwalt42acef32009-08-12 16:08:25 -07002103 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002104 private class NetworkStateTrackerHandler extends Handler {
2105 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002106 super(looper);
2107 }
2108
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002109 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002111 default:
2112 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002113 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002114 handleAsyncChannelHalfConnect(msg);
2115 break;
2116 }
2117 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2118 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2119 if (nai != null) nai.asyncChannel.disconnect();
2120 break;
2121 }
2122 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2123 handleAsyncChannelDisconnected(msg);
2124 break;
2125 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002126 }
2127 return true;
2128 }
2129
2130 private void maybeHandleNetworkAgentMessage(Message msg) {
2131 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2132 if (nai == null) {
2133 if (VDBG) {
2134 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2135 log(String.format("%s from unknown NetworkAgent", what));
2136 }
2137 return;
2138 }
2139
2140 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002141 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002142 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2143 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2144 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2145 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002146 }
Robin Lee585e2482016-05-01 23:00:00 +01002147 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002148 networkCapabilities)) {
2149 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2150 + nai.networkCapabilities + " -> " + networkCapabilities);
2151 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002152 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002153 break;
2154 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002155 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002156 if (VDBG) {
2157 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002158 "; created=" + nai.created +
2159 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002160 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002161 LinkProperties oldLp = nai.linkProperties;
2162 synchronized (nai) {
2163 nai.linkProperties = (LinkProperties)msg.obj;
2164 }
Robin Lee585e2482016-05-01 23:00:00 +01002165 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 break;
2167 }
2168 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002169 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002170 updateNetworkInfo(nai, info);
2171 break;
2172 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002173 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002174 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002175 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002176 break;
2177 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002178 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002179 try {
2180 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002181 } catch (Exception e) {
2182 // Never crash!
2183 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002184 }
2185 break;
2186 }
2187 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002188 try {
2189 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002190 } catch (Exception e) {
2191 // Never crash!
2192 loge("Exception in removeVpnUidRanges: " + e);
2193 }
2194 break;
2195 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002196 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002197 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2198 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002199 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002200 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002201 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002202 break;
2203 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002204 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002205 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2206 break;
2207 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002208 }
2209 }
2210
2211 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2212 switch (msg.what) {
2213 default:
2214 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002215 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002216 final NetworkAgentInfo nai;
2217 synchronized (mNetworkForNetId) {
2218 nai = mNetworkForNetId.get(msg.arg2);
2219 }
2220 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002221 final boolean valid =
2222 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002223 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002224 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2225 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002226 if (valid != nai.lastValidated) {
2227 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002228 nai.lastValidated = valid;
2229 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002230 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002231 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2232 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002233 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002234 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002235 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002236 Bundle redirectUrlBundle = new Bundle();
2237 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002238 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002239 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002240 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002241 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002242 if (wasValidated && !nai.lastValidated) {
2243 handleNetworkUnvalidated(nai);
2244 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002245 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002246 break;
2247 }
Paul Jensen869868be2014-05-15 10:33:05 -04002248 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002249 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002250 final boolean visible = (msg.arg1 != 0);
2251 final NetworkAgentInfo nai;
2252 synchronized (mNetworkForNetId) {
2253 nai = mNetworkForNetId.get(netId);
2254 }
2255 // If captive portal status has changed, update capabilities.
2256 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002257 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002258 nai.lastCaptivePortalDetected = visible;
2259 nai.everCaptivePortalDetected |= visible;
Hugo Benichif15b2822016-09-15 18:18:48 +09002260 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002261 }
2262 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002263 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002264 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002265 if (nai == null) {
2266 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2267 break;
2268 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002269 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002270 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002271 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002272 }
Paul Jensen869868be2014-05-15 10:33:05 -04002273 }
Paul Jensen869868be2014-05-15 10:33:05 -04002274 break;
2275 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002276 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002277 return true;
2278 }
2279
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002280 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2281 switch (msg.what) {
2282 default:
2283 return false;
2284 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2285 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2286 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2287 handleLingerComplete(nai);
2288 }
2289 break;
2290 }
2291 }
2292 return true;
2293 }
2294
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002295 @Override
2296 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002297 if (!maybeHandleAsyncChannelMessage(msg) &&
2298 !maybeHandleNetworkMonitorMessage(msg) &&
2299 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002300 maybeHandleNetworkAgentMessage(msg);
2301 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002302 }
2303 }
2304
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002305 private void updateLingerState(NetworkAgentInfo nai, long now) {
2306 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2307 // 2. If the network was lingering and there are now requests, unlinger it.
2308 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2309 // one lingered request, start lingering.
2310 nai.updateLingerTimer();
2311 if (nai.isLingering() && nai.numRequestNetworkRequests() > 0) {
2312 if (DBG) log("Unlingering " + nai.name());
2313 nai.unlinger();
2314 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
2315 } else if (unneeded(nai) && nai.getLingerExpiry() > 0) { // unneeded() calls isLingering()
2316 int lingerTime = (int) (nai.getLingerExpiry() - now);
2317 if (DBG) {
2318 Log.d(TAG, "Lingering " + nai.name() + " for " + lingerTime + "ms");
2319 }
2320 nai.linger();
2321 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2322 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2323 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002324 }
2325
Robert Greenwalt7b816022014-04-18 15:25:25 -07002326 private void handleAsyncChannelHalfConnect(Message msg) {
2327 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002328 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002329 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2330 if (VDBG) log("NetworkFactory connected");
2331 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002332 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002333 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002334 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002335 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002336 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002337 }
2338 } else {
2339 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002340 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002341 }
2342 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2343 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2344 if (VDBG) log("NetworkAgent connected");
2345 // A network agent has requested a connection. Establish the connection.
2346 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2347 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2348 } else {
2349 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002350 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002351 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002352 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002353 synchronized (mNetworkForNetId) {
2354 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002355 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002356 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002357 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002358 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002359 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002360 }
2361 }
2362 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002363
Robert Greenwalt7b816022014-04-18 15:25:25 -07002364 private void handleAsyncChannelDisconnected(Message msg) {
2365 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2366 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002367 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002368 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002369 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002370 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002371 // TODO - if we move the logic to the network agent (have them disconnect
2372 // because they lost all their requests or because their score isn't good)
2373 // then they would disconnect organically, report their new state and then
2374 // disconnect the channel.
2375 if (nai.networkInfo.isConnected()) {
2376 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2377 null, null);
2378 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002379 final boolean wasDefault = isDefaultNetwork(nai);
2380 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002381 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002382 // Log default network disconnection before required book-keeping.
2383 // Let rematchAllNetworksAndRequests() below record a new default network event
2384 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2385 // whose timestamps tell how long it takes to recover a default network.
2386 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002387 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002388 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002389 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2390 // by other networks that are already connected. Perhaps that can be done by
2391 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2392 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002393 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002394 mKeepaliveTracker.handleStopAllKeepalives(nai,
2395 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002396 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002397 mNetworkAgentInfos.remove(msg.replyTo);
2398 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002399 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002400 // Remove the NetworkAgent, but don't mark the netId as
2401 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002402 mNetworkForNetId.remove(nai.network.netId);
2403 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002404 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002405 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2406 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002407 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2408 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2409 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002410 sendUpdatedScoreToFactories(request, 0);
2411 }
2412 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002413 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002414 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002415 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002416 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002417 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002418 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002419 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002420 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002421 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002422 if (nai.created) {
2423 // Tell netd to clean up the configuration for this network
2424 // (routing rules, DNS, etc).
2425 // This may be slow as it requires a lot of netd shelling out to ip and
2426 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2427 // after we've rematched networks with requests which should make a potential
2428 // fallback network the default or requested a new network from the
2429 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2430 // long time.
2431 try {
2432 mNetd.removeNetwork(nai.network.netId);
2433 } catch (Exception e) {
2434 loge("Exception removing network: " + e);
2435 }
2436 }
2437 synchronized (mNetworkForNetId) {
2438 mNetIdInUse.delete(nai.network.netId);
2439 }
2440 } else {
2441 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2442 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002443 }
2444 }
2445
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002446 // If this method proves to be too slow then we can maintain a separate
2447 // pendingIntent => NetworkRequestInfo map.
2448 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2449 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2450 Intent intent = pendingIntent.getIntent();
2451 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2452 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2453 if (existingPendingIntent != null &&
2454 existingPendingIntent.getIntent().filterEquals(intent)) {
2455 return entry.getValue();
2456 }
2457 }
2458 return null;
2459 }
2460
2461 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2462 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2463
2464 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2465 if (existingRequest != null) { // remove the existing request.
2466 if (DBG) log("Replacing " + existingRequest.request + " with "
2467 + nri.request + " because their intents matched.");
2468 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2469 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002470 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002471 }
2472
Erik Klineda4bfa82015-04-30 12:58:40 +09002473 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002474 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002475 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002476 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002477 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002478 if (nri.request.networkCapabilities.hasSignalStrength() &&
2479 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2480 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002481 }
2482 }
2483 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002484 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002485 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002486 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002487 }
2488 }
2489
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002490 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2491 int callingUid) {
2492 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2493 if (nri != null) {
2494 handleReleaseNetworkRequest(nri.request, callingUid);
2495 }
2496 }
2497
Paul Jensen99364842014-12-09 11:43:45 -05002498 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002499 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2500 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002501 private boolean unneeded(NetworkAgentInfo nai) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002502 if (!nai.everConnected || nai.isVPN() ||
2503 nai.isLingering() || nai.numRequestNetworkRequests() > 0) {
2504 return false;
2505 }
Paul Jensene0988542015-06-25 15:30:08 -04002506 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2507 // If this Network is already the highest scoring Network for a request, or if
2508 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002509 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002510 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002511 // Note that this catches two important cases:
2512 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2513 // is currently satisfying the request. This is desirable when
2514 // cellular ends up validating but WiFi does not.
2515 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002516 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002517 // WiFi ends up validating and out scoring cellular.
2518 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2519 nai.getCurrentScoreAsValidated())) {
2520 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002521 }
2522 }
Paul Jensene0988542015-06-25 15:30:08 -04002523 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002524 }
2525
Erik Klineacdd6392016-07-07 16:50:58 +09002526 private NetworkRequestInfo getNriForAppRequest(
2527 NetworkRequest request, int callingUid, String requestedOperation) {
2528 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2529
Robert Greenwalt9258c642014-03-26 16:47:06 -07002530 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002531 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002532 log(String.format("UID %d attempted to %s for unowned request %s",
2533 callingUid, requestedOperation, nri));
2534 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002535 }
Erik Klineacdd6392016-07-07 16:50:58 +09002536 }
2537
2538 return nri;
2539 }
2540
2541 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2542 String description, int callbackType) {
2543 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2544 if (nri == null) return;
2545
2546 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2547 // The network that is satisfying this request may have changed since
2548 // the application requested the update.
2549 //
2550 // - If the request is no longer satisfied, don't send any updates.
2551 // - If the request is satisfied by a different network, it is the
2552 // caller's responsibility to check that the Network object in the
2553 // callback matches the network that was returned in the last
2554 // onAvailable() callback for this request.
2555 if (nai == null) return;
2556 callCallbackForRequest(nri, nai, callbackType, 0);
2557 }
2558
2559 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2560 handleRequestCallbackUpdate(request, callingUid,
2561 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2562 }
2563
2564 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2565 handleRequestCallbackUpdate(request, callingUid,
2566 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2567 }
2568
2569 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2570 final NetworkRequestInfo nri = getNriForAppRequest(
2571 request, callingUid, "release NetworkRequest");
2572 if (nri == null) return;
2573
2574 if (VDBG || (DBG && nri.request.isRequest())) log("releasing " + request);
2575 nri.unlinkDeathRecipient();
2576 mNetworkRequests.remove(request);
2577 synchronized (mUidToNetworkRequestCount) {
2578 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2579 if (requests < 1) {
2580 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2581 nri.mUid);
2582 } else if (requests == 1) {
2583 mUidToNetworkRequestCount.removeAt(
2584 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2585 } else {
2586 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2587 }
2588 }
2589 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2590 if (nri.request.isRequest()) {
2591 boolean wasKept = false;
2592 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2593 if (nai != null) {
2594 nai.removeRequest(nri.request.requestId);
2595 if (VDBG) {
2596 log(" Removing from current network " + nai.name() +
2597 ", leaving " + nai.numNetworkRequests() + " requests.");
2598 }
2599 // If there are still lingered requests on this network, don't tear it down,
2600 // but resume lingering instead.
2601 updateLingerState(nai, SystemClock.elapsedRealtime());
2602 if (unneeded(nai)) {
2603 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2604 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002605 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002606 wasKept = true;
2607 }
2608 mNetworkForRequestId.remove(nri.request.requestId);
2609 }
2610
2611 // TODO: remove this code once we know that the Slog.wtf is never hit.
2612 //
2613 // Find all networks that are satisfying this request and remove the request
2614 // from their request lists.
2615 // TODO - it's my understanding that for a request there is only a single
2616 // network satisfying it, so this loop is wasteful
2617 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2618 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2619 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2620 otherNai.name() + ", but mNetworkAgentInfos says " +
2621 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002622 }
2623 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002624
Erik Klineacdd6392016-07-07 16:50:58 +09002625 // Maintain the illusion. When this request arrived, we might have pretended
2626 // that a network connected to serve it, even though the network was already
2627 // connected. Now that this request has gone away, we might have to pretend
2628 // that the network disconnected. LegacyTypeTracker will generate that
2629 // phantom disconnect for this type.
2630 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2631 boolean doRemove = true;
2632 if (wasKept) {
2633 // check if any of the remaining requests for this network are for the
2634 // same legacy type - if so, don't remove the nai
2635 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2636 NetworkRequest otherRequest = nai.requestAt(i);
2637 if (otherRequest.legacyType == nri.request.legacyType &&
2638 otherRequest.isRequest()) {
2639 if (DBG) log(" still have other legacy request - leaving");
2640 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002641 }
2642 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002643 }
2644
Erik Klineacdd6392016-07-07 16:50:58 +09002645 if (doRemove) {
2646 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002647 }
2648 }
Erik Klineacdd6392016-07-07 16:50:58 +09002649
2650 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2651 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2652 nri.request);
2653 }
2654 } else {
2655 // listens don't have a singular affectedNetwork. Check all networks to see
2656 // if this listen request applies and remove it.
2657 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2658 nai.removeRequest(nri.request.requestId);
2659 if (nri.request.networkCapabilities.hasSignalStrength() &&
2660 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2661 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2662 }
2663 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002664 }
Erik Klineacdd6392016-07-07 16:50:58 +09002665 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002666 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002667
Lorenzo Colitti18660282016-07-04 12:55:44 +09002668 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002669 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2670 enforceConnectivityInternalPermission();
2671 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2672 accept ? 1 : 0, always ? 1: 0, network));
2673 }
2674
2675 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2676 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2677 " accept=" + accept + " always=" + always);
2678
2679 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2680 if (nai == null) {
2681 // Nothing to do.
2682 return;
2683 }
2684
2685 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002686 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002687 return;
2688 }
2689
2690 if (!nai.networkMisc.explicitlySelected) {
2691 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2692 }
2693
2694 if (accept != nai.networkMisc.acceptUnvalidated) {
2695 int oldScore = nai.getCurrentScore();
2696 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002697 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002698 sendUpdatedScoreToFactories(nai);
2699 }
2700
2701 if (always) {
2702 nai.asyncChannel.sendMessage(
2703 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2704 }
2705
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002706 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002707 // Tell the NetworkAgent to not automatically reconnect to the network.
2708 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2709 // Teardown the nework.
2710 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002711 }
2712
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002713 }
2714
2715 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002716 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002717 mHandler.sendMessageDelayed(
2718 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2719 PROMPT_UNVALIDATED_DELAY_MS);
2720 }
2721
Hugo Benichic8e9e122016-09-14 23:23:08 +00002722 @VisibleForTesting
2723 public boolean avoidBadWifi() {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002724 // There are two modes: either we always automatically avoid unvalidated wifi, or we show a
2725 // dialog and don't switch to it. The behaviour is controlled by the NETWORK_AVOID_BAD_WIFI
2726 // setting. If the setting has no value, then the value is taken from the config value,
2727 // which can be changed via OEM/carrier overlays.
Hugo Benichic8e9e122016-09-14 23:23:08 +00002728 int defaultAvoidBadWifi =
2729 mContext.getResources().getInteger(R.integer.config_networkAvoidBadWifi);
2730 int avoid = Settings.Global.getInt(mContext.getContentResolver(),
2731 Settings.Global.NETWORK_AVOID_BAD_WIFI, defaultAvoidBadWifi);
2732 return avoid == 1;
2733 }
2734
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002735 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2736 final String action;
2737 switch (type) {
2738 case NO_INTERNET:
2739 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2740 break;
2741 case LOST_INTERNET:
2742 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2743 break;
2744 default:
2745 Slog.wtf(TAG, "Unknown notification type " + type);
2746 return;
2747 }
2748
2749 Intent intent = new Intent(action);
2750 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2751 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2752 intent.setClassName("com.android.settings",
2753 "com.android.settings.wifi.WifiNoInternetDialog");
2754
2755 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2756 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2757 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2758 }
2759
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002760 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002761 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002762 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2763
2764 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2765 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002766 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002767 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002768 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2769 return;
2770 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002771 showValidationNotification(nai, NotificationType.NO_INTERNET);
2772 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002773
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002774 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2775 NetworkCapabilities nc = nai.networkCapabilities;
2776 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002777
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002778 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && !avoidBadWifi()) {
2779 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2780 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002781 }
2782
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002783 private class InternalHandler extends Handler {
2784 public InternalHandler(Looper looper) {
2785 super(looper);
2786 }
2787
2788 @Override
2789 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002790 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002791 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002792 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002793 String causedBy = null;
2794 synchronized (ConnectivityService.this) {
2795 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2796 mNetTransitionWakeLock.isHeld()) {
2797 mNetTransitionWakeLock.release();
2798 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002799 } else {
2800 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002801 }
2802 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002803 if (VDBG) {
2804 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2805 log("Failed to find a new network - expiring NetTransition Wakelock");
2806 } else {
2807 log("NetTransition Wakelock (" +
2808 (causedBy == null ? "unknown" : causedBy) +
2809 " cleared because we found a replacement network");
2810 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002811 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002812 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002813 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002814 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002815 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002816 break;
2817 }
Jason Monkdecd2952013-10-10 14:02:51 -04002818 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002819 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002820 break;
2821 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002822 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002823 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2824 break;
2825 }
2826 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2827 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002828 break;
2829 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002830 case EVENT_REGISTER_NETWORK_AGENT: {
2831 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2832 break;
2833 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002834 case EVENT_REGISTER_NETWORK_REQUEST:
2835 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002836 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002837 break;
2838 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002839 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2840 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002841 handleRegisterNetworkRequestWithIntent(msg);
2842 break;
2843 }
2844 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2845 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2846 break;
2847 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002848 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002849 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002850 break;
2851 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002852 case EVENT_SET_ACCEPT_UNVALIDATED: {
2853 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2854 break;
2855 }
2856 case EVENT_PROMPT_UNVALIDATED: {
2857 handlePromptUnvalidated((Network) msg.obj);
2858 break;
2859 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002860 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2861 handleMobileDataAlwaysOn();
2862 break;
2863 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002864 case EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI: {
2865 rematchAllNetworksAndRequests(null, 0);
2866 break;
2867 }
Erik Klineacdd6392016-07-07 16:50:58 +09002868 case EVENT_REQUEST_LINKPROPERTIES:
2869 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2870 break;
2871 case EVENT_REQUEST_NETCAPABILITIES:
2872 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2873 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002874 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2875 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2876 mKeepaliveTracker.handleStartKeepalive(msg);
2877 break;
2878 }
2879 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2880 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2881 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2882 int slot = msg.arg1;
2883 int reason = msg.arg2;
2884 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2885 break;
2886 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002887 case EVENT_SYSTEM_READY: {
2888 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2889 nai.networkMonitor.systemReady = true;
2890 }
2891 break;
2892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 }
2894 }
2895 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002896
2897 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002898 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002899 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002900 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002901 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002902 final int status = mTethering.tether(iface);
2903 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2904 try {
2905 mPolicyManager.onTetheringChanged(iface, true);
2906 } catch (RemoteException e) {
2907 }
2908 }
2909 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002910 } else {
2911 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2912 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002913 }
2914
2915 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002916 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002917 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002918 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002919
2920 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002921 final int status = mTethering.untether(iface);
2922 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2923 try {
2924 mPolicyManager.onTetheringChanged(iface, false);
2925 } catch (RemoteException e) {
2926 }
2927 }
2928 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002929 } else {
2930 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2931 }
2932 }
2933
2934 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002935 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002936 public int getLastTetherError(String iface) {
2937 enforceTetherAccessPermission();
2938
2939 if (isTetheringSupported()) {
2940 return mTethering.getLastTetherError(iface);
2941 } else {
2942 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2943 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002944 }
2945
2946 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002947 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002948 public String[] getTetherableUsbRegexs() {
2949 enforceTetherAccessPermission();
2950 if (isTetheringSupported()) {
2951 return mTethering.getTetherableUsbRegexs();
2952 } else {
2953 return new String[0];
2954 }
2955 }
2956
Lorenzo Colitti18660282016-07-04 12:55:44 +09002957 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002958 public String[] getTetherableWifiRegexs() {
2959 enforceTetherAccessPermission();
2960 if (isTetheringSupported()) {
2961 return mTethering.getTetherableWifiRegexs();
2962 } else {
2963 return new String[0];
2964 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002965 }
2966
Lorenzo Colitti18660282016-07-04 12:55:44 +09002967 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002968 public String[] getTetherableBluetoothRegexs() {
2969 enforceTetherAccessPermission();
2970 if (isTetheringSupported()) {
2971 return mTethering.getTetherableBluetoothRegexs();
2972 } else {
2973 return new String[0];
2974 }
2975 }
2976
Lorenzo Colitti18660282016-07-04 12:55:44 +09002977 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002978 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002979 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002980 if (isTetheringSupported()) {
2981 return mTethering.setUsbTethering(enable);
2982 } else {
2983 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2984 }
2985 }
2986
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002987 // TODO - move iface listing, queries, etc to new module
2988 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002989 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002990 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002991 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002992 return mTethering.getTetherableIfaces();
2993 }
2994
Lorenzo Colitti18660282016-07-04 12:55:44 +09002995 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002996 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002997 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002998 return mTethering.getTetheredIfaces();
2999 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003000
Lorenzo Colitti18660282016-07-04 12:55:44 +09003001 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003002 public String[] getTetheringErroredIfaces() {
3003 enforceTetherAccessPermission();
3004 return mTethering.getErroredIfaces();
3005 }
3006
Lorenzo Colitti18660282016-07-04 12:55:44 +09003007 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003008 public String[] getTetheredDhcpRanges() {
3009 enforceConnectivityInternalPermission();
3010 return mTethering.getTetheredDhcpRanges();
3011 }
3012
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003013 // if ro.tether.denied = true we default to no tethering
3014 // gservices could set the secure setting to 1 though to enable it on a build where it
3015 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003016 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003017 public boolean isTetheringSupported() {
3018 enforceTetherAccessPermission();
3019 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003020 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003021 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3022 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003023 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
3024 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003025 mTethering.getTetherableWifiRegexs().length != 0 ||
3026 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3027 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003028 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003029
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003030 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003031 public void startTethering(int type, ResultReceiver receiver,
3032 boolean showProvisioningUi) {
3033 ConnectivityManager.enforceTetherChangePermission(mContext);
3034 if (!isTetheringSupported()) {
3035 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3036 return;
3037 }
3038 mTethering.startTethering(type, receiver, showProvisioningUi);
3039 }
3040
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003041 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003042 public void stopTethering(int type) {
3043 ConnectivityManager.enforceTetherChangePermission(mContext);
3044 mTethering.stopTethering(type);
3045 }
3046
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003047 // Called when we lose the default network and have no replacement yet.
3048 // This will automatically be cleared after X seconds or a new default network
3049 // becomes CONNECTED, whichever happens first. The timer is started by the
3050 // first caller and not restarted by subsequent callers.
3051 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003052 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003053 synchronized (this) {
3054 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003055 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003056 mNetTransitionWakeLock.acquire();
3057 mNetTransitionWakeLockCausedBy = forWhom;
3058 }
3059 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003060 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003061 mNetTransitionWakeLockTimeout);
3062 return;
3063 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003064
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003065 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003066 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003067 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003068 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003069 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003070 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003071 }
3072
Lorenzo Colitti18660282016-07-04 12:55:44 +09003073 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003074 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003075 enforceAccessPermission();
3076 enforceInternetPermission();
3077
Paul Jensenbfd17b72015-04-07 12:43:13 -04003078 NetworkAgentInfo nai;
3079 if (network == null) {
3080 nai = getDefaultNetwork();
3081 } else {
3082 nai = getNetworkAgentInfoForNetwork(network);
3083 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003084 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3085 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3086 return;
3087 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003088 // Revalidate if the app report does not match our current validated state.
3089 if (hasConnectivity == nai.lastValidated) return;
3090 final int uid = Binder.getCallingUid();
3091 if (DBG) {
3092 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3093 ") by " + uid);
3094 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003095 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003096 // Validating a network that has not yet connected could result in a call to
3097 // rematchNetworkAndRequests() which is not meant to work on such networks.
3098 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003099
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003100 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003101
3102 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3103 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003104 }
3105
Paul Jensencee9b512015-05-06 07:32:40 -04003106 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003107 // this information is already available as a world read/writable jvm property
3108 // so this API change wouldn't have a benifit. It also breaks the passing
3109 // of proxy info to all the JVMs.
3110 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003111 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003112 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003113 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3114 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003115 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003116 }
3117
Lorenzo Colitti18660282016-07-04 12:55:44 +09003118 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003119 public ProxyInfo getProxyForNetwork(Network network) {
3120 if (network == null) return getDefaultProxy();
3121 final ProxyInfo globalProxy = getGlobalProxy();
3122 if (globalProxy != null) return globalProxy;
3123 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3124 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3125 // caller may not have.
3126 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3127 if (nai == null) return null;
3128 synchronized (nai) {
3129 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3130 if (proxyInfo == null) return null;
3131 return new ProxyInfo(proxyInfo);
3132 }
3133 }
3134
Paul Jensene0bef712014-12-10 15:12:18 -05003135 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3136 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3137 // proxy is null then there is no proxy in place).
3138 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3139 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3140 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3141 proxy = null;
3142 }
3143 return proxy;
3144 }
3145
3146 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3147 // better for determining if a new proxy broadcast is necessary:
3148 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3149 // avoid unnecessary broadcasts.
3150 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3151 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3152 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3153 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3154 // all set.
3155 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3156 a = canonicalizeProxyInfo(a);
3157 b = canonicalizeProxyInfo(b);
3158 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3159 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3160 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3161 }
3162
Jason Monk207900c2014-04-25 15:00:09 -04003163 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003164 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003165
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003166 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003167 if (proxyProperties == mGlobalProxy) return;
3168 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3169 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3170
3171 String host = "";
3172 int port = 0;
3173 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003174 String pacFileUrl = "";
3175 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003176 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003177 if (!proxyProperties.isValid()) {
3178 if (DBG)
3179 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3180 return;
3181 }
Jason Monk207900c2014-04-25 15:00:09 -04003182 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003183 host = mGlobalProxy.getHost();
3184 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003185 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003186 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003187 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003188 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003189 } else {
3190 mGlobalProxy = null;
3191 }
3192 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003193 final long token = Binder.clearCallingIdentity();
3194 try {
3195 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3196 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3197 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3198 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003199 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003200 } finally {
3201 Binder.restoreCallingIdentity(token);
3202 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003203
Jason Monkcf0f97a2014-10-02 15:39:38 -04003204 if (mGlobalProxy == null) {
3205 proxyProperties = mDefaultProxy;
3206 }
3207 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003208 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003209 }
3210
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003211 private void loadGlobalProxy() {
3212 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003213 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3214 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3215 String exclList = Settings.Global.getString(res,
3216 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003217 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3218 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003219 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003220 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003221 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003222 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003223 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003224 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003225 if (!proxyProperties.isValid()) {
3226 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3227 return;
3228 }
3229
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003230 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003231 mGlobalProxy = proxyProperties;
3232 }
3233 }
3234 }
3235
Jason Monk207900c2014-04-25 15:00:09 -04003236 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003237 // this information is already available as a world read/writable jvm property
3238 // so this API change wouldn't have a benifit. It also breaks the passing
3239 // of proxy info to all the JVMs.
3240 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003241 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003242 return mGlobalProxy;
3243 }
3244 }
3245
Jason Monk207900c2014-04-25 15:00:09 -04003246 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003247 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003248 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003249 proxy = null;
3250 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003251 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003252 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003253 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003254 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003255 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3256 return;
3257 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003258
3259 // This call could be coming from the PacManager, containing the port of the local
3260 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3261 // global (to get the correct local port), and send a broadcast.
3262 // TODO: Switch PacManager to have its own message to send back rather than
3263 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003264 if ((mGlobalProxy != null) && (proxy != null)
3265 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003266 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3267 mGlobalProxy = proxy;
3268 sendProxyBroadcast(mGlobalProxy);
3269 return;
3270 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003271 mDefaultProxy = proxy;
3272
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003273 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003274 if (!mDefaultProxyDisabled) {
3275 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003276 }
3277 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003278 }
3279
Paul Jensene0bef712014-12-10 15:12:18 -05003280 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3281 // This method gets called when any network changes proxy, but the broadcast only ever contains
3282 // the default proxy (even if it hasn't changed).
3283 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3284 // world where an app might be bound to a non-default network.
3285 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3286 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3287 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3288
3289 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3290 sendProxyBroadcast(getDefaultProxy());
3291 }
3292 }
3293
Robert Greenwalt434203a2010-10-11 16:00:27 -07003294 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003295 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3296 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003297 if (!TextUtils.isEmpty(proxy)) {
3298 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003299 if (data.length == 0) {
3300 return;
3301 }
3302
Robert Greenwalt434203a2010-10-11 16:00:27 -07003303 String proxyHost = data[0];
3304 int proxyPort = 8080;
3305 if (data.length > 1) {
3306 try {
3307 proxyPort = Integer.parseInt(data[1]);
3308 } catch (NumberFormatException e) {
3309 return;
3310 }
3311 }
Jason Monk207900c2014-04-25 15:00:09 -04003312 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003313 setGlobalProxy(p);
3314 }
3315 }
3316
Jason Monk207900c2014-04-25 15:00:09 -04003317 private void sendProxyBroadcast(ProxyInfo proxy) {
3318 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003319 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003320 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003321 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003322 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3323 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003324 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003325 final long ident = Binder.clearCallingIdentity();
3326 try {
3327 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3328 } finally {
3329 Binder.restoreCallingIdentity(ident);
3330 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003331 }
3332
3333 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003334 final private HashMap<Uri, Integer> mUriEventMap;
3335 final private Context mContext;
3336 final private Handler mHandler;
3337
3338 SettingsObserver(Context context, Handler handler) {
3339 super(null);
3340 mUriEventMap = new HashMap<Uri, Integer>();
3341 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003342 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003343 }
3344
Erik Klineda4bfa82015-04-30 12:58:40 +09003345 void observe(Uri uri, int what) {
3346 mUriEventMap.put(uri, what);
3347 final ContentResolver resolver = mContext.getContentResolver();
3348 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003349 }
3350
3351 @Override
3352 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003353 Slog.wtf(TAG, "Should never be reached.");
3354 }
3355
3356 @Override
3357 public void onChange(boolean selfChange, Uri uri) {
3358 final Integer what = mUriEventMap.get(uri);
3359 if (what != null) {
3360 mHandler.obtainMessage(what.intValue()).sendToTarget();
3361 } else {
3362 loge("No matching event to send for URI=" + uri);
3363 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003364 }
3365 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003366
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003367 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003368 Slog.d(TAG, s);
3369 }
3370
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003371 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003372 Slog.e(TAG, s);
3373 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003374
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003375 private static <T> T checkNotNull(T value, String message) {
3376 if (value == null) {
3377 throw new NullPointerException(message);
3378 }
3379 return value;
3380 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003381
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003382 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003383 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003384 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3385 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3386 *
3387 * @param oldPackage Package name of the application which currently controls VPN, which will
3388 * be replaced. If there is no such application, this should should either be
3389 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3390 * @param newPackage Package name of the application which should gain control of VPN, or
3391 * {@code null} to disable.
3392 * @param userId User for whom to prepare the new VPN.
3393 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003394 * @hide
3395 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003396 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003397 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3398 int userId) {
3399 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003400 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003401
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003402 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003403 Vpn vpn = mVpns.get(userId);
3404 if (vpn != null) {
3405 return vpn.prepare(oldPackage, newPackage);
3406 } else {
3407 return false;
3408 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003409 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003410 }
3411
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003412 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003413 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3414 * This method is used by system-privileged apps.
3415 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3416 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3417 *
3418 * @param packageName The package for which authorization state should change.
3419 * @param userId User for whom {@code packageName} is installed.
3420 * @param authorized {@code true} if this app should be able to start a VPN connection without
3421 * explicit user approval, {@code false} if not.
3422 *
Jeff Davidson05542602014-08-11 14:07:27 -07003423 * @hide
3424 */
3425 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003426 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3427 enforceCrossUserPermission(userId);
3428
Jeff Davidson05542602014-08-11 14:07:27 -07003429 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003430 Vpn vpn = mVpns.get(userId);
3431 if (vpn != null) {
3432 vpn.setPackageAuthorization(packageName, authorized);
3433 }
Jeff Davidson05542602014-08-11 14:07:27 -07003434 }
3435 }
3436
3437 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003438 * Configure a TUN interface and return its file descriptor. Parameters
3439 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003440 * and not available in ConnectivityManager. Permissions are checked in
3441 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003442 * @hide
3443 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003444 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003445 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003446 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003447 int user = UserHandle.getUserId(Binder.getCallingUid());
3448 synchronized(mVpns) {
3449 return mVpns.get(user).establish(config);
3450 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003451 }
3452
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003453 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003454 * Start legacy VPN, controlling native daemons as needed. Creates a
3455 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003456 */
3457 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003458 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003459 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003460 final LinkProperties egress = getActiveLinkProperties();
3461 if (egress == null) {
3462 throw new IllegalStateException("Missing active network connection");
3463 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003464 int user = UserHandle.getUserId(Binder.getCallingUid());
3465 synchronized(mVpns) {
3466 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3467 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003468 }
3469
3470 /**
3471 * Return the information of the ongoing legacy VPN. This method is used
3472 * by VpnSettings and not available in ConnectivityManager. Permissions
3473 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003474 */
3475 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003476 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3477 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003478
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003479 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003480 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003481 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003482 }
3483
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003484 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003485 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3486 * and not available in ConnectivityManager.
3487 */
3488 @Override
3489 public VpnInfo[] getAllVpnInfo() {
3490 enforceConnectivityInternalPermission();
3491 if (mLockdownEnabled) {
3492 return new VpnInfo[0];
3493 }
3494
3495 synchronized(mVpns) {
3496 List<VpnInfo> infoList = new ArrayList<>();
3497 for (int i = 0; i < mVpns.size(); i++) {
3498 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3499 if (info != null) {
3500 infoList.add(info);
3501 }
3502 }
3503 return infoList.toArray(new VpnInfo[infoList.size()]);
3504 }
3505 }
3506
3507 /**
3508 * @return VPN information for accounting, or null if we can't retrieve all required
3509 * information, e.g primary underlying iface.
3510 */
3511 @Nullable
3512 private VpnInfo createVpnInfo(Vpn vpn) {
3513 VpnInfo info = vpn.getVpnInfo();
3514 if (info == null) {
3515 return null;
3516 }
3517 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3518 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3519 // the underlyingNetworks list.
3520 if (underlyingNetworks == null) {
3521 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3522 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3523 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3524 }
3525 } else if (underlyingNetworks.length > 0) {
3526 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3527 if (linkProperties != null) {
3528 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3529 }
3530 }
3531 return info.primaryUnderlyingIface == null ? null : info;
3532 }
3533
3534 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003535 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3536 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003537 * Permissions are checked in Vpn class.
3538 * @hide
3539 */
3540 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003541 public VpnConfig getVpnConfig(int userId) {
3542 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003543 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003544 Vpn vpn = mVpns.get(userId);
3545 if (vpn != null) {
3546 return vpn.getVpnConfig();
3547 } else {
3548 return null;
3549 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003550 }
3551 }
3552
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003553 @Override
3554 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003555 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3556 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3557 return false;
3558 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003559
3560 // Tear down existing lockdown if profile was removed
3561 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3562 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003563 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3564 final VpnProfile profile = VpnProfile.decode(
3565 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003566 if (profile == null) {
3567 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3568 setLockdownTracker(null);
3569 return true;
3570 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003571 int user = UserHandle.getUserId(Binder.getCallingUid());
3572 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003573 Vpn vpn = mVpns.get(user);
3574 if (vpn == null) {
3575 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3576 return false;
3577 }
3578 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003579 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003580 } else {
3581 setLockdownTracker(null);
3582 }
3583
3584 return true;
3585 }
3586
3587 /**
3588 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3589 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3590 */
3591 private void setLockdownTracker(LockdownVpnTracker tracker) {
3592 // Shutdown any existing tracker
3593 final LockdownVpnTracker existing = mLockdownTracker;
3594 mLockdownTracker = null;
3595 if (existing != null) {
3596 existing.shutdown();
3597 }
3598
3599 try {
3600 if (tracker != null) {
3601 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003602 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003603 mLockdownTracker = tracker;
3604 mLockdownTracker.init();
3605 } else {
3606 mNetd.setFirewallEnabled(false);
3607 }
3608 } catch (RemoteException e) {
3609 // ignored; NMS lives inside system_server
3610 }
3611 }
3612
3613 private void throwIfLockdownEnabled() {
3614 if (mLockdownEnabled) {
3615 throw new IllegalStateException("Unavailable in lockdown mode");
3616 }
3617 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003618
Robin Lee244ce8e2016-01-05 18:03:46 +00003619 /**
Robin Lee17e61832016-05-09 13:46:28 +01003620 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3621 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003622 *
Robin Lee17e61832016-05-09 13:46:28 +01003623 * @return {@code true} if the service was started, the service was already connected, or there
3624 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003625 */
Robin Lee17e61832016-05-09 13:46:28 +01003626 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003627 synchronized (mVpns) {
3628 Vpn vpn = mVpns.get(userId);
3629 if (vpn == null) {
3630 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3631 // exists already.
3632 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3633 return false;
3634 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003635
Robin Lee812800c2016-05-13 15:38:08 +01003636 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003637 }
3638 }
3639
3640 @Override
Robin Leedc679712016-05-03 13:23:03 +01003641 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003642 enforceConnectivityInternalPermission();
3643 enforceCrossUserPermission(userId);
3644
3645 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3646 if (LockdownVpnTracker.isEnabled()) {
3647 return false;
3648 }
3649
Robin Lee244ce8e2016-01-05 18:03:46 +00003650 synchronized (mVpns) {
3651 Vpn vpn = mVpns.get(userId);
3652 if (vpn == null) {
3653 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3654 return false;
3655 }
Robin Lee17e61832016-05-09 13:46:28 +01003656 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003657 return false;
3658 }
Robin Lee17e61832016-05-09 13:46:28 +01003659 if (!startAlwaysOnVpn(userId)) {
3660 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003661 return false;
3662 }
Robin Lee17e61832016-05-09 13:46:28 +01003663
Robin Lee812800c2016-05-13 15:38:08 +01003664 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003665 }
3666 return true;
3667 }
3668
3669 @Override
3670 public String getAlwaysOnVpnPackage(int userId) {
3671 enforceConnectivityInternalPermission();
3672 enforceCrossUserPermission(userId);
3673
3674 synchronized (mVpns) {
3675 Vpn vpn = mVpns.get(userId);
3676 if (vpn == null) {
3677 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3678 return null;
3679 }
3680 return vpn.getAlwaysOnPackage();
3681 }
3682 }
3683
Wink Savilleab9321d2013-06-29 21:10:57 -07003684 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003685 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003686 // TODO: Remove? Any reason to trigger a provisioning check?
3687 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003688 }
3689
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003690 /** Location to an updatable file listing carrier provisioning urls.
3691 * An example:
3692 *
3693 * <?xml version="1.0" encoding="utf-8"?>
3694 * <provisioningUrls>
3695 * <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 -07003696 * </provisioningUrls>
3697 */
3698 private static final String PROVISIONING_URL_PATH =
3699 "/data/misc/radio/provisioning_urls.xml";
3700 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003701
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003702 /** XML tag for root element. */
3703 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3704 /** XML tag for individual url */
3705 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003706 /** XML attribute for mcc */
3707 private static final String ATTR_MCC = "mcc";
3708 /** XML attribute for mnc */
3709 private static final String ATTR_MNC = "mnc";
3710
Paul Jensen434dde82015-06-11 09:43:30 -04003711 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003712 FileReader fileReader = null;
3713 XmlPullParser parser = null;
3714 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003715
3716 try {
3717 fileReader = new FileReader(mProvisioningUrlFile);
3718 parser = Xml.newPullParser();
3719 parser.setInput(fileReader);
3720 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3721
3722 while (true) {
3723 XmlUtils.nextElement(parser);
3724
3725 String element = parser.getName();
3726 if (element == null) break;
3727
Paul Jensen434dde82015-06-11 09:43:30 -04003728 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003729 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3730 try {
3731 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3732 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3733 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3734 parser.next();
3735 if (parser.getEventType() == XmlPullParser.TEXT) {
3736 return parser.getText();
3737 }
3738 }
3739 }
3740 } catch (NumberFormatException e) {
3741 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3742 }
3743 }
3744 }
3745 return null;
3746 } catch (FileNotFoundException e) {
3747 loge("Carrier Provisioning Urls file not found");
3748 } catch (XmlPullParserException e) {
3749 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3750 } catch (IOException e) {
3751 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3752 } finally {
3753 if (fileReader != null) {
3754 try {
3755 fileReader.close();
3756 } catch (IOException e) {}
3757 }
3758 }
3759 return null;
3760 }
3761
Wink Saville42d4f082013-07-20 20:31:59 -07003762 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003763 public String getMobileProvisioningUrl() {
3764 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003765 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003766 if (TextUtils.isEmpty(url)) {
3767 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003768 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003769 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003770 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003771 }
Wink Saville8cf35602013-07-10 23:00:07 -07003772 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003773 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003774 String phoneNumber = mTelephonyManager.getLine1Number();
3775 if (TextUtils.isEmpty(phoneNumber)) {
3776 phoneNumber = "0000000000";
3777 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003778 url = String.format(url,
3779 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3780 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003781 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003782 }
3783
Wink Savilleab9321d2013-06-29 21:10:57 -07003784 return url;
3785 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003786
Wink Saville948282b2013-08-29 08:55:16 -07003787 @Override
3788 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003789 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003790 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003791 final long ident = Binder.clearCallingIdentity();
3792 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003793 // Concatenate the range of types onto the range of NetIDs.
3794 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3795 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003796 } finally {
3797 Binder.restoreCallingIdentity(ident);
3798 }
Wink Saville948282b2013-08-29 08:55:16 -07003799 }
Wink Saville7788c612013-08-29 14:57:08 -07003800
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003801 @Override
3802 public void setAirplaneMode(boolean enable) {
3803 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003804 final long ident = Binder.clearCallingIdentity();
3805 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003806 final ContentResolver cr = mContext.getContentResolver();
3807 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3808 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3809 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003810 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003811 } finally {
3812 Binder.restoreCallingIdentity(ident);
3813 }
3814 }
3815
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003816 private void onUserStart(int userId) {
3817 synchronized(mVpns) {
3818 Vpn userVpn = mVpns.get(userId);
3819 if (userVpn != null) {
3820 loge("Starting user already has a VPN");
3821 return;
3822 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003823 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003824 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003825
3826 final ContentResolver cr = mContext.getContentResolver();
3827 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3828 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3829 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3830 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3831 if (alwaysOnPackage != null) {
3832 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3833 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003834 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003835 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3836 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003837 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003838 }
3839
3840 private void onUserStop(int userId) {
3841 synchronized(mVpns) {
3842 Vpn userVpn = mVpns.get(userId);
3843 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003844 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003845 return;
3846 }
Robin Lee17e61832016-05-09 13:46:28 +01003847 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003848 mVpns.delete(userId);
3849 }
3850 }
3851
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003852 private void onUserAdded(int userId) {
3853 synchronized(mVpns) {
3854 final int vpnsSize = mVpns.size();
3855 for (int i = 0; i < vpnsSize; i++) {
3856 Vpn vpn = mVpns.valueAt(i);
3857 vpn.onUserAdded(userId);
3858 }
3859 }
3860 }
3861
3862 private void onUserRemoved(int userId) {
3863 synchronized(mVpns) {
3864 final int vpnsSize = mVpns.size();
3865 for (int i = 0; i < vpnsSize; i++) {
3866 Vpn vpn = mVpns.valueAt(i);
3867 vpn.onUserRemoved(userId);
3868 }
3869 }
3870 }
3871
Robin Lee89e7a692016-02-29 14:38:17 +00003872 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003873 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3874 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3875 updateLockdownVpn();
3876 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003877 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003878 }
3879 }
3880
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003881 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3882 @Override
3883 public void onReceive(Context context, Intent intent) {
3884 final String action = intent.getAction();
3885 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3886 if (userId == UserHandle.USER_NULL) return;
3887
Robin Lee323f29d2016-05-04 16:38:06 +01003888 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003889 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003890 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003891 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003892 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3893 onUserAdded(userId);
3894 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3895 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003896 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3897 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003898 }
3899 }
3900 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003901
Robert Greenwalta67be032014-05-16 15:49:14 -07003902 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3903 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003904 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3905 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003906
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003907 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3908 // Map from UID to number of NetworkRequests that UID has filed.
3909 @GuardedBy("mUidToNetworkRequestCount")
3910 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3911
Robert Greenwalta67be032014-05-16 15:49:14 -07003912 private static class NetworkFactoryInfo {
3913 public final String name;
3914 public final Messenger messenger;
3915 public final AsyncChannel asyncChannel;
3916
3917 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3918 this.name = name;
3919 this.messenger = messenger;
3920 this.asyncChannel = asyncChannel;
3921 }
3922 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003923
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003924 private void ensureNetworkRequestHasType(NetworkRequest request) {
3925 if (request.type == NetworkRequest.Type.NONE) {
3926 throw new IllegalArgumentException(
3927 "All NetworkRequests in ConnectivityService must have a type");
3928 }
3929 }
3930
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003931 /**
3932 * Tracks info about the requester.
3933 * Also used to notice when the calling process dies so we can self-expire
3934 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003935 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003936 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003937 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003938 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003939 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003940 final int mPid;
3941 final int mUid;
3942 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003943
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003944 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003945 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003946 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003947 mPendingIntent = pi;
3948 messenger = null;
3949 mBinder = null;
3950 mPid = getCallingPid();
3951 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003952 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003953 }
3954
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003955 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003956 super();
3957 messenger = m;
3958 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003959 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003960 mBinder = binder;
3961 mPid = getCallingPid();
3962 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003963 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003964 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003965
3966 try {
3967 mBinder.linkToDeath(this, 0);
3968 } catch (RemoteException e) {
3969 binderDied();
3970 }
3971 }
3972
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003973 private void enforceRequestCountLimit() {
3974 synchronized (mUidToNetworkRequestCount) {
3975 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3976 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3977 throw new IllegalArgumentException("Too many NetworkRequests filed");
3978 }
3979 mUidToNetworkRequestCount.put(mUid, networkRequests);
3980 }
3981 }
3982
Robert Greenwalt9258c642014-03-26 16:47:06 -07003983 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003984 if (mBinder != null) {
3985 mBinder.unlinkToDeath(this, 0);
3986 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003987 }
3988
3989 public void binderDied() {
3990 log("ConnectivityService NetworkRequestInfo binderDied(" +
3991 request + ", " + mBinder + ")");
3992 releaseNetworkRequest(request);
3993 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003994
3995 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003996 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003997 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003998 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003999 }
4000
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004001 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4002 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4003 if (badCapability != null) {
4004 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004005 }
4006 }
4007
Erik Kline9d598e12015-07-13 16:37:51 +09004008 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004009 final SortedSet<Integer> thresholds = new TreeSet();
4010 synchronized (nai) {
4011 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4012 if (nri.request.networkCapabilities.hasSignalStrength() &&
4013 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4014 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4015 }
4016 }
4017 }
Erik Kline9d598e12015-07-13 16:37:51 +09004018 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004019 }
4020
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004021 private void updateSignalStrengthThresholds(
4022 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4023 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004024 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004025 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4026
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004027 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004028 String detail;
4029 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4030 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4031 } else {
4032 detail = reason;
4033 }
4034 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4035 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4036 }
4037
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004038 nai.asyncChannel.sendMessage(
4039 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004040 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004041 }
4042
Robert Greenwalt9258c642014-03-26 16:47:06 -07004043 @Override
4044 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004045 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004046 final NetworkRequest.Type type = (networkCapabilities == null)
4047 ? NetworkRequest.Type.TRACK_DEFAULT
4048 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004049 // If the requested networkCapabilities is null, take them instead from
4050 // the default network request. This allows callers to keep track of
4051 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004052 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004053 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4054 enforceAccessPermission();
4055 } else {
4056 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4057 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004058 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4059 // of the app when the request is filed, but we never change the request if the app
4060 // changes network state. http://b/29964605
4061 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004062 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004063 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004064
Robert Greenwalt6078b502014-06-11 16:05:07 -07004065 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004066 throw new IllegalArgumentException("Bad timeout specified");
4067 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004068
Etan Cohenddb9ef02015-11-18 10:56:15 -08004069 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4070 .equals(networkCapabilities.getNetworkSpecifier())) {
4071 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4072 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4073 }
4074
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004075 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004076 nextNetworkRequestId(), type);
4077 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004078 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079
4080 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004081 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004082 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004083 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004084 }
4085 return networkRequest;
4086 }
4087
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004088 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004089 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004090 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004091 } else {
4092 enforceChangePermission();
4093 }
4094 }
4095
fenglub15e72b2015-03-20 11:29:56 -07004096 @Override
fengludb571472015-04-21 17:12:05 -07004097 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004098 enforceAccessPermission();
4099 NetworkAgentInfo nai = null;
4100 if (network == null) {
4101 return false;
4102 }
4103 synchronized (mNetworkForNetId) {
4104 nai = mNetworkForNetId.get(network.netId);
4105 }
4106 if (nai != null) {
4107 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4108 return true;
4109 }
4110 return false;
4111 }
4112
Felipe Lemeee27cab2016-06-20 16:36:29 -07004113 private boolean isSystem(int uid) {
4114 return uid < Process.FIRST_APPLICATION_UID;
4115 }
fenglub15e72b2015-03-20 11:29:56 -07004116
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004117 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004118 final int uid = Binder.getCallingUid();
4119 if (isSystem(uid)) {
4120 return;
4121 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004122 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004123 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004124 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004125 synchronized(mRulesLock) {
4126 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4127 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004128 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4129 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004130 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004131 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004132 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004133 }
4134 }
4135 }
4136
Robert Greenwalt9258c642014-03-26 16:47:06 -07004137 @Override
4138 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4139 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004140 checkNotNull(operation, "PendingIntent cannot be null.");
4141 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4142 enforceNetworkRequestPermissions(networkCapabilities);
4143 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004144 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004145
4146 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004147 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4148 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004149 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004150 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4151 nri));
4152 return networkRequest;
4153 }
4154
Jeremy Joslin79294842014-12-03 17:15:28 -08004155 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4156 mHandler.sendMessageDelayed(
4157 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4158 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4159 }
4160
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004161 @Override
4162 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004163 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004164 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4165 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004166 }
4167
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004168 // In order to implement the compatibility measure for pre-M apps that call
4169 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4170 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4171 // This ensures it has permission to do so.
4172 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4173 if (nc == null) {
4174 return false;
4175 }
4176 int[] transportTypes = nc.getTransportTypes();
4177 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4178 return false;
4179 }
4180 try {
4181 mContext.enforceCallingOrSelfPermission(
4182 android.Manifest.permission.ACCESS_WIFI_STATE,
4183 "ConnectivityService");
4184 } catch (SecurityException e) {
4185 return false;
4186 }
4187 return true;
4188 }
4189
Robert Greenwalt9258c642014-03-26 16:47:06 -07004190 @Override
4191 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4192 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004193 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4194 enforceAccessPermission();
4195 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004196
Erik Kline7523eb32015-07-09 18:24:03 +09004197 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004198 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4199 NetworkRequest.Type.LISTEN);
4200 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004201 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004202
4203 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4204 return networkRequest;
4205 }
4206
4207 @Override
4208 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4209 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004210 checkNotNull(operation, "PendingIntent cannot be null.");
4211 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4212 enforceAccessPermission();
4213 }
4214
Erik Kline7523eb32015-07-09 18:24:03 +09004215 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004216 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4217 NetworkRequest.Type.LISTEN);
4218 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004219 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004220
4221 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004222 }
4223
4224 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004225 public void requestLinkProperties(NetworkRequest networkRequest) {
4226 ensureNetworkRequestHasType(networkRequest);
4227 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4228 mHandler.sendMessage(mHandler.obtainMessage(
4229 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4230 }
4231
4232 @Override
4233 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4234 ensureNetworkRequestHasType(networkRequest);
4235 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4236 mHandler.sendMessage(mHandler.obtainMessage(
4237 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4238 }
4239
4240 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004241 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004242 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004243 mHandler.sendMessage(mHandler.obtainMessage(
4244 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004245 }
4246
4247 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004248 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004249 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004250 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4251 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004252 }
4253
Robert Greenwalta67be032014-05-16 15:49:14 -07004254 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004255 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004256 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4257 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4258 }
4259
4260 @Override
4261 public void unregisterNetworkFactory(Messenger messenger) {
4262 enforceConnectivityInternalPermission();
4263 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4264 }
4265
4266 private void handleUnregisterNetworkFactory(Messenger messenger) {
4267 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4268 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004269 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004270 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004271 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004272 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004273 }
4274
Robert Greenwalt7b816022014-04-18 15:25:25 -07004275 /**
4276 * NetworkAgentInfo supporting a request by requestId.
4277 * These have already been vetted (their Capabilities satisfy the request)
4278 * and the are the highest scored network available.
4279 * the are keyed off the Requests requestId.
4280 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004281 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004282 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4283 new SparseArray<NetworkAgentInfo>();
4284
Paul Jensen31a94f42015-02-13 14:18:39 -05004285 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4286 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004287 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4288 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004289 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4290 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4291 // there may not be a strict 1:1 correlation between the two.
4292 @GuardedBy("mNetworkForNetId")
4293 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004294
Robert Greenwalt7b816022014-04-18 15:25:25 -07004295 // NetworkAgentInfo keyed off its connecting messenger
4296 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004297 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004298 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4299 new HashMap<Messenger, NetworkAgentInfo>();
4300
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004301 @GuardedBy("mBlockedAppUids")
4302 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4303
Paul Jensen2c311d62014-11-17 12:34:51 -05004304 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004305 private final NetworkRequest mDefaultRequest;
4306
Erik Klineda4bfa82015-04-30 12:58:40 +09004307 // Request used to optionally keep mobile data active even when higher
4308 // priority networks like Wi-Fi are active.
4309 private final NetworkRequest mDefaultMobileDataRequest;
4310
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004311 private NetworkAgentInfo getDefaultNetwork() {
4312 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4313 }
4314
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004315 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004316 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004317 }
4318
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004319 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4320 return nri.request.requestId == mDefaultRequest.requestId;
4321 }
4322
Paul Jensen31a94f42015-02-13 14:18:39 -05004323 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004324 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004325 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004326 enforceConnectivityInternalPermission();
4327
Paul Jensen2c311d62014-11-17 12:34:51 -05004328 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4329 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004330 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004331 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4332 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004333 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004334 synchronized (this) {
4335 nai.networkMonitor.systemReady = mSystemReady;
4336 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004337 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4338 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004339 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004340 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004341 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004342 }
4343
4344 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4345 if (VDBG) log("Got NetworkAgent Messenger");
4346 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004347 synchronized (mNetworkForNetId) {
4348 mNetworkForNetId.put(na.network.netId, na);
4349 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004350 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4351 NetworkInfo networkInfo = na.networkInfo;
4352 na.networkInfo = null;
4353 updateNetworkInfo(na, networkInfo);
4354 }
4355
4356 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4357 LinkProperties newLp = networkAgent.linkProperties;
4358 int netId = networkAgent.network.netId;
4359
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004360 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4361 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004362 if (networkAgent.clatd != null) {
4363 networkAgent.clatd.fixupLinkProperties(oldLp);
4364 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004365
Paul Jensen992f2522014-04-28 10:33:11 -04004366 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004367 updateMtu(newLp, oldLp);
4368 // TODO - figure out what to do for clat
4369// for (LinkProperties lp : newLp.getStackedLinks()) {
4370// updateMtu(lp, null);
4371// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004372 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004373
Erik Kline94887872016-04-05 13:30:49 +09004374 updateRoutes(newLp, oldLp, netId);
4375 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004376
Paul Jensen3b759822014-05-13 11:44:01 -04004377 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004378 if (isDefaultNetwork(networkAgent)) {
4379 handleApplyDefaultProxy(newLp.getHttpProxy());
4380 } else {
4381 updateProxy(newLp, oldLp, networkAgent);
4382 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004383 // TODO - move this check to cover the whole function
4384 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004385 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004386 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4387 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004388
4389 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004390 }
4391
Lorenzo Colitti95439462014-10-09 13:44:48 +09004392 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4393 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4394 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004395
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004396 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004397 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4398 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004399 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004400 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004401 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004402 }
Paul Jensen992f2522014-04-28 10:33:11 -04004403
4404 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4405 CompareResult<String> interfaceDiff = new CompareResult<String>();
4406 if (oldLp != null) {
4407 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4408 } else if (newLp != null) {
4409 interfaceDiff.added = newLp.getAllInterfaceNames();
4410 }
4411 for (String iface : interfaceDiff.added) {
4412 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004413 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004414 mNetd.addInterfaceToNetwork(iface, netId);
4415 } catch (Exception e) {
4416 loge("Exception adding interface: " + e);
4417 }
4418 }
4419 for (String iface : interfaceDiff.removed) {
4420 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004421 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004422 mNetd.removeInterfaceFromNetwork(iface, netId);
4423 } catch (Exception e) {
4424 loge("Exception removing interface: " + e);
4425 }
4426 }
4427 }
4428
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004429 /**
4430 * Have netd update routes from oldLp to newLp.
4431 * @return true if routes changed between oldLp and newLp
4432 */
4433 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004434 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4435 if (oldLp != null) {
4436 routeDiff = oldLp.compareAllRoutes(newLp);
4437 } else if (newLp != null) {
4438 routeDiff.added = newLp.getAllRoutes();
4439 }
4440
4441 // add routes before removing old in case it helps with continuous connectivity
4442
4443 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4444 for (RouteInfo route : routeDiff.added) {
4445 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004446 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004447 try {
4448 mNetd.addRoute(netId, route);
4449 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004450 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4451 loge("Exception in addRoute for non-gateway: " + e);
4452 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004453 }
4454 }
4455 for (RouteInfo route : routeDiff.added) {
4456 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004457 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004458 try {
4459 mNetd.addRoute(netId, route);
4460 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004461 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4462 loge("Exception in addRoute for gateway: " + e);
4463 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004464 }
4465 }
4466
4467 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004468 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004469 try {
4470 mNetd.removeRoute(netId, route);
4471 } catch (Exception e) {
4472 loge("Exception in removeRoute: " + e);
4473 }
4474 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004475 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004476 }
Erik Kline41368502015-06-17 13:19:54 +09004477
Erik Kline94887872016-04-05 13:30:49 +09004478 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4479 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4480 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004481 }
Erik Kline94887872016-04-05 13:30:49 +09004482
4483 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004484 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004485 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004486 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004487 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4488 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004489 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004490 }
4491 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4492 if (defaultNai != null && defaultNai.network.netId == netId) {
4493 setDefaultDnsSystemProperties(dnses);
4494 }
4495 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004496 }
4497
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004498 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4499 int last = 0;
4500 for (InetAddress dns : dnses) {
4501 ++last;
4502 String key = "net.dns" + last;
4503 String value = dns.getHostAddress();
4504 SystemProperties.set(key, value);
4505 }
4506 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4507 String key = "net.dns" + i;
4508 SystemProperties.set(key, "");
4509 }
4510 mNumDnsEntries = last;
4511 }
4512
Paul Jensen3d194ea2015-06-16 14:27:36 -04004513 /**
4514 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4515 * augmented with any stateful capabilities implied from {@code networkAgent}
4516 * (e.g., validated status and captive portal status).
4517 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004518 * @param oldScore score of the network before any of the changes that prompted us
4519 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004520 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004521 * @param networkCapabilities the new network capabilities.
4522 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004523 private void updateCapabilities(
4524 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004525 // Don't modify caller's NetworkCapabilities.
4526 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004527 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004528 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4529 } else {
4530 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4531 }
Paul Jensene0988542015-06-25 15:30:08 -04004532 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004533 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4534 } else {
4535 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4536 }
Paul Jensene0988542015-06-25 15:30:08 -04004537 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
Paul Jensen487ffe72015-07-24 15:57:11 -04004538 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4539 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4540 try {
4541 mNetd.setNetworkPermission(nai.network.netId,
4542 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4543 null : NetworkManagementService.PERMISSION_SYSTEM);
4544 } catch (RemoteException e) {
4545 loge("Exception in setNetworkPermission: " + e);
4546 }
4547 }
Paul Jensene0988542015-06-25 15:30:08 -04004548 synchronized (nai) {
4549 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004550 }
Paul Jensene0988542015-06-25 15:30:08 -04004551 rematchAllNetworksAndRequests(nai, oldScore);
4552 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004553 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004554 }
4555
Paul Jensenc8b9a742014-09-30 15:37:41 -04004556 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004557 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4558 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004559 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004560 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004561 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4562 }
4563 }
4564
Robert Greenwalt7b816022014-04-18 15:25:25 -07004565 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4566 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004567 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004568 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4569 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004570 }
4571 }
4572
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004573 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4574 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004575 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004576 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004577 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4578 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004579 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004580 sendIntent(nri.mPendingIntent, intent);
4581 }
4582 // else not handled
4583 }
4584
4585 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4586 mPendingIntentWakeLock.acquire();
4587 try {
4588 if (DBG) log("Sending " + pendingIntent);
4589 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4590 } catch (PendingIntent.CanceledException e) {
4591 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4592 mPendingIntentWakeLock.release();
4593 releasePendingNetworkRequest(pendingIntent);
4594 }
4595 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4596 }
4597
4598 @Override
4599 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4600 String resultData, Bundle resultExtras) {
4601 if (DBG) log("Finished sending " + pendingIntent);
4602 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004603 // Release with a delay so the receiving client has an opportunity to put in its
4604 // own request.
4605 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004606 }
4607
Robert Greenwalt9258c642014-03-26 16:47:06 -07004608 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004609 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004610 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004611 Bundle bundle = new Bundle();
4612 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4613 new NetworkRequest(nri.request));
4614 Message msg = Message.obtain();
4615 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4616 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4617 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4618 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004619 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004620 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004621 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004622 break;
4623 }
4624 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4625 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4626 new NetworkCapabilities(networkAgent.networkCapabilities));
4627 break;
4628 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004629 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004630 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4631 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004632 break;
4633 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004634 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004635 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004636 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004637 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004638 if (VDBG) {
4639 log("sending notification " + notifyTypeToName(notificationType) +
4640 " for " + nri.request);
4641 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004642 nri.messenger.send(msg);
4643 } catch (RemoteException e) {
4644 // may occur naturally in the race of binder death.
4645 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4646 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004647 }
4648
Paul Jensenc8b9a742014-09-30 15:37:41 -04004649 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004650 if (nai.numRequestNetworkRequests() != 0) {
4651 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4652 NetworkRequest nr = nai.requestAt(i);
4653 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004654 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004655 loge("Dead network still had at least " + nr);
4656 break;
4657 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004658 }
4659 nai.asyncChannel.disconnect();
4660 }
4661
Robert Greenwalt7b816022014-04-18 15:25:25 -07004662 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4663 if (oldNetwork == null) {
4664 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4665 return;
4666 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004667 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004668
4669 // If we get here it means that the last linger timeout for this network expired. So there
4670 // must be no other active linger timers, and we must stop lingering.
4671 oldNetwork.clearLingerState();
4672
4673 if (unneeded(oldNetwork)) {
4674 teardownUnneededNetwork(oldNetwork);
4675 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004676 }
4677
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004678 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004679 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004680 setupDataActivityTracking(newNetwork);
4681 try {
4682 mNetd.setDefaultNetId(newNetwork.network.netId);
4683 } catch (Exception e) {
4684 loge("Exception setting default network :" + e);
4685 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004686 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004687 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004688 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004689 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004690 }
4691
Paul Jensen2161a8e2014-09-11 11:00:39 -04004692 // Handles a network appearing or improving its score.
4693 //
4694 // - Evaluates all current NetworkRequests that can be
4695 // satisfied by newNetwork, and reassigns to newNetwork
4696 // any such requests for which newNetwork is the best.
4697 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004698 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004699 // needed. A network is needed if it is the best network for
4700 // one or more NetworkRequests, or if it is a VPN.
4701 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004702 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004703 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004704 //
4705 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4706 // networks that have no chance (i.e. even if validated)
4707 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004708 //
4709 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4710 // it does not remove NetworkRequests that other Networks could better satisfy.
4711 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4712 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4713 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004714 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004715 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004716 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4717 // performed to tear down unvalidated networks that have no chance (i.e. even if
4718 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004719 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004720 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004721 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004722 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004723 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004724 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004725 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004726 // Find and migrate to this Network any NetworkRequests for
4727 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004728 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004729 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004730 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004731 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004732 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4733 final boolean satisfies = newNetwork.satisfies(nri.request);
4734 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004735 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004736 log("Network " + newNetwork.name() + " was already satisfying" +
4737 " request " + nri.request.requestId + ". No change.");
4738 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004739 keep = true;
4740 continue;
4741 }
4742
4743 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004744 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004745 if (satisfies) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004746 if (nri.request.isListen()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004747 // This is not a request, it's a callback listener.
4748 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004749 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004750 continue;
4751 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004752
Robert Greenwalt7b816022014-04-18 15:25:25 -07004753 // next check if it's better than any current network we're using for
4754 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004755 if (VDBG) {
4756 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004757 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4758 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004759 }
4760 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004761 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004762 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004763 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004764 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004765 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004766 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004767 affectedNetworks.add(currentNetwork);
4768 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004769 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004770 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004771 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004772 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004773 if (!newNetwork.addRequest(nri.request)) {
4774 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4775 }
4776 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004777 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004778 // Tell NetworkFactories about the new score, so they can stop
4779 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004780 // TODO - this could get expensive if we have alot of requests for this
4781 // network. Think about if there is a way to reduce this. Push
4782 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004783 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004784 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004785 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004786 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004787 if (currentNetwork != null) {
4788 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4789 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004790 }
4791 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004792 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004793 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4794 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004795 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004796 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4797 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4798 // This means this code doesn't have to handle the case where "currentNetwork" no
4799 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4800 if (DBG) {
4801 log("Network " + newNetwork.name() + " stopped satisfying" +
4802 " request " + nri.request.requestId);
4803 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004804 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004805 if (currentNetwork == newNetwork) {
4806 mNetworkForRequestId.remove(nri.request.requestId);
4807 sendUpdatedScoreToFactories(nri.request, 0);
4808 } else {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004809 if (nri.request.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004810 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4811 newNetwork.name() +
4812 " without updating mNetworkForRequestId or factories!");
4813 }
4814 }
4815 // TODO: technically, sending CALLBACK_LOST here is
4816 // incorrect if nri is a request (not a listen) and there
4817 // is a replacement network currently connected that can
4818 // satisfy it. However, the only capability that can both
4819 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4820 // so this code is only incorrect for a network that loses
4821 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004822 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004823 }
4824 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004825 if (isNewDefault) {
4826 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004827 makeDefault(newNetwork);
4828 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4829 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004830 synchronized (ConnectivityService.this) {
4831 // have a new default network, release the transition wakelock in
4832 // a second if it's held. The second pause is to allow apps
4833 // to reconnect over the new network
4834 if (mNetTransitionWakeLock.isHeld()) {
4835 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4836 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4837 mNetTransitionWakeLockSerialNumber, 0),
4838 1000);
4839 }
4840 }
4841 }
4842
4843 // do this after the default net is switched, but
4844 // before LegacyTypeTracker sends legacy broadcasts
4845 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4846
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004847 // Linger any networks that are no longer needed. This should be done after sending the
4848 // available callback for newNetwork.
4849 for (NetworkAgentInfo nai : affectedNetworks) {
4850 updateLingerState(nai, now);
4851 }
4852 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4853 // does not need to be done in any particular order.
4854 updateLingerState(newNetwork, now);
4855
Paul Jensencf4c2c62015-07-01 14:16:32 -04004856 if (isNewDefault) {
4857 // Maintain the illusion: since the legacy API only
4858 // understands one network at a time, we must pretend
4859 // that the current default network disconnected before
4860 // the new one connected.
4861 if (oldDefaultNetwork != null) {
4862 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4863 oldDefaultNetwork, true);
4864 }
4865 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4866 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4867 notifyLockdownVpn(newNetwork);
4868 }
4869
Robert Greenwalt7b816022014-04-18 15:25:25 -07004870 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004871 // Notify battery stats service about this network, both the normal
4872 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004873 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004874 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004875 final IBatteryStats bs = BatteryStatsService.getService();
4876 final int type = newNetwork.networkInfo.getType();
4877
4878 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4879 bs.noteNetworkInterfaceType(baseIface, type);
4880 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4881 final String stackedIface = stacked.getInterfaceName();
4882 bs.noteNetworkInterfaceType(stackedIface, type);
4883 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4884 }
4885 } catch (RemoteException ignored) {
4886 }
4887
Robert Greenwalt152ed372014-12-17 17:19:53 -08004888 // This has to happen after the notifyNetworkCallbacks as that tickles each
4889 // ConnectivityManager instance so that legacy requests correctly bind dns
4890 // requests to this network. The legacy users are listening for this bcast
4891 // and will generally do a dns request so they can ensureRouteToHost and if
4892 // they do that before the callbacks happen they'll use the default network.
4893 //
4894 // TODO: Is there still a race here? We send the broadcast
4895 // after sending the callback, but if the app can receive the
4896 // broadcast before the callback, it might still break.
4897 //
4898 // This *does* introduce a race where if the user uses the new api
4899 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4900 // they may get old info. Reverse this after the old startUsing api is removed.
4901 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004902 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4903 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004904 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004905 // legacy type tracker filters out repeat adds
4906 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4907 }
4908 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004909
4910 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4911 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4912 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4913 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4914 if (newNetwork.isVPN()) {
4915 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4916 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004917 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004918 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4919 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004920 if (unneeded(nai)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004921 if (nai.getLingerExpiry() > 0) {
4922 // This network has active linger timers and no requests, but is not
4923 // lingering. Linger it.
4924 //
4925 // One way (the only way?) this can happen if this network is unvalidated
4926 // and became unneeded due to another network improving its score to the
4927 // point where this network will no longer be able to satisfy any requests
4928 // even if it validates.
4929 updateLingerState(nai, now);
4930 } else {
4931 if (DBG) log("Reaping " + nai.name());
4932 teardownUnneededNetwork(nai);
4933 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004934 }
4935 }
4936 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004937 }
4938
Paul Jensen1c7ba022015-06-16 14:27:36 -04004939 /**
4940 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4941 * being disconnected.
4942 * @param changed If only one Network's score or capabilities have been modified since the last
4943 * time this function was called, pass this Network in this argument, otherwise pass
4944 * null.
4945 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4946 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4947 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4948 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4949 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004950 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004951 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004952 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4953 // to avoid the slowness. It is not simply enough to process just "changed", for
4954 // example in the case where "changed"'s score decreases and another network should begin
4955 // satifying a NetworkRequest that "changed" currently satisfies.
4956
4957 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4958 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4959 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004960 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04004961 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004962 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004963 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004964 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4965 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4966 // Rematch higher scoring networks first to prevent requests first matching a lower
4967 // scoring network and then a higher scoring network, which could produce multiple
4968 // callbacks and inadvertently unlinger networks.
4969 Arrays.sort(nais);
4970 for (NetworkAgentInfo nai : nais) {
4971 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004972 // Only reap the last time through the loop. Reaping before all rematching
4973 // is complete could incorrectly teardown a network that hasn't yet been
4974 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004975 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004976 : ReapUnvalidatedNetworks.REAP,
4977 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004978 }
4979 }
4980 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004981
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004982 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004983 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004984 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004985 // For now only update icons for default connection.
4986 // TODO: Update WiFi and cellular icons separately. b/17237507
4987 if (!isDefaultNetwork(nai)) return;
4988
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004989 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004990 // Don't repeat publish.
4991 if (newInetCondition == mDefaultInetConditionPublished) return;
4992
4993 mDefaultInetConditionPublished = newInetCondition;
4994 sendInetConditionBroadcast(nai.networkInfo);
4995 }
4996
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004997 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4998 if (mLockdownTracker != null) {
4999 if (nai != null && nai.isVPN()) {
5000 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5001 } else {
5002 mLockdownTracker.onNetworkInfoChanged();
5003 }
5004 }
5005 }
5006
Robert Greenwalt7b816022014-04-18 15:25:25 -07005007 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5008 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005009 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005010 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005011 synchronized (networkAgent) {
5012 oldInfo = networkAgent.networkInfo;
5013 networkAgent.networkInfo = newInfo;
5014 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005015 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005016
5017 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005018 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5019 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5020 notifyIfacesChangedForNetworkStats();
5021 } else if (VDBG) log("ignoring duplicate network state non-change");
5022 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005023 return;
5024 }
5025 if (DBG) {
5026 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5027 (oldInfo == null ? "null" : oldInfo.getState()) +
5028 " to " + state);
5029 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005030
Robin Lee585e2482016-05-01 23:00:00 +01005031 if (!networkAgent.created
5032 && (state == NetworkInfo.State.CONNECTED
5033 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005034 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005035 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005036 if (networkAgent.isVPN()) {
5037 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005038 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5039 (networkAgent.networkMisc == null ||
5040 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005041 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005042 mNetd.createPhysicalNetwork(networkAgent.network.netId,
5043 networkAgent.networkCapabilities.hasCapability(
5044 NET_CAPABILITY_NOT_RESTRICTED) ?
5045 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005046 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005047 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005048 loge("Error creating network " + networkAgent.network.netId + ": "
5049 + e.getMessage());
5050 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005051 }
Paul Jenseneec75412014-08-04 12:21:19 -04005052 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005053 }
5054
5055 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5056 networkAgent.everConnected = true;
5057
Robert Greenwalt7b816022014-04-18 15:25:25 -07005058 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005059 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005060
Paul Jensenca8f16a2014-05-09 12:47:55 -04005061 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005062 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005063
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005064 if (networkAgent.isVPN()) {
5065 // Temporarily disable the default proxy (not global).
5066 synchronized (mProxyLock) {
5067 if (!mDefaultProxyDisabled) {
5068 mDefaultProxyDisabled = true;
5069 if (mGlobalProxy == null && mDefaultProxy != null) {
5070 sendProxyBroadcast(null);
5071 }
5072 }
5073 }
5074 // TODO: support proxy per network.
5075 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005076
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005077 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5078 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5079 // capabilities, so it only needs to be done once on initial connect, not every time the
5080 // network's capabilities change. Note that we do this before rematching the network,
5081 // so we could decide to tear it down immediately afterwards. That's fine though - on
5082 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5083 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005084 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005085
Paul Jensen2161a8e2014-09-11 11:00:39 -04005086 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005087 final long now = SystemClock.elapsedRealtime();
5088 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005089
5090 // This has to happen after matching the requests, because callbacks are just requests.
5091 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005092 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005093 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005094 if (networkAgent.isVPN()) {
5095 synchronized (mProxyLock) {
5096 if (mDefaultProxyDisabled) {
5097 mDefaultProxyDisabled = false;
5098 if (mGlobalProxy == null && mDefaultProxy != null) {
5099 sendProxyBroadcast(mDefaultProxy);
5100 }
5101 }
5102 }
5103 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005104 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5105 state == NetworkInfo.State.SUSPENDED) {
5106 // going into or coming out of SUSPEND: rescore and notify
5107 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005108 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005109 }
5110 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5111 ConnectivityManager.CALLBACK_SUSPENDED :
5112 ConnectivityManager.CALLBACK_RESUMED));
5113 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005114 }
5115 }
5116
Robert Greenwaltac96c522014-06-03 16:43:57 -07005117 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005118 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005119 if (score < 0) {
5120 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5121 "). Bumping score to min of 0");
5122 score = 0;
5123 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005124
Paul Jensen2161a8e2014-09-11 11:00:39 -04005125 final int oldScore = nai.getCurrentScore();
5126 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005127
Paul Jensen85cf78e2015-06-25 13:25:07 -04005128 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005129
Paul Jensenc8b9a742014-09-30 15:37:41 -04005130 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005131 }
5132
Robert Greenwalt9258c642014-03-26 16:47:06 -07005133 // notify only this one new request of the current state
5134 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5135 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005136 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005137 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005138 } else {
5139 sendPendingIntentForRequest(nri, nai, notifyType);
5140 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005141 }
5142
Robert Greenwalt8d482522015-06-24 13:23:42 -07005143 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005144 // The NetworkInfo we actually send out has no bearing on the real
5145 // state of affairs. For example, if the default connection is mobile,
5146 // and a request for HIPRI has just gone away, we need to pretend that
5147 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5148 // the state to DISCONNECTED, even though the network is of type MOBILE
5149 // and is still connected.
5150 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5151 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005152 if (state != DetailedState.DISCONNECTED) {
5153 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005154 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005155 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005156 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005157 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5158 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5159 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5160 if (info.isFailover()) {
5161 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5162 nai.networkInfo.setFailover(false);
5163 }
5164 if (info.getReason() != null) {
5165 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5166 }
5167 if (info.getExtraInfo() != null) {
5168 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5169 }
5170 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005171 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005172 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005173 if (newDefaultAgent != null) {
5174 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5175 newDefaultAgent.networkInfo);
5176 } else {
5177 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5178 }
5179 }
5180 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5181 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005182 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005183 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005184 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005185 }
5186 }
5187 }
5188
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005189 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005190 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005191 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5192 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005193 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5194 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005195 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005196 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005197 } else {
5198 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5199 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005200 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005201 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005202
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005203 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5204 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5205 }
5206
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005207 private String notifyTypeToName(int notifyType) {
5208 switch (notifyType) {
5209 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5210 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5211 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5212 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5213 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5214 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5215 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5216 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5217 }
5218 return "UNKNOWN";
5219 }
5220
Jeff Sharkey69736342014-12-08 14:50:12 -08005221 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005222 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5223 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005224 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005225 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005226 try {
5227 mStatsService.forceUpdateIfaces();
5228 } catch (Exception ignored) {
5229 }
5230 }
5231
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005232 @Override
5233 public boolean addVpnAddress(String address, int prefixLength) {
5234 throwIfLockdownEnabled();
5235 int user = UserHandle.getUserId(Binder.getCallingUid());
5236 synchronized (mVpns) {
5237 return mVpns.get(user).addAddress(address, prefixLength);
5238 }
5239 }
5240
5241 @Override
5242 public boolean removeVpnAddress(String address, int prefixLength) {
5243 throwIfLockdownEnabled();
5244 int user = UserHandle.getUserId(Binder.getCallingUid());
5245 synchronized (mVpns) {
5246 return mVpns.get(user).removeAddress(address, prefixLength);
5247 }
5248 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005249
5250 @Override
5251 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5252 throwIfLockdownEnabled();
5253 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005254 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005255 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005256 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005257 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005258 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005259 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005260 }
5261 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005262 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005263
5264 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005265 public String getCaptivePortalServerUrl() {
5266 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5267 }
5268
5269 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005270 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5271 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5272 enforceKeepalivePermission();
5273 mKeepaliveTracker.startNattKeepalive(
5274 getNetworkAgentInfoForNetwork(network),
5275 intervalSeconds, messenger, binder,
5276 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5277 }
5278
5279 @Override
5280 public void stopKeepalive(Network network, int slot) {
5281 mHandler.sendMessage(mHandler.obtainMessage(
5282 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5283 }
5284
5285 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005286 public void factoryReset() {
5287 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005288
5289 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5290 return;
5291 }
5292
Robin Lee3b3dd942015-05-12 18:14:58 +01005293 final int userId = UserHandle.getCallingUserId();
5294
Stuart Scottf1fb3972015-04-02 18:00:02 -07005295 // Turn airplane mode off
5296 setAirplaneMode(false);
5297
Stuart Scotte3e314d2015-04-20 14:07:45 -07005298 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5299 // Untether
5300 for (String tether : getTetheredIfaces()) {
5301 untether(tether);
5302 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005303 }
5304
Stuart Scotte3e314d2015-04-20 14:07:45 -07005305 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005306 // Remove always-on package
5307 synchronized (mVpns) {
5308 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5309 if (alwaysOnPackage != null) {
5310 setAlwaysOnVpnPackage(userId, null, false);
5311 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5312 }
5313 }
5314
Stuart Scotte3e314d2015-04-20 14:07:45 -07005315 // Turn VPN off
5316 VpnConfig vpnConfig = getVpnConfig(userId);
5317 if (vpnConfig != null) {
5318 if (vpnConfig.legacy) {
5319 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5320 } else {
5321 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5322 // in the future without user intervention.
5323 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005324
Victor Changb04a5ea2016-05-30 20:36:30 +01005325 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005326 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005327 }
5328 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005329
5330 Settings.Global.putString(mContext.getContentResolver(),
5331 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005332 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005333
5334 @VisibleForTesting
5335 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5336 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5337 return new NetworkMonitor(context, handler, nai, defaultRequest);
5338 }
Erik Kline48f12f22016-04-14 17:30:59 +09005339
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005340 @VisibleForTesting
5341 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5342 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5343 }
5344
Hugo Benichicfddd682016-05-31 16:28:06 +09005345 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005346 int newNetid = NETID_UNSET;
5347 int prevNetid = NETID_UNSET;
5348 int[] transports = new int[0];
5349 boolean hadIPv4 = false;
5350 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005351
Hugo Benichi5f16f762016-04-20 12:09:33 +09005352 if (newNai != null) {
5353 newNetid = newNai.network.netId;
5354 transports = newNai.networkCapabilities.getTransportTypes();
5355 }
5356 if (prevNai != null) {
5357 prevNetid = prevNai.network.netId;
5358 final LinkProperties lp = prevNai.linkProperties;
5359 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5360 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5361 }
5362
Hugo Benichicfddd682016-05-31 16:28:06 +09005363 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5364 }
5365
5366 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5367 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369}