blob: 97b0981f72edff9f47695f2ea0ac7bc057998d97 [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;
Wink Savilleab9321d2013-06-29 21:10:57 -070041import android.app.Notification;
42import android.app.NotificationManager;
43import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070048import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090051import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070052import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090054import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070056import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.INetworkPolicyListener;
58import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070059import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070063import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070065import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070067import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070068import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070069import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070070import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070071import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070072import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070073import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040074import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070075import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040076import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040077import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090078import android.net.metrics.DefaultNetworkEvent;
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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070097import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040098import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700100import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700101import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700102import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700103import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600104import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700105import android.util.LocalLog;
106import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600107import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700108import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800109import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700110import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500111import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700112import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700113import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
Wink Savilleab9321d2013-06-29 21:10:57 -0700115import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400116import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400117import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700118import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700119import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700121import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800122import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700123import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700124import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700125import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900126import com.android.internal.util.MessageUtils;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700127import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700128import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400129import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900130import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700131import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900132import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700133import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600134import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400135import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400136import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700137import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800138import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700139import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700140import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700141import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600142
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700143import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700144
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700145import org.xmlpull.v1.XmlPullParser;
146import org.xmlpull.v1.XmlPullParserException;
147
148import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700150import java.io.FileNotFoundException;
151import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700152import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700154import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700155import java.net.InetAddress;
156import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700157import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700158import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700159import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700160import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700161import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700162import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700163import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700164import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700165import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600166import java.util.SortedSet;
167import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
169/**
170 * @hide
171 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800172public class ConnectivityService extends IConnectivityManager.Stub
173 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700174 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900176 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700177 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
Jake Hamby786e71a2014-02-06 14:43:50 -0800179 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900180 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700181
Jeff Sharkey899223b2012-08-04 15:24:58 -0700182 // TODO: create better separation between radio types and network types
183
Robert Greenwalt42acef32009-08-12 16:08:25 -0700184 // how long to wait before switching back to a radio's default network
185 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
186 // system property that can override the above value
187 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
188 "android.telephony.apn-restore";
189
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900190 // How long to wait before putting up a "This network doesn't have an Internet connection,
191 // connect anyway?" dialog after the user selects a network that doesn't validate.
192 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
193
Jeremy Joslin79294842014-12-03 17:15:28 -0800194 // How long to delay to removal of a pending intent based request.
195 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
196 private final int mReleasePendingIntentDelayMs;
197
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800198 private Tethering mTethering;
199
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700200 private final PermissionMonitor mPermissionMonitor;
201
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700202 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700203
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700204 @GuardedBy("mVpns")
205 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700206
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700207 private boolean mLockdownEnabled;
208 private LockdownVpnTracker mLockdownTracker;
209
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700210 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
211 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700212 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600213 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700214 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700215 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600216 @GuardedBy("mRulesLock")
217 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
218 /** Flag indicating if background data is restricted. */
219 @GuardedBy("mRulesLock")
220 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700221
Erik Klineda4bfa82015-04-30 12:58:40 +0900222 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700224 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700225 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800227 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228
229 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700230 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700232 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800233 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700234 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700235
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700236 private String mCurrentTcpBufferSizes;
237
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700238 private static final int ENABLED = 1;
239 private static final int DISABLED = 0;
240
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900241 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
242 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class });
243
Paul Jensenb10e37f2014-11-25 12:33:08 -0500244 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400245 // Tear down networks that have no chance (e.g. even if validated) of becoming
246 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500247 // all networks have been rematched against all NetworkRequests.
248 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400249 // Don't reap networks. This should be passed when some networks have not yet been
250 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500251 DONT_REAP
252 };
253
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700254 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700255 * used internally to change our mobile data enabled flag
256 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700257 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700258
259 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700260 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700261 * from one net to another. Clear happens when we get a new
262 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
263 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700264 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700265 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700266
Robert Greenwalt434203a2010-10-11 16:00:27 -0700267 /**
268 * used internally to reload global proxy settings
269 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700270 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700271
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700272 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400273 * PAC manager has received new port.
274 */
275 private static final int EVENT_PROXY_HAS_CHANGED = 16;
276
Robert Greenwalte049c232014-04-11 15:53:27 -0700277 /**
278 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700279 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700280 */
281 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
282
Robert Greenwalt7b816022014-04-18 15:25:25 -0700283 /**
284 * used internally when registering NetworkAgents
285 * obj = Messenger
286 */
287 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
288
Robert Greenwalt9258c642014-03-26 16:47:06 -0700289 /**
290 * used to add a network request
291 * includes a NetworkRequestInfo
292 */
293 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
294
295 /**
296 * indicates a timeout period is over - check if we had a network yet or not
297 * and if not, call the timeout calback (but leave the request live until they
298 * cancel it.
299 * includes a NetworkRequestInfo
300 */
301 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
302
303 /**
304 * used to add a network listener - no request
305 * includes a NetworkRequestInfo
306 */
307 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
308
309 /**
310 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400311 * arg1 = UID of caller
312 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700313 */
314 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
315
Robert Greenwalta67be032014-05-16 15:49:14 -0700316 /**
317 * used internally when registering NetworkFactories
318 * obj = Messenger
319 */
320 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
321
Robert Greenwalt27711812014-06-25 16:45:57 -0700322 /**
323 * used internally to expire a wakelock when transitioning
324 * from one net to another. Expire happens when we fail to find
325 * a new network (typically after 1 minute) -
326 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
327 * a replacement network.
328 */
329 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
330
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700331 /**
332 * Used internally to indicate the system is ready.
333 */
334 private static final int EVENT_SYSTEM_READY = 25;
335
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800336 /**
337 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400338 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800339 */
340 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
341
342 /**
343 * used to remove a pending intent and its associated network request.
344 * arg1 = UID of caller
345 * obj = PendingIntent
346 */
347 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
348
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900349 /**
350 * used to specify whether a network should be used even if unvalidated.
351 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
352 * arg2 = whether to remember this choice in the future (1 or 0)
353 * obj = network
354 */
355 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
356
357 /**
358 * used to ask the user to confirm a connection to an unvalidated network.
359 * obj = network
360 */
361 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700362
Erik Klineda4bfa82015-04-30 12:58:40 +0900363 /**
364 * used internally to (re)configure mobile data always-on settings.
365 */
366 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
367
Paul Jensen694f2b82015-06-17 14:15:39 -0400368 /**
369 * used to add a network listener with a pending intent
370 * obj = NetworkRequestInfo
371 */
372 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
373
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900374 /** Handler thread used for both of the handlers below. */
375 @VisibleForTesting
376 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700377 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700378 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700379 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700380 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700381
Mike Lockwood0f79b542009-08-14 14:18:49 -0400382 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800383 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400384
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700385 private PowerManager.WakeLock mNetTransitionWakeLock;
386 private String mNetTransitionWakeLockCausedBy = "";
387 private int mNetTransitionWakeLockSerialNumber;
388 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800389 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700390
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700391 // used in DBG mode to track inet condition reports
392 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
393 private ArrayList mInetLog;
394
Robert Greenwalt434203a2010-10-11 16:00:27 -0700395 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400396 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700397 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700398 private boolean mDefaultProxyDisabled = false;
399
Robert Greenwalt434203a2010-10-11 16:00:27 -0700400 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400401 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700402
Jason Monk602b2322013-07-03 17:04:33 -0400403 private PacManager mPacManager = null;
404
Erik Klineda4bfa82015-04-30 12:58:40 +0900405 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700406
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400407 private UserManager mUserManager;
408
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700409 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700410 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700411
Robert Greenwalt50393202011-06-21 17:26:14 -0700412 // the set of network types that can only be enabled by system/sig apps
413 List mProtectedNetworks;
414
John Spurlockbf991a82013-06-24 14:20:23 -0400415 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700416
Wink Savilleab9321d2013-06-29 21:10:57 -0700417 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400418
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900419 private KeepaliveTracker mKeepaliveTracker;
420
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700421 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
422 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700423 private final static int MAX_NET_ID = 65535;
424 private int mNextNetId = MIN_NET_ID;
425
Robert Greenwalt34524f02014-05-18 16:22:10 -0700426 // sequence number of NetworkRequests
427 private int mNextNetworkRequestId = 1;
428
Erik Kline7523eb32015-07-09 18:24:03 +0900429 // NetworkRequest activity String log entries.
430 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
431 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
432
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700433 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
434 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400435 private static class ValidationLog {
436 final Network mNetwork;
437 final String mNetworkExtraInfo;
438 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700439
Paul Jensen0808eb82016-06-03 13:51:21 -0400440 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
441 mNetwork = network;
442 mNetworkExtraInfo = networkExtraInfo;
443 mLog = log;
444 }
445 }
446 private final ArrayDeque<ValidationLog> mValidationLogs =
447 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
448
449 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700450 synchronized(mValidationLogs) {
451 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
452 mValidationLogs.removeLast();
453 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400454 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700455 }
456 }
457
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700458 /**
459 * Implements support for the legacy "one network per network type" model.
460 *
461 * We used to have a static array of NetworkStateTrackers, one for each
462 * network type, but that doesn't work any more now that we can have,
463 * for example, more that one wifi network. This class stores all the
464 * NetworkAgentInfo objects that support a given type, but the legacy
465 * API will only see the first one.
466 *
467 * It serves two main purposes:
468 *
469 * 1. Provide information about "the network for a given type" (since this
470 * API only supports one).
471 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
472 * the first network for a given type changes, or if the default network
473 * changes.
474 */
475 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900476
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900477 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900478 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900479
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700480 /**
481 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
482 * Each list holds references to all NetworkAgentInfos that are used to
483 * satisfy requests for that network type.
484 *
485 * This array is built out at startup such that an unsupported network
486 * doesn't get an ArrayList instance, making this a tristate:
487 * unsupported, supported but not active and active.
488 *
489 * The actual lists are populated when we scan the network types that
490 * are supported on this device.
Hugo Benichi5224f002016-06-21 09:48:07 +0900491 *
492 * Threading model:
493 * - addSupportedType() is only called in the constructor
494 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
495 * They are therefore not thread-safe with respect to each other.
496 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
497 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
498 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700499 */
Hugo Benichi5224f002016-06-21 09:48:07 +0900500 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700501
502 public LegacyTypeTracker() {
503 mTypeLists = (ArrayList<NetworkAgentInfo>[])
504 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
505 }
506
507 public void addSupportedType(int type) {
508 if (mTypeLists[type] != null) {
509 throw new IllegalStateException(
510 "legacy list for type " + type + "already initialized");
511 }
512 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
513 }
514
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700515 public boolean isTypeSupported(int type) {
516 return isNetworkTypeValid(type) && mTypeLists[type] != null;
517 }
518
519 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi5224f002016-06-21 09:48:07 +0900520 synchronized (mTypeLists) {
521 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
522 return mTypeLists[type].get(0);
523 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700524 }
Hugo Benichi5224f002016-06-21 09:48:07 +0900525 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700526 }
527
Robert Greenwalt8d482522015-06-24 13:23:42 -0700528 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900529 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900530 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700531 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900532 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900534 }
535 }
536
537 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700538 public void add(int type, NetworkAgentInfo nai) {
539 if (!isTypeSupported(type)) {
540 return; // Invalid network type.
541 }
542 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
543
544 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
545 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700546 return;
547 }
Hugo Benichi5224f002016-06-21 09:48:07 +0900548 synchronized (mTypeLists) {
549 list.add(nai);
550 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900551
552 // 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 +0900553 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi5224f002016-06-21 09:48:07 +0900554 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700555 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
556 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700557 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700558 }
559
Lorenzo Colittia793a672014-07-31 23:20:17 +0900560 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900561 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900562 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
563 if (list == null || list.isEmpty()) {
564 return;
565 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900566 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900567
Hugo Benichi5224f002016-06-21 09:48:07 +0900568 synchronized (mTypeLists) {
569 if (!list.remove(nai)) {
570 return;
571 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900572 }
573
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 final DetailedState state = DetailedState.DISCONNECTED;
575
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900576 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 maybeLogBroadcast(nai, state, type, wasDefault);
578 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900579 }
580
581 if (!list.isEmpty() && wasFirstNetwork) {
582 if (DBG) log("Other network available for type " + type +
583 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900584 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700585 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
586 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900587 }
588 }
589
590 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900591 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
592 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700593 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900594 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700595 }
596 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700597
Robert Greenwalt8d482522015-06-24 13:23:42 -0700598 // send out another legacy broadcast - currently only used for suspend/unsuspend
599 // toggle
600 public void update(NetworkAgentInfo nai) {
601 final boolean isDefault = isDefaultNetwork(nai);
602 final DetailedState state = nai.networkInfo.getDetailedState();
603 for (int type = 0; type < mTypeLists.length; type++) {
604 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700605 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi5224f002016-06-21 09:48:07 +0900606 final boolean isFirst = contains && (nai == list.get(0));
607 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700608 maybeLogBroadcast(nai, state, type, isDefault);
609 sendLegacyNetworkBroadcast(nai, state, type);
610 }
611 }
612 }
613
Lorenzo Colittia793a672014-07-31 23:20:17 +0900614 private String naiToString(NetworkAgentInfo nai) {
615 String name = (nai != null) ? nai.name() : "null";
616 String state = (nai.networkInfo != null) ?
617 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
618 "???/???";
619 return name + " " + state;
620 }
621
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700622 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900623 pw.println("mLegacyTypeTracker:");
624 pw.increaseIndent();
625 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700626 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900627 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700628 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900629 pw.println();
630 pw.println("Current state:");
631 pw.increaseIndent();
Hugo Benichi5224f002016-06-21 09:48:07 +0900632 synchronized (mTypeLists) {
633 for (int type = 0; type < mTypeLists.length; type++) {
634 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
635 for (NetworkAgentInfo nai : mTypeLists[type]) {
636 pw.println(type + " " + naiToString(nai));
637 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900638 }
639 }
640 pw.decreaseIndent();
641 pw.decreaseIndent();
642 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700643 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700644 }
645 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
646
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900647 @VisibleForTesting
648 protected HandlerThread createHandlerThread() {
649 return new HandlerThread("ConnectivityServiceThread");
650 }
651
Jeff Sharkey899223b2012-08-04 15:24:58 -0700652 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700653 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800654 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800655
Erik Klineda4bfa82015-04-30 12:58:40 +0900656 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900657 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
Erik Kline371c7b72016-03-22 17:04:20 +0900658 new Binder(), NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +0900659 mNetworkRequests.put(mDefaultRequest, defaultNRI);
660 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900661
662 mDefaultMobileDataRequest = createInternetRequestForTransport(
663 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700664
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900665 mHandlerThread = createHandlerThread();
666 mHandlerThread.start();
667 mHandler = new InternalHandler(mHandlerThread.getLooper());
668 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700669
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800670 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800671 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
672 String id = Settings.Secure.getString(context.getContentResolver(),
673 Settings.Secure.ANDROID_ID);
674 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700675 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800676 SystemProperties.set("net.hostname", name);
677 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800678 }
679
Jeremy Joslin79294842014-12-03 17:15:28 -0800680 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
681 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
682
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700683 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700684 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800685 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700686 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700687 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700688 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700689
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700690 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600691 mPolicyManager.setConnectivityListener(mPolicyListener);
692 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700693 } catch (RemoteException e) {
694 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700695 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700696 }
697
698 final PowerManager powerManager = (PowerManager) context.getSystemService(
699 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700700 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
701 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
702 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800703 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700704
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700705 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700706
Wink Saville51f456f2013-04-23 14:26:51 -0700707 // TODO: What is the "correct" way to do determine if this is a wifi only device?
708 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
709 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700710 String[] naStrings = context.getResources().getStringArray(
711 com.android.internal.R.array.networkAttributes);
712 for (String naString : naStrings) {
713 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700714 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700715 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700716 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800717 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700718 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700719 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700720 }
Wink Saville51f456f2013-04-23 14:26:51 -0700721 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
722 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
723 n.type);
724 continue;
725 }
Wink Saville975c8482011-04-07 14:23:45 -0700726 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800727 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700728 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700729 continue;
730 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700731 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700732
Wink Saville975c8482011-04-07 14:23:45 -0700733 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700734 mNetworksDefined++;
735 } catch(Exception e) {
736 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700737 }
738 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700739
740 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
741 if (mNetConfigs[TYPE_VPN] == null) {
742 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
743 // don't need to add TYPE_VPN to mNetConfigs.
744 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
745 mNetworksDefined++; // used only in the log() statement below.
746 }
747
Wink Saville5e56bc52013-07-29 15:00:57 -0700748 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700749
Robert Greenwalt50393202011-06-21 17:26:14 -0700750 mProtectedNetworks = new ArrayList<Integer>();
751 int[] protectedNetworks = context.getResources().getIntArray(
752 com.android.internal.R.array.config_protectedNetworks);
753 for (int p : protectedNetworks) {
754 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
755 mProtectedNetworks.add(p);
756 } else {
757 if (DBG) loge("Ignoring protectedNetwork " + p);
758 }
759 }
760
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700761 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
762 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700763
Christopher Wiley497c1472016-10-11 13:26:03 -0700764 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
765 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800766
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700767 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
768
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700769 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700770 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100771 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700772 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700773 intentFilter.addAction(Intent.ACTION_USER_ADDED);
774 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000775 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700776 mContext.registerReceiverAsUser(
777 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900778
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700779 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700780 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700781 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700782 } catch (RemoteException e) {
783 loge("Error registering observer :" + e);
784 }
785
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700786 if (DBG) {
787 mInetLog = new ArrayList();
788 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700789
Erik Klineda4bfa82015-04-30 12:58:40 +0900790 mSettingsObserver = new SettingsObserver(mContext, mHandler);
791 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800792
John Spurlockbf991a82013-06-24 14:20:23 -0400793 mDataConnectionStats = new DataConnectionStats(mContext);
794 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400795
Jason Monkdecd2952013-10-10 14:02:51 -0400796 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700797
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400798 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900799
800 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700802
Erik Klineda4bfa82015-04-30 12:58:40 +0900803 private NetworkRequest createInternetRequestForTransport(int transportType) {
804 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900805 netCap.addCapability(NET_CAPABILITY_INTERNET);
806 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900807 if (transportType > -1) {
808 netCap.addTransportType(transportType);
809 }
810 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
811 }
812
813 private void handleMobileDataAlwaysOn() {
814 final boolean enable = (Settings.Global.getInt(
815 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
816 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
817 if (enable == isEnabled) {
818 return; // Nothing to do.
819 }
820
821 if (enable) {
822 handleRegisterNetworkRequest(new NetworkRequestInfo(
Erik Kline371c7b72016-03-22 17:04:20 +0900823 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
Erik Klineda4bfa82015-04-30 12:58:40 +0900824 } else {
825 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
826 }
827 }
828
829 private void registerSettingsCallbacks() {
830 // Watch for global HTTP proxy changes.
831 mSettingsObserver.observe(
832 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
833 EVENT_APPLY_GLOBAL_HTTP_PROXY);
834
835 // Watch for whether or not to keep mobile data always on.
836 mSettingsObserver.observe(
837 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
838 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
839 }
840
Robert Greenwalt34524f02014-05-18 16:22:10 -0700841 private synchronized int nextNetworkRequestId() {
842 return mNextNetworkRequestId++;
843 }
844
Paul Jensen67b0b072015-06-10 11:22:17 -0400845 @VisibleForTesting
846 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400847 synchronized (mNetworkForNetId) {
848 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
849 int netId = mNextNetId;
850 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
851 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500852 if (!mNetIdInUse.get(netId)) {
853 mNetIdInUse.put(netId, true);
854 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400855 }
856 }
857 }
858 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700859 }
860
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600861 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800862 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600863 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
864 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800865 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600866 state = nai.getNetworkState();
867 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800868 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600869 final NetworkInfo info = new NetworkInfo(networkType, 0,
870 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800871 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
872 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600873 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
874 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800875 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600876 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600877 return state;
878 } else {
879 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800880 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400881 }
882
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800883 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
884 if (network == null) {
885 return null;
886 }
887 synchronized (mNetworkForNetId) {
888 return mNetworkForNetId.get(network.netId);
889 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600890 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800891
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900892 private Network[] getVpnUnderlyingNetworks(int uid) {
893 if (!mLockdownEnabled) {
894 int user = UserHandle.getUserId(uid);
895 synchronized (mVpns) {
896 Vpn vpn = mVpns.get(user);
897 if (vpn != null && vpn.appliesToUid(uid)) {
898 return vpn.getUnderlyingNetworks();
899 }
900 }
901 }
902 return null;
903 }
904
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800905 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400906 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800907
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900908 final Network[] networks = getVpnUnderlyingNetworks(uid);
909 if (networks != null) {
910 // getUnderlyingNetworks() returns:
911 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
912 // empty array => the VPN explicitly said "no default network".
913 // non-empty array => the VPN specified one or more default networks; we use the
914 // first one.
915 if (networks.length > 0) {
916 nai = getNetworkAgentInfoForNetwork(networks[0]);
917 } else {
918 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800919 }
920 }
921
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800922 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600923 return nai.getNetworkState();
924 } else {
925 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800926 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400927 }
928
929 /**
930 * Check if UID should be blocked from using the network with the given LinkProperties.
931 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600932 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
933 boolean ignoreBlocked) {
934 // Networks aren't blocked when ignoring blocked status
935 if (ignoreBlocked) return false;
936 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -0700937 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600938
939 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700940 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700941
Robin Lee17e61832016-05-09 13:46:28 +0100942 synchronized (mVpns) {
943 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
944 if (vpn != null && vpn.isBlockingUid(uid)) {
945 return true;
946 }
947 }
948
Robert Greenwalt12e67352014-05-13 21:41:06 -0700949 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700950 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600951 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -0700952 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700953 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700954
Felipe Lemed31a97f2016-05-06 14:53:50 -0700955 boolean allowed = true;
956 // Check Data Saver Mode first...
957 if (networkMetered) {
958 if ((uidRules & RULE_REJECT_METERED) != 0) {
959 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
960 // Explicitly blacklisted.
961 allowed = false;
962 } else {
963 allowed = !mRestrictBackground
964 || (uidRules & RULE_ALLOW_METERED) != 0
965 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
966 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
967 + " mRestrictBackground=" + mRestrictBackground
968 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
969 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
970 + ": " + allowed);
971 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700972 }
Felipe Leme781ba142016-05-09 16:24:48 -0700973 // ...then power restrictions.
974 if (allowed) {
975 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -0700976 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -0700977 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -0700978 }
979 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700980 }
981
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900982 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
983 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
984 boolean removed = false;
985 boolean added = false;
986 synchronized (mBlockedAppUids) {
987 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
988 added = true;
989 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
990 removed = true;
991 }
992 }
993 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
994 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
995 }
996
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700997 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600998 * Apply any relevant filters to {@link NetworkState} for the given UID. For
999 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1000 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1001 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001002 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001003 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001004 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1005
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001006 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001007 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001008 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001009 if (mLockdownTracker != null) {
1010 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001011 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001012
1013 // TODO: apply metered state closer to NetworkAgentInfo
1014 final long token = Binder.clearCallingIdentity();
1015 try {
1016 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1017 } catch (RemoteException e) {
1018 } finally {
1019 Binder.restoreCallingIdentity(token);
1020 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001021 }
1022
1023 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 * Return NetworkInfo for the active (i.e., connected) network interface.
1025 * It is assumed that at most one network is active at a time. If more
1026 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001027 * @return the info for the active network, or {@code null} if none is
1028 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001030 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001032 enforceAccessPermission();
1033 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001034 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001035 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001036 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1037 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
1039
Paul Jensen31a94f42015-02-13 14:18:39 -05001040 @Override
1041 public Network getActiveNetwork() {
1042 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001043 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001044 }
1045
1046 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001047 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001048 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001049 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001050 }
1051
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001052 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001053 final int user = UserHandle.getUserId(uid);
1054 int vpnNetId = NETID_UNSET;
1055 synchronized (mVpns) {
1056 final Vpn vpn = mVpns.get(user);
1057 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1058 }
1059 NetworkAgentInfo nai;
1060 if (vpnNetId != NETID_UNSET) {
1061 synchronized (mNetworkForNetId) {
1062 nai = mNetworkForNetId.get(vpnNetId);
1063 }
1064 if (nai != null) return nai.network;
1065 }
1066 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001067 if (nai != null
1068 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1069 nai = null;
1070 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001071 return nai != null ? nai.network : null;
1072 }
1073
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001074 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1075 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001076 final int uid = Binder.getCallingUid();
1077 NetworkState state = getUnfilteredActiveNetworkState(uid);
1078 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001079 }
1080
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001081 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001082 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001083 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001084 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001085 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001086 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001087 }
1088
1089 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 public NetworkInfo getNetworkInfo(int networkType) {
1091 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001092 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001093 if (getVpnUnderlyingNetworks(uid) != null) {
1094 // A VPN is active, so we may need to return one of its underlying networks. This
1095 // information is not available in LegacyTypeTracker, so we have to get it from
1096 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001097 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001098 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001099 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001100 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001101 }
1102 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001103 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001104 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 }
1106
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001107 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001108 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001109 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001110 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001111 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001112 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001113 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001114 return state.networkInfo;
1115 } else {
1116 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001117 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001118 }
1119
1120 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 public NetworkInfo[] getAllNetworkInfo() {
1122 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001123 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001124 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1125 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001126 NetworkInfo info = getNetworkInfo(networkType);
1127 if (info != null) {
1128 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001131 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 }
1133
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001134 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001135 public Network getNetworkForType(int networkType) {
1136 enforceAccessPermission();
1137 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001138 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1139 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001140 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001141 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001142 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001143 }
1144
1145 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001146 public Network[] getAllNetworks() {
1147 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001148 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001149 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001150 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001151 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001152 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001153 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001154 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001155 }
1156
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001157 @Override
1158 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1159 // The basic principle is: if an app's traffic could possibly go over a
1160 // network, without the app doing anything multinetwork-specific,
1161 // (hence, by "default"), then include that network's capabilities in
1162 // the array.
1163 //
1164 // In the normal case, app traffic only goes over the system's default
1165 // network connection, so that's the only network returned.
1166 //
1167 // With a VPN in force, some app traffic may go into the VPN, and thus
1168 // over whatever underlying networks the VPN specifies, while other app
1169 // traffic may go over the system default network (e.g.: a split-tunnel
1170 // VPN, or an app disallowed by the VPN), so the set of networks
1171 // returned includes the VPN's underlying networks and the system
1172 // default.
1173 enforceAccessPermission();
1174
1175 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1176
1177 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001178 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001179 if (nc != null) {
1180 result.put(nai.network, nc);
1181 }
1182
1183 if (!mLockdownEnabled) {
1184 synchronized (mVpns) {
1185 Vpn vpn = mVpns.get(userId);
1186 if (vpn != null) {
1187 Network[] networks = vpn.getUnderlyingNetworks();
1188 if (networks != null) {
1189 for (Network network : networks) {
1190 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001191 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001192 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001193 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001194 }
1195 }
1196 }
1197 }
1198 }
1199 }
1200
1201 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1202 out = result.values().toArray(out);
1203 return out;
1204 }
1205
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001206 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001207 public boolean isNetworkSupported(int networkType) {
1208 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001209 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001210 }
1211
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001212 /**
1213 * Return LinkProperties for the active (i.e., connected) default
1214 * network interface. It is assumed that at most one default network
1215 * is active at a time. If more than one is active, it is indeterminate
1216 * which will be returned.
1217 * @return the ip properties for the active network, or {@code null} if
1218 * none is active
1219 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001220 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001221 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001222 enforceAccessPermission();
1223 final int uid = Binder.getCallingUid();
1224 NetworkState state = getUnfilteredActiveNetworkState(uid);
1225 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001226 }
1227
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001228 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001229 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001230 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001231 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1232 if (nai != null) {
1233 synchronized (nai) {
1234 return new LinkProperties(nai.linkProperties);
1235 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001236 }
1237 return null;
1238 }
1239
Robert Greenwalt12e67352014-05-13 21:41:06 -07001240 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001241 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001242 public LinkProperties getLinkProperties(Network network) {
1243 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001244 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001245 if (nai != null) {
1246 synchronized (nai) {
1247 return new LinkProperties(nai.linkProperties);
1248 }
1249 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001250 return null;
1251 }
1252
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001253 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001254 if (nai != null) {
1255 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001256 if (nai.networkCapabilities != null) {
1257 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001258 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001259 }
1260 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001261 return null;
1262 }
1263
1264 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001265 public NetworkCapabilities getNetworkCapabilities(Network network) {
1266 enforceAccessPermission();
1267 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1268 }
1269
1270 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001271 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001272 // Require internal since we're handing out IMSI details
1273 enforceConnectivityInternalPermission();
1274
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001275 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001276 for (Network network : getAllNetworks()) {
1277 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1278 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001279 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001280 }
1281 }
1282 return result.toArray(new NetworkState[result.size()]);
1283 }
1284
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001285 @Override
1286 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1287 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001288 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001289 final long token = Binder.clearCallingIdentity();
1290 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001291 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1292 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001293 try {
1294 return mPolicyManager.getNetworkQuotaInfo(state);
1295 } catch (RemoteException e) {
1296 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001297 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001298 return null;
1299 } finally {
1300 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001301 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001302 }
1303
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001304 @Override
1305 public boolean isActiveNetworkMetered() {
1306 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001307
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001308 final NetworkInfo info = getActiveNetworkInfo();
1309 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001310 }
1311
Jeff Sharkey216c1812012-08-05 14:29:23 -07001312 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1313 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001314 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001315 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001316 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001317 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001318 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001319
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001320 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 * Ensure that a network route exists to deliver traffic to the specified
1322 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001323 * @param networkType the type of the network over which traffic to the
1324 * specified host is to be routed
1325 * @param hostAddress the IP address of the host to which the route is
1326 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 * @return {@code true} on success, {@code false} on failure
1328 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001329 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001331 if (mProtectedNetworks.contains(networkType)) {
1332 enforceConnectivityInternalPermission();
1333 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001334
Chad Brubakerc0234532014-02-14 13:24:29 -08001335 InetAddress addr;
1336 try {
1337 addr = InetAddress.getByAddress(hostAddress);
1338 } catch (UnknownHostException e) {
1339 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1340 return false;
1341 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001344 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 return false;
1346 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001347
1348 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1349 if (nai == null) {
1350 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1351 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1352 } else {
1353 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1354 }
1355 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001356 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001357
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001358 DetailedState netState;
1359 synchronized (nai) {
1360 netState = nai.networkInfo.getDetailedState();
1361 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001362
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001363 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001364 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001365 log("requestRouteToHostAddress on down network "
1366 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001367 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001368 }
1369 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001371
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001372 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001373 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001374 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001375 LinkProperties lp;
1376 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001377 synchronized (nai) {
1378 lp = nai.linkProperties;
1379 netId = nai.network.netId;
1380 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001381 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001382 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1383 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001384 } finally {
1385 Binder.restoreCallingIdentity(token);
1386 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001387 }
1388
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001389 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001390 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001391 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001392 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001393 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001394 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001395 if (bestRoute.getGateway().equals(addr)) {
1396 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001397 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001398 } else {
1399 // if we will connect to this through another route, add a direct route
1400 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001401 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001402 }
1403 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001404 if (DBG) log("Adding legacy route " + bestRoute +
1405 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001406 try {
1407 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1408 } catch (Exception e) {
1409 // never crash - catch them all
1410 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001411 return false;
1412 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001413 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001416 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1417 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001418 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001419 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001420 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001421 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001422 }
1423
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001424 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001425 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001426 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001427 if (oldRules == uidRules) return;
1428
Felipe Leme781ba142016-05-09 16:24:48 -07001429 if (uidRules == RULE_NONE) {
1430 mUidRules.delete(uid);
1431 } else {
1432 mUidRules.put(uid, uidRules);
1433 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001434 }
1435
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001436 // TODO: notify UID when it has requested targeted updates
1437 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001438
1439 @Override
1440 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001441 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001442 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001443 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001444 }
1445
1446 synchronized (mRulesLock) {
1447 mMeteredIfaces.clear();
1448 for (String iface : meteredIfaces) {
1449 mMeteredIfaces.add(iface);
1450 }
1451 }
1452 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001453
1454 @Override
1455 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1456 // caller is NPMS, since we only register with them
1457 if (LOGD_RULES) {
1458 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1459 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001460
1461 synchronized (mRulesLock) {
1462 mRestrictBackground = restrictBackground;
1463 }
1464
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001465 if (restrictBackground) {
1466 log("onRestrictBackgroundChanged(true): disabling tethering");
1467 mTethering.untetherAll();
1468 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001469 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001470
1471 @Override
1472 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1473 if (LOGD_RULES) {
1474 // caller is NPMS, since we only register with them
1475 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1476 + whitelisted + ")");
1477 }
1478 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001479 @Override
1480 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1481 if (LOGD_RULES) {
1482 // caller is NPMS, since we only register with them
1483 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1484 + blacklisted + ")");
1485 }
1486 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001487 };
1488
Robin Lee3b3dd942015-05-12 18:14:58 +01001489 /**
1490 * Require that the caller is either in the same user or has appropriate permission to interact
1491 * across users.
1492 *
1493 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1494 */
1495 private void enforceCrossUserPermission(int userId) {
1496 if (userId == UserHandle.getCallingUserId()) {
1497 // Not a cross-user call.
1498 return;
1499 }
1500 mContext.enforceCallingOrSelfPermission(
1501 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1502 "ConnectivityService");
1503 }
1504
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001505 private void enforceInternetPermission() {
1506 mContext.enforceCallingOrSelfPermission(
1507 android.Manifest.permission.INTERNET,
1508 "ConnectivityService");
1509 }
1510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001512 mContext.enforceCallingOrSelfPermission(
1513 android.Manifest.permission.ACCESS_NETWORK_STATE,
1514 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516
1517 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001518 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 }
1520
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001521 private void enforceTetherAccessPermission() {
1522 mContext.enforceCallingOrSelfPermission(
1523 android.Manifest.permission.ACCESS_NETWORK_STATE,
1524 "ConnectivityService");
1525 }
1526
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001527 private void enforceConnectivityInternalPermission() {
1528 mContext.enforceCallingOrSelfPermission(
1529 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1530 "ConnectivityService");
1531 }
1532
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001533 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001534 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001535 }
1536
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001537 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001538 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001539 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001540 }
1541
1542 private void sendInetConditionBroadcast(NetworkInfo info) {
1543 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1544 }
1545
Wink Saville628b0852011-08-04 15:01:58 -07001546 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001547 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001548 info = new NetworkInfo(info);
1549 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001550 }
1551
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001552 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001553 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001554 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 if (info.isFailover()) {
1556 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1557 info.setFailover(false);
1558 }
1559 if (info.getReason() != null) {
1560 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1561 }
1562 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001563 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1564 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001566 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001567 return intent;
1568 }
1569
1570 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1571 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1572 }
1573
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001574 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001575 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1576 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1577 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001578 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001579 final long ident = Binder.clearCallingIdentity();
1580 try {
1581 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1582 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1583 } finally {
1584 Binder.restoreCallingIdentity(ident);
1585 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001586 }
1587
Mike Lockwood0f79b542009-08-14 14:18:49 -04001588 private void sendStickyBroadcast(Intent intent) {
1589 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001590 if (!mSystemReady) {
1591 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001592 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001593 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001594 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001595 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001596 }
1597
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001598 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001599 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001600 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001601 final NetworkInfo ni = intent.getParcelableExtra(
1602 ConnectivityManager.EXTRA_NETWORK_INFO);
1603 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1604 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1605 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001606 } else {
1607 BroadcastOptions opts = BroadcastOptions.makeBasic();
1608 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1609 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001610 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001611 final IBatteryStats bs = BatteryStatsService.getService();
1612 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001613 bs.noteConnectivityChanged(intent.getIntExtra(
1614 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1615 ni != null ? ni.getState().toString() : "?");
1616 } catch (RemoteException e) {
1617 }
1618 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001619 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001620 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001621 } finally {
1622 Binder.restoreCallingIdentity(ident);
1623 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001624 }
1625 }
1626
1627 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001628 loadGlobalProxy();
1629
Mike Lockwood0f79b542009-08-14 14:18:49 -04001630 synchronized(this) {
1631 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001632 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001633 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001634 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001635 }
1636 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001637 // load the global proxy at startup
1638 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001639
Robin Lee244ce8e2016-01-05 18:03:46 +00001640 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1641 // for user to unlock device too.
1642 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001643
Erik Klineda4bfa82015-04-30 12:58:40 +09001644 // Configure whether mobile data is always on.
1645 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1646
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001647 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001648
1649 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
1651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001653 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001654 *
1655 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001656 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001657 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001658 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1659 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001660
1661 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001662 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001663
Robert Greenwalt7b816022014-04-18 15:25:25 -07001664 if (networkAgent.networkCapabilities.hasTransport(
1665 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001666 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1667 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001668 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001669 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001670 } else if (networkAgent.networkCapabilities.hasTransport(
1671 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001672 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1673 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001674 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001675 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001676 } else {
1677 // do not track any other networks
1678 timeout = 0;
1679 }
1680
Robert Greenwalt7b816022014-04-18 15:25:25 -07001681 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001682 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001683 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001684 } catch (Exception e) {
1685 // You shall not crash!
1686 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001687 }
1688 }
1689 }
1690
1691 /**
1692 * Remove data activity tracking when network disconnects.
1693 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001694 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1695 final String iface = networkAgent.linkProperties.getInterfaceName();
1696 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001697
Robert Greenwalt7b816022014-04-18 15:25:25 -07001698 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1699 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001700 try {
1701 // the call fails silently if no idletimer setup for this interface
1702 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001703 } catch (Exception e) {
1704 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001705 }
1706 }
1707 }
1708
1709 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001710 * Reads the network specific MTU size from reources.
1711 * and set it on it's iface.
1712 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001713 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1714 final String iface = newLp.getInterfaceName();
1715 final int mtu = newLp.getMtu();
1716 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1717 if (VDBG) log("identical MTU - not setting");
1718 return;
1719 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001720
Robert Greenwalt43074032014-08-15 17:53:05 -07001721 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001722 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001723 return;
1724 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001725
w1997615afd812014-08-05 15:18:11 -07001726 // Cannot set MTU without interface name
1727 if (TextUtils.isEmpty(iface)) {
1728 loge("Setting MTU size with null iface.");
1729 return;
1730 }
1731
Robert Greenwalt7b816022014-04-18 15:25:25 -07001732 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001733 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001734 mNetd.setMtu(iface, mtu);
1735 } catch (Exception e) {
1736 Slog.e(TAG, "exception in setMtu()" + e);
1737 }
1738 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001739
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001740 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001741 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1742
1743 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001744 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001745 protected int getDefaultTcpRwnd() {
1746 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1747 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001748
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001749 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1750 if (isDefaultNetwork(nai) == false) {
1751 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001752 }
1753
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001754 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1755 String[] values = null;
1756 if (tcpBufferSizes != null) {
1757 values = tcpBufferSizes.split(",");
1758 }
1759
1760 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001761 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001762 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1763 values = tcpBufferSizes.split(",");
1764 }
1765
1766 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1767
1768 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001769 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001770
1771 final String prefix = "/sys/kernel/ipv4/tcp_";
1772 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1773 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1774 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1775 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1776 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1777 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1778 mCurrentTcpBufferSizes = tcpBufferSizes;
1779 } catch (IOException e) {
1780 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001781 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001782
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001783 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001784 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001785 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1786 if (rwndValue != 0) {
1787 SystemProperties.set(sysctlKey, rwndValue.toString());
1788 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001789 }
1790
Mattias Falk8b47b362011-08-23 14:15:13 +02001791 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001792 /*
1793 * Tell the VMs to toss their DNS caches
1794 */
1795 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1796 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001797 /*
1798 * Connectivity events can happen before boot has completed ...
1799 */
1800 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001801 final long ident = Binder.clearCallingIdentity();
1802 try {
1803 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1804 } finally {
1805 Binder.restoreCallingIdentity(ident);
1806 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001807 }
1808
Robert Greenwalt562cc542014-05-15 18:07:26 -07001809 @Override
1810 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001811 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1812 NETWORK_RESTORE_DELAY_PROP_NAME);
1813 if(restoreDefaultNetworkDelayStr != null &&
1814 restoreDefaultNetworkDelayStr.length() != 0) {
1815 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001816 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001817 } catch (NumberFormatException e) {
1818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001820 // if the system property isn't set, use the value for the apn type
1821 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1822
1823 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1824 (mNetConfigs[networkType] != null)) {
1825 ret = mNetConfigs[networkType].restoreTime;
1826 }
1827 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
1829
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001830 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001831 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001832 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001833 }
1834 return false;
1835 }
1836
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001837 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1838 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1839 final long DIAG_TIME_MS = 5000;
1840 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1841 // Start gathering diagnostic information.
1842 netDiags.add(new NetworkDiagnostics(
1843 nai.network,
1844 new LinkProperties(nai.linkProperties), // Must be a copy.
1845 DIAG_TIME_MS));
1846 }
1847
1848 for (NetworkDiagnostics netDiag : netDiags) {
1849 pw.println();
1850 netDiag.waitForMeasurements();
1851 netDiag.dump(pw);
1852 }
1853 }
1854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001856 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1857 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001858 if (mContext.checkCallingOrSelfPermission(
1859 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001861 pw.println("Permission Denial: can't dump ConnectivityService " +
1862 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1863 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 return;
1865 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001866
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001867 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001868 dumpNetworkDiagnostics(pw);
1869 return;
1870 }
Erik Kline379747a2015-06-05 17:47:34 +09001871
Lorenzo Colittie3805462015-06-03 11:18:24 +09001872 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001873 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001874 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001875 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001876 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001877 pw.println();
1878
Paul Jensen85cf78e2015-06-25 13:25:07 -04001879 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001880 pw.print("Active default network: ");
1881 if (defaultNai == null) {
1882 pw.println("none");
1883 } else {
1884 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001886 pw.println();
1887
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001888 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001889 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001890 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1891 pw.println(nai.toString());
1892 pw.increaseIndent();
1893 pw.println("Requests:");
1894 pw.increaseIndent();
1895 for (int i = 0; i < nai.networkRequests.size(); i++) {
1896 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001897 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001898 pw.decreaseIndent();
1899 pw.println("Lingered:");
1900 pw.increaseIndent();
1901 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1902 pw.decreaseIndent();
1903 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001904 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001905 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001906 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001907
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001908 pw.println("Metered Interfaces:");
1909 pw.increaseIndent();
1910 for (String value : mMeteredIfaces) {
1911 pw.println(value);
1912 }
1913 pw.decreaseIndent();
1914 pw.println();
1915
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001916 pw.print("Restrict background: ");
1917 pw.println(mRestrictBackground);
1918 pw.println();
1919
Felipe Leme46c4fc32016-05-04 09:21:43 -07001920 pw.println("Status for known UIDs:");
1921 pw.increaseIndent();
1922 final int size = mUidRules.size();
1923 for (int i = 0; i < size; i++) {
1924 final int uid = mUidRules.keyAt(i);
1925 pw.print("UID=");
1926 pw.print(uid);
1927 final int uidRules = mUidRules.get(uid, RULE_NONE);
1928 pw.print(" rules=");
1929 pw.print(uidRulesToString(uidRules));
1930 pw.println();
1931 }
1932 pw.println();
1933 pw.decreaseIndent();
1934
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001935 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001936 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001937 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1938 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001939 }
1940 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001941 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001942
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001943 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001944
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001945 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001946 pw.print("mNetTransitionWakeLock: currently " +
1947 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1948 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1949 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1950 } else {
1951 pw.println(", last requested never");
1952 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001953 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001954
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001955 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001956 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001957
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001958 pw.println();
1959 mKeepaliveTracker.dump(pw);
1960
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001961 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001962
Lorenzo Colittie3805462015-06-03 11:18:24 +09001963 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001964 pw.println();
1965 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001966 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001967 for(int i = 0; i < mInetLog.size(); i++) {
1968 pw.println(mInetLog.get(i));
1969 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001970 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001971 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001972
1973 if (argsContain(args, "--short") == false) {
1974 pw.println();
1975 synchronized (mValidationLogs) {
1976 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001977 for (ValidationLog p : mValidationLogs) {
1978 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001979 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001980 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001981 pw.decreaseIndent();
1982 }
1983 }
Erik Kline7523eb32015-07-09 18:24:03 +09001984
1985 pw.println();
1986 pw.println("mNetworkRequestInfoLogs (most recent first):");
1987 pw.increaseIndent();
1988 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1989 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 }
1992
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001993 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001994 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001995 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001996 if (officialNai != null && officialNai.equals(nai)) return true;
1997 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001998 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001999 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002000 " - " + nai);
2001 }
2002 return false;
2003 }
2004
Paul Jensenc8b9a742014-09-30 15:37:41 -04002005 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09002006 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04002007 }
2008
Robert Greenwalt42acef32009-08-12 16:08:25 -07002009 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002010 private class NetworkStateTrackerHandler extends Handler {
2011 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002012 super(looper);
2013 }
2014
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002015 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002017 default:
2018 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002019 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002020 handleAsyncChannelHalfConnect(msg);
2021 break;
2022 }
2023 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2024 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2025 if (nai != null) nai.asyncChannel.disconnect();
2026 break;
2027 }
2028 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2029 handleAsyncChannelDisconnected(msg);
2030 break;
2031 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002032 }
2033 return true;
2034 }
2035
2036 private void maybeHandleNetworkAgentMessage(Message msg) {
2037 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2038 if (nai == null) {
2039 if (VDBG) {
2040 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2041 log(String.format("%s from unknown NetworkAgent", what));
2042 }
2043 return;
2044 }
2045
2046 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002047 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002048 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2049 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2050 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2051 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002052 }
Robin Lee585e2482016-05-01 23:00:00 +01002053 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002054 networkCapabilities)) {
2055 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2056 + nai.networkCapabilities + " -> " + networkCapabilities);
2057 }
2058 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002059 break;
2060 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002061 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002062 if (VDBG) {
2063 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002064 "; created=" + nai.created +
2065 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002066 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002067 LinkProperties oldLp = nai.linkProperties;
2068 synchronized (nai) {
2069 nai.linkProperties = (LinkProperties)msg.obj;
2070 }
Robin Lee585e2482016-05-01 23:00:00 +01002071 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002072 break;
2073 }
2074 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002075 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002076 updateNetworkInfo(nai, info);
2077 break;
2078 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002079 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002080 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002081 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002082 break;
2083 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002084 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002085 try {
2086 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002087 } catch (Exception e) {
2088 // Never crash!
2089 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002090 }
2091 break;
2092 }
2093 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002094 try {
2095 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002096 } catch (Exception e) {
2097 // Never crash!
2098 loge("Exception in removeVpnUidRanges: " + e);
2099 }
2100 break;
2101 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002102 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002103 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2104 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002105 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002106 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002107 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002108 break;
2109 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002110 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002111 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2112 break;
2113 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002114 }
2115 }
2116
2117 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2118 switch (msg.what) {
2119 default:
2120 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002121 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002122 final NetworkAgentInfo nai;
2123 synchronized (mNetworkForNetId) {
2124 nai = mNetworkForNetId.get(msg.arg2);
2125 }
2126 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002127 final boolean valid =
2128 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002129 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2130 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002131 if (valid != nai.lastValidated) {
2132 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002133 nai.lastValidated = valid;
2134 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002135 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002136 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2137 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002138 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002139 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002140 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002141 Bundle redirectUrlBundle = new Bundle();
2142 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002143 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002144 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002145 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002146 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002147 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002148 break;
2149 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002150 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002151 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002152 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002153 handleLingerComplete(nai);
2154 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002155 break;
2156 }
Paul Jensen869868be2014-05-15 10:33:05 -04002157 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002158 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002159 final boolean visible = (msg.arg1 != 0);
2160 final NetworkAgentInfo nai;
2161 synchronized (mNetworkForNetId) {
2162 nai = mNetworkForNetId.get(netId);
2163 }
2164 // If captive portal status has changed, update capabilities.
2165 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2166 nai.lastCaptivePortalDetected = visible;
2167 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002168 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002169 }
2170 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002171 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002172 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002173 if (nai == null) {
2174 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2175 break;
2176 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002177 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002178 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2179 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002180 }
Paul Jensen869868be2014-05-15 10:33:05 -04002181 break;
2182 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002183 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002184 return true;
2185 }
2186
2187 @Override
2188 public void handleMessage(Message msg) {
2189 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2190 maybeHandleNetworkAgentMessage(msg);
2191 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002192 }
2193 }
2194
Paul Jensen85cf78e2015-06-25 13:25:07 -04002195 private void linger(NetworkAgentInfo nai) {
2196 nai.lingering = true;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002197 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002198 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2199 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2200 }
2201
Paul Jensen0cc17322014-11-25 15:26:53 -05002202 // Cancel any lingering so the linger timeout doesn't teardown a network.
2203 // This should be called when a network begins satisfying a NetworkRequest.
2204 // Note: depending on what state the NetworkMonitor is in (e.g.,
2205 // if it's awaiting captive portal login, or if validation failed), this
2206 // may trigger a re-evaluation of the network.
2207 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002208 nai.networkLingered.clear();
2209 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002210 nai.lingering = false;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002211 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
Paul Jensen0cc17322014-11-25 15:26:53 -05002212 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002213 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2214 }
2215
Robert Greenwalt7b816022014-04-18 15:25:25 -07002216 private void handleAsyncChannelHalfConnect(Message msg) {
2217 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002218 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002219 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2220 if (VDBG) log("NetworkFactory connected");
2221 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002222 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002223 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002224 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002225 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002226 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002227 }
2228 } else {
2229 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002230 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002231 }
2232 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2233 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2234 if (VDBG) log("NetworkAgent connected");
2235 // A network agent has requested a connection. Establish the connection.
2236 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2237 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2238 } else {
2239 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002240 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002241 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002242 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002243 synchronized (mNetworkForNetId) {
2244 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002245 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002246 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002247 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002248 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002249 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002250 }
2251 }
2252 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002253
Robert Greenwalt7b816022014-04-18 15:25:25 -07002254 private void handleAsyncChannelDisconnected(Message msg) {
2255 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2256 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002257 if (DBG) {
2258 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2259 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002260 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002261 // TODO - if we move the logic to the network agent (have them disconnect
2262 // because they lost all their requests or because their score isn't good)
2263 // then they would disconnect organically, report their new state and then
2264 // disconnect the channel.
2265 if (nai.networkInfo.isConnected()) {
2266 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2267 null, null);
2268 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002269 final boolean wasDefault = isDefaultNetwork(nai);
2270 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002271 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002272 // Log default network disconnection before required book-keeping.
2273 // Let rematchAllNetworksAndRequests() below record a new default network event
2274 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2275 // whose timestamps tell how long it takes to recover a default network.
2276 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002277 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002278 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002279 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2280 // by other networks that are already connected. Perhaps that can be done by
2281 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2282 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002283 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002284 mKeepaliveTracker.handleStopAllKeepalives(nai,
2285 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002286 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002287 mNetworkAgentInfos.remove(msg.replyTo);
2288 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002289 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002290 // Remove the NetworkAgent, but don't mark the netId as
2291 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002292 mNetworkForNetId.remove(nai.network.netId);
2293 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002294 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002295 for (int i = 0; i < nai.networkRequests.size(); i++) {
2296 NetworkRequest request = nai.networkRequests.valueAt(i);
2297 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2298 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2299 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002300 sendUpdatedScoreToFactories(request, 0);
2301 }
2302 }
2303 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2304 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002305 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002306 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002307 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002308 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002309 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002310 if (nai.created) {
2311 // Tell netd to clean up the configuration for this network
2312 // (routing rules, DNS, etc).
2313 // This may be slow as it requires a lot of netd shelling out to ip and
2314 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2315 // after we've rematched networks with requests which should make a potential
2316 // fallback network the default or requested a new network from the
2317 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2318 // long time.
2319 try {
2320 mNetd.removeNetwork(nai.network.netId);
2321 } catch (Exception e) {
2322 loge("Exception removing network: " + e);
2323 }
2324 }
2325 synchronized (mNetworkForNetId) {
2326 mNetIdInUse.delete(nai.network.netId);
2327 }
2328 } else {
2329 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2330 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002331 }
2332 }
2333
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002334 // If this method proves to be too slow then we can maintain a separate
2335 // pendingIntent => NetworkRequestInfo map.
2336 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2337 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2338 Intent intent = pendingIntent.getIntent();
2339 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2340 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2341 if (existingPendingIntent != null &&
2342 existingPendingIntent.getIntent().filterEquals(intent)) {
2343 return entry.getValue();
2344 }
2345 }
2346 return null;
2347 }
2348
2349 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2350 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2351
2352 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2353 if (existingRequest != null) { // remove the existing request.
2354 if (DBG) log("Replacing " + existingRequest.request + " with "
2355 + nri.request + " because their intents matched.");
2356 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2357 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002358 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002359 }
2360
Erik Klineda4bfa82015-04-30 12:58:40 +09002361 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002362 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002363 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002364 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002365 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002366 if (nri.request.networkCapabilities.hasSignalStrength() &&
2367 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2368 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002369 }
2370 }
2371 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002372 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002373 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002374 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002375 }
2376 }
2377
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002378 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2379 int callingUid) {
2380 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2381 if (nri != null) {
2382 handleReleaseNetworkRequest(nri.request, callingUid);
2383 }
2384 }
2385
Paul Jensen99364842014-12-09 11:43:45 -05002386 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002387 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2388 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002389 private boolean unneeded(NetworkAgentInfo nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002390 if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002391 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2392 // If this Network is already the highest scoring Network for a request, or if
2393 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002394 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002395 (nai.networkRequests.get(nri.request.requestId) != null ||
2396 // Note that this catches two important cases:
2397 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2398 // is currently satisfying the request. This is desirable when
2399 // cellular ends up validating but WiFi does not.
2400 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002401 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002402 // WiFi ends up validating and out scoring cellular.
2403 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2404 nai.getCurrentScoreAsValidated())) {
2405 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002406 }
2407 }
Paul Jensene0988542015-06-25 15:30:08 -04002408 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002409 }
2410
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002411 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2412 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002413 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002414 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002415 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2416 return;
2417 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002418 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002419 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002420 mNetworkRequests.remove(request);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002421 synchronized (mUidToNetworkRequestCount) {
2422 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2423 if (requests < 1) {
2424 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2425 nri.mUid);
2426 } else if (requests == 1) {
2427 mUidToNetworkRequestCount.removeAt(
2428 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2429 } else {
2430 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2431 }
2432 }
Erik Kline7523eb32015-07-09 18:24:03 +09002433 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002434 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002435 // Find all networks that are satisfying this request and remove the request
2436 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002437 // TODO - it's my understanding that for a request there is only a single
2438 // network satisfying it, so this loop is wasteful
2439 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002440 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2441 if (nai.networkRequests.get(nri.request.requestId) != null) {
2442 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002443 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002444 log(" Removing from current network " + nai.name() +
2445 ", leaving " + nai.networkRequests.size() +
2446 " requests.");
2447 }
Paul Jensen99364842014-12-09 11:43:45 -05002448 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002449 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002450 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002451 } else {
2452 // suspect there should only be one pass through here
2453 // but if any were kept do the check below
2454 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002455 }
2456 }
2457 }
2458
Robert Greenwalt51481852015-01-08 14:43:31 -08002459 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2460 if (nai != null) {
2461 mNetworkForRequestId.remove(nri.request.requestId);
2462 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002463 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002464 // that a network connected to serve it, even though the network was already
2465 // connected. Now that this request has gone away, we might have to pretend
2466 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002467 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002468 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2469 boolean doRemove = true;
2470 if (wasKept) {
2471 // check if any of the remaining requests for this network are for the
2472 // same legacy type - if so, don't remove the nai
2473 for (int i = 0; i < nai.networkRequests.size(); i++) {
2474 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2475 if (otherRequest.legacyType == nri.request.legacyType &&
2476 isRequest(otherRequest)) {
2477 if (DBG) log(" still have other legacy request - leaving");
2478 doRemove = false;
2479 }
2480 }
2481 }
2482
2483 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002484 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002485 }
2486 }
2487
Robert Greenwalta67be032014-05-16 15:49:14 -07002488 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002489 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2490 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002491 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002492 } else {
2493 // listens don't have a singular affectedNetwork. Check all networks to see
2494 // if this listen request applies and remove it.
2495 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2496 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002497 if (nri.request.networkCapabilities.hasSignalStrength() &&
2498 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2499 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002500 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002501 }
2502 }
2503 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2504 }
2505 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002506
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002507 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2508 enforceConnectivityInternalPermission();
2509 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2510 accept ? 1 : 0, always ? 1: 0, network));
2511 }
2512
2513 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2514 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2515 " accept=" + accept + " always=" + always);
2516
2517 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2518 if (nai == null) {
2519 // Nothing to do.
2520 return;
2521 }
2522
2523 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002524 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002525 return;
2526 }
2527
2528 if (!nai.networkMisc.explicitlySelected) {
2529 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2530 }
2531
2532 if (accept != nai.networkMisc.acceptUnvalidated) {
2533 int oldScore = nai.getCurrentScore();
2534 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002535 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002536 sendUpdatedScoreToFactories(nai);
2537 }
2538
2539 if (always) {
2540 nai.asyncChannel.sendMessage(
2541 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2542 }
2543
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002544 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002545 // Tell the NetworkAgent to not automatically reconnect to the network.
2546 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2547 // Teardown the nework.
2548 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002549 }
2550
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002551 }
2552
2553 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002554 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002555 mHandler.sendMessageDelayed(
2556 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2557 PROMPT_UNVALIDATED_DELAY_MS);
2558 }
2559
2560 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002561 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002562 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2563
2564 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2565 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002566 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002567 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002568 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2569 return;
2570 }
2571
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002572 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002573 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002574 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2575 intent.setClassName("com.android.settings",
2576 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002577
2578 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2579 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2580 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002581 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002582 }
2583
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002584 private class InternalHandler extends Handler {
2585 public InternalHandler(Looper looper) {
2586 super(looper);
2587 }
2588
2589 @Override
2590 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002591 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002592 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002593 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002594 String causedBy = null;
2595 synchronized (ConnectivityService.this) {
2596 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2597 mNetTransitionWakeLock.isHeld()) {
2598 mNetTransitionWakeLock.release();
2599 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002600 } else {
2601 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002602 }
2603 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002604 if (VDBG) {
2605 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2606 log("Failed to find a new network - expiring NetTransition Wakelock");
2607 } else {
2608 log("NetTransition Wakelock (" +
2609 (causedBy == null ? "unknown" : causedBy) +
2610 " cleared because we found a replacement network");
2611 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002612 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002613 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002614 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002615 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002616 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002617 break;
2618 }
Jason Monkdecd2952013-10-10 14:02:51 -04002619 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002620 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002621 break;
2622 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002623 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002624 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2625 break;
2626 }
2627 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2628 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002629 break;
2630 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002631 case EVENT_REGISTER_NETWORK_AGENT: {
2632 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2633 break;
2634 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002635 case EVENT_REGISTER_NETWORK_REQUEST:
2636 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002637 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002638 break;
2639 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002640 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2641 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002642 handleRegisterNetworkRequestWithIntent(msg);
2643 break;
2644 }
2645 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2646 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2647 break;
2648 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002649 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002650 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002651 break;
2652 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002653 case EVENT_SET_ACCEPT_UNVALIDATED: {
2654 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2655 break;
2656 }
2657 case EVENT_PROMPT_UNVALIDATED: {
2658 handlePromptUnvalidated((Network) msg.obj);
2659 break;
2660 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002661 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2662 handleMobileDataAlwaysOn();
2663 break;
2664 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002665 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2666 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2667 mKeepaliveTracker.handleStartKeepalive(msg);
2668 break;
2669 }
2670 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2671 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2672 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2673 int slot = msg.arg1;
2674 int reason = msg.arg2;
2675 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2676 break;
2677 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002678 case EVENT_SYSTEM_READY: {
2679 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2680 nai.networkMonitor.systemReady = true;
2681 }
2682 break;
2683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 }
2685 }
2686 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002687
2688 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002689 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002690 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002691 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002692 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002693 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002694 } else {
2695 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2696 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002697 }
2698
2699 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002700 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002701 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002702
2703 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002704 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002705 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002706 } else {
2707 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2708 }
2709 }
2710
2711 // javadoc from interface
2712 public int getLastTetherError(String iface) {
2713 enforceTetherAccessPermission();
2714
2715 if (isTetheringSupported()) {
2716 return mTethering.getLastTetherError(iface);
2717 } else {
2718 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2719 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002720 }
2721
2722 // TODO - proper iface API for selection by property, inspection, etc
2723 public String[] getTetherableUsbRegexs() {
2724 enforceTetherAccessPermission();
2725 if (isTetheringSupported()) {
2726 return mTethering.getTetherableUsbRegexs();
2727 } else {
2728 return new String[0];
2729 }
2730 }
2731
2732 public String[] getTetherableWifiRegexs() {
2733 enforceTetherAccessPermission();
2734 if (isTetheringSupported()) {
2735 return mTethering.getTetherableWifiRegexs();
2736 } else {
2737 return new String[0];
2738 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002739 }
2740
Danica Chang6fdd0c62010-08-11 14:54:43 -07002741 public String[] getTetherableBluetoothRegexs() {
2742 enforceTetherAccessPermission();
2743 if (isTetheringSupported()) {
2744 return mTethering.getTetherableBluetoothRegexs();
2745 } else {
2746 return new String[0];
2747 }
2748 }
2749
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002750 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002751 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002752 if (isTetheringSupported()) {
2753 return mTethering.setUsbTethering(enable);
2754 } else {
2755 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2756 }
2757 }
2758
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002759 // TODO - move iface listing, queries, etc to new module
2760 // javadoc from interface
2761 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002762 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002763 return mTethering.getTetherableIfaces();
2764 }
2765
2766 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002767 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002768 return mTethering.getTetheredIfaces();
2769 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002770
Robert Greenwalt5a735062010-03-02 17:25:02 -08002771 public String[] getTetheringErroredIfaces() {
2772 enforceTetherAccessPermission();
2773 return mTethering.getErroredIfaces();
2774 }
2775
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002776 public String[] getTetheredDhcpRanges() {
2777 enforceConnectivityInternalPermission();
2778 return mTethering.getTetheredDhcpRanges();
2779 }
2780
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002781 // if ro.tether.denied = true we default to no tethering
2782 // gservices could set the secure setting to 1 though to enable it on a build where it
2783 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002784 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002785 public boolean isTetheringSupported() {
2786 enforceTetherAccessPermission();
2787 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002788 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002789 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2790 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002791 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2792 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002793 mTethering.getTetherableWifiRegexs().length != 0 ||
2794 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2795 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002796 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002797
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002798 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002799 public void startTethering(int type, ResultReceiver receiver,
2800 boolean showProvisioningUi) {
2801 ConnectivityManager.enforceTetherChangePermission(mContext);
2802 if (!isTetheringSupported()) {
2803 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2804 return;
2805 }
2806 mTethering.startTethering(type, receiver, showProvisioningUi);
2807 }
2808
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002809 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002810 public void stopTethering(int type) {
2811 ConnectivityManager.enforceTetherChangePermission(mContext);
2812 mTethering.stopTethering(type);
2813 }
2814
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002815 // Called when we lose the default network and have no replacement yet.
2816 // This will automatically be cleared after X seconds or a new default network
2817 // becomes CONNECTED, whichever happens first. The timer is started by the
2818 // first caller and not restarted by subsequent callers.
2819 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002820 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002821 synchronized (this) {
2822 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002823 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002824 mNetTransitionWakeLock.acquire();
2825 mNetTransitionWakeLockCausedBy = forWhom;
2826 }
2827 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002828 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002829 mNetTransitionWakeLockTimeout);
2830 return;
2831 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002832
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002833 // 100 percent is full good, 0 is full bad.
2834 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002835 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002836 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002837 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002838 }
2839
Paul Jensenbfd17b72015-04-07 12:43:13 -04002840 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002841 enforceAccessPermission();
2842 enforceInternetPermission();
2843
Paul Jensenbfd17b72015-04-07 12:43:13 -04002844 NetworkAgentInfo nai;
2845 if (network == null) {
2846 nai = getDefaultNetwork();
2847 } else {
2848 nai = getNetworkAgentInfoForNetwork(network);
2849 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002850 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2851 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2852 return;
2853 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002854 // Revalidate if the app report does not match our current validated state.
2855 if (hasConnectivity == nai.lastValidated) return;
2856 final int uid = Binder.getCallingUid();
2857 if (DBG) {
2858 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2859 ") by " + uid);
2860 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002861 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002862 // Validating a network that has not yet connected could result in a call to
2863 // rematchNetworkAndRequests() which is not meant to work on such networks.
2864 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04002865
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002866 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002867
2868 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2869 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002870 }
2871
Paul Jensencee9b512015-05-06 07:32:40 -04002872 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002873 // this information is already available as a world read/writable jvm property
2874 // so this API change wouldn't have a benifit. It also breaks the passing
2875 // of proxy info to all the JVMs.
2876 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002877 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002878 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002879 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2880 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002881 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002882 }
2883
Paul Jensencee9b512015-05-06 07:32:40 -04002884 public ProxyInfo getProxyForNetwork(Network network) {
2885 if (network == null) return getDefaultProxy();
2886 final ProxyInfo globalProxy = getGlobalProxy();
2887 if (globalProxy != null) return globalProxy;
2888 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2889 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2890 // caller may not have.
2891 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2892 if (nai == null) return null;
2893 synchronized (nai) {
2894 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2895 if (proxyInfo == null) return null;
2896 return new ProxyInfo(proxyInfo);
2897 }
2898 }
2899
Paul Jensene0bef712014-12-10 15:12:18 -05002900 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2901 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2902 // proxy is null then there is no proxy in place).
2903 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2904 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2905 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2906 proxy = null;
2907 }
2908 return proxy;
2909 }
2910
2911 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2912 // better for determining if a new proxy broadcast is necessary:
2913 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2914 // avoid unnecessary broadcasts.
2915 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2916 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2917 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2918 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2919 // all set.
2920 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2921 a = canonicalizeProxyInfo(a);
2922 b = canonicalizeProxyInfo(b);
2923 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2924 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2925 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2926 }
2927
Jason Monk207900c2014-04-25 15:00:09 -04002928 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002929 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002930
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002931 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002932 if (proxyProperties == mGlobalProxy) return;
2933 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2934 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2935
2936 String host = "";
2937 int port = 0;
2938 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002939 String pacFileUrl = "";
2940 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002941 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002942 if (!proxyProperties.isValid()) {
2943 if (DBG)
2944 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2945 return;
2946 }
Jason Monk207900c2014-04-25 15:00:09 -04002947 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002948 host = mGlobalProxy.getHost();
2949 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002950 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002951 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002952 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002953 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002954 } else {
2955 mGlobalProxy = null;
2956 }
2957 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002958 final long token = Binder.clearCallingIdentity();
2959 try {
2960 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2961 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2962 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2963 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002964 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002965 } finally {
2966 Binder.restoreCallingIdentity(token);
2967 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002968
Jason Monkcf0f97a2014-10-02 15:39:38 -04002969 if (mGlobalProxy == null) {
2970 proxyProperties = mDefaultProxy;
2971 }
2972 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002973 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002974 }
2975
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002976 private void loadGlobalProxy() {
2977 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002978 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2979 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2980 String exclList = Settings.Global.getString(res,
2981 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002982 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2983 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002984 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002985 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002986 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002987 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002988 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002989 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002990 if (!proxyProperties.isValid()) {
2991 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2992 return;
2993 }
2994
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002995 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002996 mGlobalProxy = proxyProperties;
2997 }
2998 }
2999 }
3000
Jason Monk207900c2014-04-25 15:00:09 -04003001 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003002 // this information is already available as a world read/writable jvm property
3003 // so this API change wouldn't have a benifit. It also breaks the passing
3004 // of proxy info to all the JVMs.
3005 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003006 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003007 return mGlobalProxy;
3008 }
3009 }
3010
Jason Monk207900c2014-04-25 15:00:09 -04003011 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003012 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003013 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003014 proxy = null;
3015 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003016 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003017 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003018 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003019 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003020 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3021 return;
3022 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003023
3024 // This call could be coming from the PacManager, containing the port of the local
3025 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3026 // global (to get the correct local port), and send a broadcast.
3027 // TODO: Switch PacManager to have its own message to send back rather than
3028 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003029 if ((mGlobalProxy != null) && (proxy != null)
3030 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003031 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3032 mGlobalProxy = proxy;
3033 sendProxyBroadcast(mGlobalProxy);
3034 return;
3035 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003036 mDefaultProxy = proxy;
3037
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003038 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003039 if (!mDefaultProxyDisabled) {
3040 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003041 }
3042 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003043 }
3044
Paul Jensene0bef712014-12-10 15:12:18 -05003045 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3046 // This method gets called when any network changes proxy, but the broadcast only ever contains
3047 // the default proxy (even if it hasn't changed).
3048 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3049 // world where an app might be bound to a non-default network.
3050 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3051 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3052 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3053
3054 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3055 sendProxyBroadcast(getDefaultProxy());
3056 }
3057 }
3058
Robert Greenwalt434203a2010-10-11 16:00:27 -07003059 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003060 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3061 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003062 if (!TextUtils.isEmpty(proxy)) {
3063 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003064 if (data.length == 0) {
3065 return;
3066 }
3067
Robert Greenwalt434203a2010-10-11 16:00:27 -07003068 String proxyHost = data[0];
3069 int proxyPort = 8080;
3070 if (data.length > 1) {
3071 try {
3072 proxyPort = Integer.parseInt(data[1]);
3073 } catch (NumberFormatException e) {
3074 return;
3075 }
3076 }
Jason Monk207900c2014-04-25 15:00:09 -04003077 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003078 setGlobalProxy(p);
3079 }
3080 }
3081
Jason Monk207900c2014-04-25 15:00:09 -04003082 private void sendProxyBroadcast(ProxyInfo proxy) {
3083 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003084 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003085 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003086 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003087 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3088 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003089 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003090 final long ident = Binder.clearCallingIdentity();
3091 try {
3092 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3093 } finally {
3094 Binder.restoreCallingIdentity(ident);
3095 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003096 }
3097
3098 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003099 final private HashMap<Uri, Integer> mUriEventMap;
3100 final private Context mContext;
3101 final private Handler mHandler;
3102
3103 SettingsObserver(Context context, Handler handler) {
3104 super(null);
3105 mUriEventMap = new HashMap<Uri, Integer>();
3106 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003107 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003108 }
3109
Erik Klineda4bfa82015-04-30 12:58:40 +09003110 void observe(Uri uri, int what) {
3111 mUriEventMap.put(uri, what);
3112 final ContentResolver resolver = mContext.getContentResolver();
3113 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003114 }
3115
3116 @Override
3117 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003118 Slog.wtf(TAG, "Should never be reached.");
3119 }
3120
3121 @Override
3122 public void onChange(boolean selfChange, Uri uri) {
3123 final Integer what = mUriEventMap.get(uri);
3124 if (what != null) {
3125 mHandler.obtainMessage(what.intValue()).sendToTarget();
3126 } else {
3127 loge("No matching event to send for URI=" + uri);
3128 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003129 }
3130 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003131
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003132 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003133 Slog.d(TAG, s);
3134 }
3135
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003136 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003137 Slog.e(TAG, s);
3138 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003139
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003140 private static <T> T checkNotNull(T value, String message) {
3141 if (value == null) {
3142 throw new NullPointerException(message);
3143 }
3144 return value;
3145 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003146
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003147 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003148 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003149 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3150 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3151 *
3152 * @param oldPackage Package name of the application which currently controls VPN, which will
3153 * be replaced. If there is no such application, this should should either be
3154 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3155 * @param newPackage Package name of the application which should gain control of VPN, or
3156 * {@code null} to disable.
3157 * @param userId User for whom to prepare the new VPN.
3158 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003159 * @hide
3160 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003161 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003162 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3163 int userId) {
3164 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003165 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003166
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003167 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003168 Vpn vpn = mVpns.get(userId);
3169 if (vpn != null) {
3170 return vpn.prepare(oldPackage, newPackage);
3171 } else {
3172 return false;
3173 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003174 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003175 }
3176
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003177 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003178 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3179 * This method is used by system-privileged apps.
3180 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3181 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3182 *
3183 * @param packageName The package for which authorization state should change.
3184 * @param userId User for whom {@code packageName} is installed.
3185 * @param authorized {@code true} if this app should be able to start a VPN connection without
3186 * explicit user approval, {@code false} if not.
3187 *
Jeff Davidson05542602014-08-11 14:07:27 -07003188 * @hide
3189 */
3190 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003191 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3192 enforceCrossUserPermission(userId);
3193
Jeff Davidson05542602014-08-11 14:07:27 -07003194 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003195 Vpn vpn = mVpns.get(userId);
3196 if (vpn != null) {
3197 vpn.setPackageAuthorization(packageName, authorized);
3198 }
Jeff Davidson05542602014-08-11 14:07:27 -07003199 }
3200 }
3201
3202 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003203 * Configure a TUN interface and return its file descriptor. Parameters
3204 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003205 * and not available in ConnectivityManager. Permissions are checked in
3206 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003207 * @hide
3208 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003209 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003210 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003211 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003212 int user = UserHandle.getUserId(Binder.getCallingUid());
3213 synchronized(mVpns) {
3214 return mVpns.get(user).establish(config);
3215 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003216 }
3217
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003218 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003219 * Start legacy VPN, controlling native daemons as needed. Creates a
3220 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003221 */
3222 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003223 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003224 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003225 final LinkProperties egress = getActiveLinkProperties();
3226 if (egress == null) {
3227 throw new IllegalStateException("Missing active network connection");
3228 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003229 int user = UserHandle.getUserId(Binder.getCallingUid());
3230 synchronized(mVpns) {
3231 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3232 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003233 }
3234
3235 /**
3236 * Return the information of the ongoing legacy VPN. This method is used
3237 * by VpnSettings and not available in ConnectivityManager. Permissions
3238 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003239 */
3240 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003241 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3242 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003243
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003244 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003245 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003246 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003247 }
3248
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003249 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003250 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3251 * and not available in ConnectivityManager.
3252 */
3253 @Override
3254 public VpnInfo[] getAllVpnInfo() {
3255 enforceConnectivityInternalPermission();
3256 if (mLockdownEnabled) {
3257 return new VpnInfo[0];
3258 }
3259
3260 synchronized(mVpns) {
3261 List<VpnInfo> infoList = new ArrayList<>();
3262 for (int i = 0; i < mVpns.size(); i++) {
3263 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3264 if (info != null) {
3265 infoList.add(info);
3266 }
3267 }
3268 return infoList.toArray(new VpnInfo[infoList.size()]);
3269 }
3270 }
3271
3272 /**
3273 * @return VPN information for accounting, or null if we can't retrieve all required
3274 * information, e.g primary underlying iface.
3275 */
3276 @Nullable
3277 private VpnInfo createVpnInfo(Vpn vpn) {
3278 VpnInfo info = vpn.getVpnInfo();
3279 if (info == null) {
3280 return null;
3281 }
3282 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3283 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3284 // the underlyingNetworks list.
3285 if (underlyingNetworks == null) {
3286 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3287 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3288 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3289 }
3290 } else if (underlyingNetworks.length > 0) {
3291 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3292 if (linkProperties != null) {
3293 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3294 }
3295 }
3296 return info.primaryUnderlyingIface == null ? null : info;
3297 }
3298
3299 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003300 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3301 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003302 * Permissions are checked in Vpn class.
3303 * @hide
3304 */
3305 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003306 public VpnConfig getVpnConfig(int userId) {
3307 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003308 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003309 Vpn vpn = mVpns.get(userId);
3310 if (vpn != null) {
3311 return vpn.getVpnConfig();
3312 } else {
3313 return null;
3314 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003315 }
3316 }
3317
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003318 @Override
3319 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003320 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3321 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3322 return false;
3323 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003324
3325 // Tear down existing lockdown if profile was removed
3326 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3327 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003328 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3329 final VpnProfile profile = VpnProfile.decode(
3330 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003331 if (profile == null) {
3332 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3333 setLockdownTracker(null);
3334 return true;
3335 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003336 int user = UserHandle.getUserId(Binder.getCallingUid());
3337 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003338 Vpn vpn = mVpns.get(user);
3339 if (vpn == null) {
3340 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3341 return false;
3342 }
3343 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003344 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003345 } else {
3346 setLockdownTracker(null);
3347 }
3348
3349 return true;
3350 }
3351
3352 /**
3353 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3354 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3355 */
3356 private void setLockdownTracker(LockdownVpnTracker tracker) {
3357 // Shutdown any existing tracker
3358 final LockdownVpnTracker existing = mLockdownTracker;
3359 mLockdownTracker = null;
3360 if (existing != null) {
3361 existing.shutdown();
3362 }
3363
3364 try {
3365 if (tracker != null) {
3366 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003367 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003368 mLockdownTracker = tracker;
3369 mLockdownTracker.init();
3370 } else {
3371 mNetd.setFirewallEnabled(false);
3372 }
3373 } catch (RemoteException e) {
3374 // ignored; NMS lives inside system_server
3375 }
3376 }
3377
3378 private void throwIfLockdownEnabled() {
3379 if (mLockdownEnabled) {
3380 throw new IllegalStateException("Unavailable in lockdown mode");
3381 }
3382 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003383
Robin Lee244ce8e2016-01-05 18:03:46 +00003384 /**
Robin Lee17e61832016-05-09 13:46:28 +01003385 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3386 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003387 *
Robin Lee17e61832016-05-09 13:46:28 +01003388 * @return {@code true} if the service was started, the service was already connected, or there
3389 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003390 */
Robin Lee17e61832016-05-09 13:46:28 +01003391 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003392 synchronized (mVpns) {
3393 Vpn vpn = mVpns.get(userId);
3394 if (vpn == null) {
3395 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3396 // exists already.
3397 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3398 return false;
3399 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003400
Robin Lee812800c2016-05-13 15:38:08 +01003401 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003402 }
3403 }
3404
3405 @Override
Robin Leedc679712016-05-03 13:23:03 +01003406 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003407 enforceConnectivityInternalPermission();
3408 enforceCrossUserPermission(userId);
3409
3410 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3411 if (LockdownVpnTracker.isEnabled()) {
3412 return false;
3413 }
3414
Robin Lee244ce8e2016-01-05 18:03:46 +00003415 synchronized (mVpns) {
3416 Vpn vpn = mVpns.get(userId);
3417 if (vpn == null) {
3418 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3419 return false;
3420 }
Robin Lee17e61832016-05-09 13:46:28 +01003421 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003422 return false;
3423 }
Robin Lee17e61832016-05-09 13:46:28 +01003424 if (!startAlwaysOnVpn(userId)) {
3425 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003426 return false;
3427 }
Robin Lee17e61832016-05-09 13:46:28 +01003428
Robin Lee812800c2016-05-13 15:38:08 +01003429 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003430 }
3431 return true;
3432 }
3433
3434 @Override
3435 public String getAlwaysOnVpnPackage(int userId) {
3436 enforceConnectivityInternalPermission();
3437 enforceCrossUserPermission(userId);
3438
3439 synchronized (mVpns) {
3440 Vpn vpn = mVpns.get(userId);
3441 if (vpn == null) {
3442 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3443 return null;
3444 }
3445 return vpn.getAlwaysOnPackage();
3446 }
3447 }
3448
Wink Savilleab9321d2013-06-29 21:10:57 -07003449 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003450 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003451 // TODO: Remove? Any reason to trigger a provisioning check?
3452 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003453 }
3454
3455 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003456 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003457
Paul Jensen89e0f092014-09-15 15:59:36 -04003458 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003459 Intent intent = new Intent(action);
3460 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003461 // Concatenate the range of types onto the range of NetIDs.
3462 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003463 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003464 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003465 }
3466
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003467 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003468 * Show or hide network provisioning notifications.
3469 *
3470 * We use notifications for two purposes: to notify that a network requires sign in
3471 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3472 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3473 * particular network we can display the notification type that was most recently requested.
3474 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3475 * might first display NO_INTERNET, and then when the captive portal check completes, display
3476 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003477 *
3478 * @param id an identifier that uniquely identifies this notification. This must match
3479 * between show and hide calls. We use the NetID value but for legacy callers
3480 * we concatenate the range of types with the range of NetIDs.
3481 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003482 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003483 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3484 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003485 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003486 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3487 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003488 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003489 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003490
3491 Resources r = Resources.getSystem();
3492 NotificationManager notificationManager = (NotificationManager) mContext
3493 .getSystemService(Context.NOTIFICATION_SERVICE);
3494
3495 if (visible) {
3496 CharSequence title;
3497 CharSequence details;
3498 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003499 if (notifyType == NotificationType.NO_INTERNET &&
3500 networkType == ConnectivityManager.TYPE_WIFI) {
3501 title = r.getString(R.string.wifi_no_internet, 0);
3502 details = r.getString(R.string.wifi_no_internet_detailed);
3503 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3504 } else if (notifyType == NotificationType.SIGN_IN) {
3505 switch (networkType) {
3506 case ConnectivityManager.TYPE_WIFI:
3507 title = r.getString(R.string.wifi_available_sign_in, 0);
3508 details = r.getString(R.string.network_available_sign_in_detailed,
3509 extraInfo);
3510 icon = R.drawable.stat_notify_wifi_in_range;
3511 break;
3512 case ConnectivityManager.TYPE_MOBILE:
3513 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3514 title = r.getString(R.string.network_available_sign_in, 0);
3515 // TODO: Change this to pull from NetworkInfo once a printable
3516 // name has been added to it
3517 details = mTelephonyManager.getNetworkOperatorName();
3518 icon = R.drawable.stat_notify_rssi_in_range;
3519 break;
3520 default:
3521 title = r.getString(R.string.network_available_sign_in, 0);
3522 details = r.getString(R.string.network_available_sign_in_detailed,
3523 extraInfo);
3524 icon = R.drawable.stat_notify_rssi_in_range;
3525 break;
3526 }
3527 } else {
3528 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3529 + getNetworkTypeName(networkType));
3530 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003531 }
3532
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003533 Notification notification = new Notification.Builder(mContext)
3534 .setWhen(0)
3535 .setSmallIcon(icon)
3536 .setAutoCancel(true)
3537 .setTicker(title)
3538 .setColor(mContext.getColor(
3539 com.android.internal.R.color.system_notification_accent_color))
3540 .setContentTitle(title)
3541 .setContentText(details)
3542 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003543 .setLocalOnly(true)
3544 .setPriority(highPriority ?
3545 Notification.PRIORITY_HIGH :
3546 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003547 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003548 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003549 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003550
Wink Saville948282b2013-08-29 08:55:16 -07003551 try {
Paul Jensenf8e903f2016-06-13 09:39:28 -04003552 notificationManager.notifyAsUser(NOTIFICATION_ID, id, notification, UserHandle.ALL);
Wink Saville948282b2013-08-29 08:55:16 -07003553 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003554 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003555 npe.printStackTrace();
3556 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003557 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003558 try {
Paul Jensenf8e903f2016-06-13 09:39:28 -04003559 notificationManager.cancelAsUser(NOTIFICATION_ID, id, UserHandle.ALL);
Wink Saville948282b2013-08-29 08:55:16 -07003560 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003561 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003562 npe.printStackTrace();
3563 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003564 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003565 }
3566
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003567 /** Location to an updatable file listing carrier provisioning urls.
3568 * An example:
3569 *
3570 * <?xml version="1.0" encoding="utf-8"?>
3571 * <provisioningUrls>
3572 * <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 -07003573 * </provisioningUrls>
3574 */
3575 private static final String PROVISIONING_URL_PATH =
3576 "/data/misc/radio/provisioning_urls.xml";
3577 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003578
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003579 /** XML tag for root element. */
3580 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3581 /** XML tag for individual url */
3582 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003583 /** XML attribute for mcc */
3584 private static final String ATTR_MCC = "mcc";
3585 /** XML attribute for mnc */
3586 private static final String ATTR_MNC = "mnc";
3587
Paul Jensen434dde82015-06-11 09:43:30 -04003588 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003589 FileReader fileReader = null;
3590 XmlPullParser parser = null;
3591 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003592
3593 try {
3594 fileReader = new FileReader(mProvisioningUrlFile);
3595 parser = Xml.newPullParser();
3596 parser.setInput(fileReader);
3597 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3598
3599 while (true) {
3600 XmlUtils.nextElement(parser);
3601
3602 String element = parser.getName();
3603 if (element == null) break;
3604
Paul Jensen434dde82015-06-11 09:43:30 -04003605 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003606 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3607 try {
3608 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3609 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3610 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3611 parser.next();
3612 if (parser.getEventType() == XmlPullParser.TEXT) {
3613 return parser.getText();
3614 }
3615 }
3616 }
3617 } catch (NumberFormatException e) {
3618 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3619 }
3620 }
3621 }
3622 return null;
3623 } catch (FileNotFoundException e) {
3624 loge("Carrier Provisioning Urls file not found");
3625 } catch (XmlPullParserException e) {
3626 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3627 } catch (IOException e) {
3628 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3629 } finally {
3630 if (fileReader != null) {
3631 try {
3632 fileReader.close();
3633 } catch (IOException e) {}
3634 }
3635 }
3636 return null;
3637 }
3638
Wink Saville42d4f082013-07-20 20:31:59 -07003639 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003640 public String getMobileProvisioningUrl() {
3641 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003642 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003643 if (TextUtils.isEmpty(url)) {
3644 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003645 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003646 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003647 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003648 }
Wink Saville8cf35602013-07-10 23:00:07 -07003649 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003650 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003651 String phoneNumber = mTelephonyManager.getLine1Number();
3652 if (TextUtils.isEmpty(phoneNumber)) {
3653 phoneNumber = "0000000000";
3654 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003655 url = String.format(url,
3656 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3657 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003658 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003659 }
3660
Wink Savilleab9321d2013-06-29 21:10:57 -07003661 return url;
3662 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003663
Wink Saville948282b2013-08-29 08:55:16 -07003664 @Override
3665 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003666 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003667 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003668 final long ident = Binder.clearCallingIdentity();
3669 try {
3670 setProvNotificationVisible(visible, networkType, action);
3671 } finally {
3672 Binder.restoreCallingIdentity(ident);
3673 }
Wink Saville948282b2013-08-29 08:55:16 -07003674 }
Wink Saville7788c612013-08-29 14:57:08 -07003675
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003676 @Override
3677 public void setAirplaneMode(boolean enable) {
3678 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003679 final long ident = Binder.clearCallingIdentity();
3680 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003681 final ContentResolver cr = mContext.getContentResolver();
3682 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3683 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3684 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003685 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003686 } finally {
3687 Binder.restoreCallingIdentity(ident);
3688 }
3689 }
3690
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003691 private void onUserStart(int userId) {
3692 synchronized(mVpns) {
3693 Vpn userVpn = mVpns.get(userId);
3694 if (userVpn != null) {
3695 loge("Starting user already has a VPN");
3696 return;
3697 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003698 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003699 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003700
3701 final ContentResolver cr = mContext.getContentResolver();
3702 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3703 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3704 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3705 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3706 if (alwaysOnPackage != null) {
3707 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3708 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003709 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003710 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3711 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003712 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003713 }
3714
3715 private void onUserStop(int userId) {
3716 synchronized(mVpns) {
3717 Vpn userVpn = mVpns.get(userId);
3718 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003719 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003720 return;
3721 }
Robin Lee17e61832016-05-09 13:46:28 +01003722 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003723 mVpns.delete(userId);
3724 }
3725 }
3726
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003727 private void onUserAdded(int userId) {
3728 synchronized(mVpns) {
3729 final int vpnsSize = mVpns.size();
3730 for (int i = 0; i < vpnsSize; i++) {
3731 Vpn vpn = mVpns.valueAt(i);
3732 vpn.onUserAdded(userId);
3733 }
3734 }
3735 }
3736
3737 private void onUserRemoved(int userId) {
3738 synchronized(mVpns) {
3739 final int vpnsSize = mVpns.size();
3740 for (int i = 0; i < vpnsSize; i++) {
3741 Vpn vpn = mVpns.valueAt(i);
3742 vpn.onUserRemoved(userId);
3743 }
3744 }
3745 }
3746
Robin Lee89e7a692016-02-29 14:38:17 +00003747 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003748 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3749 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3750 updateLockdownVpn();
3751 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003752 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003753 }
3754 }
3755
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003756 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3757 @Override
3758 public void onReceive(Context context, Intent intent) {
3759 final String action = intent.getAction();
3760 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3761 if (userId == UserHandle.USER_NULL) return;
3762
Robin Lee323f29d2016-05-04 16:38:06 +01003763 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003764 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003765 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003766 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003767 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3768 onUserAdded(userId);
3769 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3770 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003771 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3772 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003773 }
3774 }
3775 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003776
Robert Greenwalta67be032014-05-16 15:49:14 -07003777 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3778 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003779 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3780 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003781
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003782 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3783 // Map from UID to number of NetworkRequests that UID has filed.
3784 @GuardedBy("mUidToNetworkRequestCount")
3785 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3786
Robert Greenwalta67be032014-05-16 15:49:14 -07003787 private static class NetworkFactoryInfo {
3788 public final String name;
3789 public final Messenger messenger;
3790 public final AsyncChannel asyncChannel;
3791
3792 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3793 this.name = name;
3794 this.messenger = messenger;
3795 this.asyncChannel = asyncChannel;
3796 }
3797 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003798
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003799 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003800 * A NetworkRequest as registered by an application can be one of three
3801 * types:
3802 *
3803 * - "listen", for which the framework will issue callbacks about any
3804 * and all networks that match the specified NetworkCapabilities,
3805 *
3806 * - "request", capable of causing a specific network to be created
3807 * first (e.g. a telephony DUN request), the framework will issue
3808 * callbacks about the single, highest scoring current network
3809 * (if any) that matches the specified NetworkCapabilities, or
3810 *
3811 * - "track the default network", a hybrid of the two designed such
3812 * that the framework will issue callbacks for the single, highest
3813 * scoring current network (if any) that matches the capabilities of
3814 * the default Internet request (mDefaultRequest), but which cannot
3815 * cause the framework to either create or retain the existence of
3816 * any specific network.
3817 *
3818 */
3819 private static enum NetworkRequestType {
3820 LISTEN,
3821 TRACK_DEFAULT,
3822 REQUEST
3823 };
3824
3825 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003826 * Tracks info about the requester.
3827 * Also used to notice when the calling process dies so we can self-expire
3828 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003829 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003830 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003831 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003832 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003833 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003834 final int mPid;
3835 final int mUid;
3836 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003837 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003838
Erik Kline371c7b72016-03-22 17:04:20 +09003839 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003840 request = r;
3841 mPendingIntent = pi;
3842 messenger = null;
3843 mBinder = null;
3844 mPid = getCallingPid();
3845 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003846 mType = type;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003847 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003848 }
3849
Erik Kline371c7b72016-03-22 17:04:20 +09003850 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003851 super();
3852 messenger = m;
3853 request = r;
3854 mBinder = binder;
3855 mPid = getCallingPid();
3856 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003857 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003858 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003859 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003860
3861 try {
3862 mBinder.linkToDeath(this, 0);
3863 } catch (RemoteException e) {
3864 binderDied();
3865 }
3866 }
3867
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003868 private void enforceRequestCountLimit() {
3869 synchronized (mUidToNetworkRequestCount) {
3870 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3871 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3872 throw new IllegalArgumentException("Too many NetworkRequests filed");
3873 }
3874 mUidToNetworkRequestCount.put(mUid, networkRequests);
3875 }
3876 }
3877
Erik Kline371c7b72016-03-22 17:04:20 +09003878 private String typeString() {
3879 switch (mType) {
3880 case LISTEN: return "Listen";
3881 case REQUEST: return "Request";
3882 case TRACK_DEFAULT: return "Track default";
3883 default:
3884 return "unknown type";
3885 }
3886 }
3887
Robert Greenwalt9258c642014-03-26 16:47:06 -07003888 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003889 if (mBinder != null) {
3890 mBinder.unlinkToDeath(this, 0);
3891 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003892 }
3893
3894 public void binderDied() {
3895 log("ConnectivityService NetworkRequestInfo binderDied(" +
3896 request + ", " + mBinder + ")");
3897 releaseNetworkRequest(request);
3898 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003899
Erik Kline371c7b72016-03-22 17:04:20 +09003900 /**
3901 * Returns true iff. the contained NetworkRequest is one that:
3902 *
3903 * - should be associated with at most one satisfying network
3904 * at a time;
3905 *
3906 * - should cause a network to be kept up if it is the only network
3907 * which can satisfy the NetworkReqeust.
3908 *
3909 * For full detail of how isRequest() is used for pairing Networks with
3910 * NetworkRequests read rematchNetworkAndRequests().
3911 *
3912 * TODO: Rename to something more properly descriptive.
3913 */
3914 public boolean isRequest() {
3915 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3916 (mType == NetworkRequestType.REQUEST);
3917 }
3918
Robert Greenwalta67be032014-05-16 15:49:14 -07003919 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003920 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003921 " from uid/pid:" + mUid + "/" + mPid +
3922 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003923 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003924 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003925 }
3926
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003927 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3928 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3929 if (badCapability != null) {
3930 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003931 }
3932 }
3933
Erik Kline9d598e12015-07-13 16:37:51 +09003934 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003935 final SortedSet<Integer> thresholds = new TreeSet();
3936 synchronized (nai) {
3937 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3938 if (nri.request.networkCapabilities.hasSignalStrength() &&
3939 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3940 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3941 }
3942 }
3943 }
Erik Kline9d598e12015-07-13 16:37:51 +09003944 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003945 }
3946
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003947 private void updateSignalStrengthThresholds(
3948 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3949 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003950 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003951 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3952
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003953 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003954 String detail;
3955 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3956 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3957 } else {
3958 detail = reason;
3959 }
3960 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3961 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3962 }
3963
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003964 nai.asyncChannel.sendMessage(
3965 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003966 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003967 }
3968
Robert Greenwalt9258c642014-03-26 16:47:06 -07003969 @Override
3970 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003971 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003972 final NetworkRequestType type = (networkCapabilities == null)
3973 ? NetworkRequestType.TRACK_DEFAULT
3974 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003975 // If the requested networkCapabilities is null, take them instead from
3976 // the default network request. This allows callers to keep track of
3977 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09003978 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003979 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3980 enforceAccessPermission();
3981 } else {
3982 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3983 enforceNetworkRequestPermissions(networkCapabilities);
3984 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003985 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003986 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003987
Robert Greenwalt6078b502014-06-11 16:05:07 -07003988 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003989 throw new IllegalArgumentException("Bad timeout specified");
3990 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003991
Etan Cohenddb9ef02015-11-18 10:56:15 -08003992 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3993 .equals(networkCapabilities.getNetworkSpecifier())) {
3994 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3995 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3996 }
3997
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003998 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3999 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09004000 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09004001 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004002
4003 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004004 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004005 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004006 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004007 }
4008 return networkRequest;
4009 }
4010
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004011 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004012 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004013 enforceConnectivityInternalPermission();
4014 } else {
4015 enforceChangePermission();
4016 }
4017 }
4018
fenglub15e72b2015-03-20 11:29:56 -07004019 @Override
fengludb571472015-04-21 17:12:05 -07004020 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004021 enforceAccessPermission();
4022 NetworkAgentInfo nai = null;
4023 if (network == null) {
4024 return false;
4025 }
4026 synchronized (mNetworkForNetId) {
4027 nai = mNetworkForNetId.get(network.netId);
4028 }
4029 if (nai != null) {
4030 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4031 return true;
4032 }
4033 return false;
4034 }
4035
Felipe Lemeee27cab2016-06-20 16:36:29 -07004036 private boolean isSystem(int uid) {
4037 return uid < Process.FIRST_APPLICATION_UID;
4038 }
fenglub15e72b2015-03-20 11:29:56 -07004039
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004040 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004041 final int uid = Binder.getCallingUid();
4042 if (isSystem(uid)) {
4043 return;
4044 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004045 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004046 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004047 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004048 synchronized(mRulesLock) {
4049 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4050 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004051 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4052 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004053 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004054 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004055 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004056 }
4057 }
4058 }
4059
Robert Greenwalt9258c642014-03-26 16:47:06 -07004060 @Override
4061 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4062 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004063 checkNotNull(operation, "PendingIntent cannot be null.");
4064 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4065 enforceNetworkRequestPermissions(networkCapabilities);
4066 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004067 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004068
4069 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
4070 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004071 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004072 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09004073 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004074 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4075 nri));
4076 return networkRequest;
4077 }
4078
Jeremy Joslin79294842014-12-03 17:15:28 -08004079 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4080 mHandler.sendMessageDelayed(
4081 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4082 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4083 }
4084
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004085 @Override
4086 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004087 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004088 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4089 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004090 }
4091
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004092 // In order to implement the compatibility measure for pre-M apps that call
4093 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4094 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4095 // This ensures it has permission to do so.
4096 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4097 if (nc == null) {
4098 return false;
4099 }
4100 int[] transportTypes = nc.getTransportTypes();
4101 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4102 return false;
4103 }
4104 try {
4105 mContext.enforceCallingOrSelfPermission(
4106 android.Manifest.permission.ACCESS_WIFI_STATE,
4107 "ConnectivityService");
4108 } catch (SecurityException e) {
4109 return false;
4110 }
4111 return true;
4112 }
4113
Robert Greenwalt9258c642014-03-26 16:47:06 -07004114 @Override
4115 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4116 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004117 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4118 enforceAccessPermission();
4119 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004120
Erik Kline7523eb32015-07-09 18:24:03 +09004121 NetworkRequest networkRequest = new NetworkRequest(
4122 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004123 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09004124 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004125 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004126
4127 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4128 return networkRequest;
4129 }
4130
4131 @Override
4132 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4133 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004134 checkNotNull(operation, "PendingIntent cannot be null.");
4135 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4136 enforceAccessPermission();
4137 }
4138
Erik Kline7523eb32015-07-09 18:24:03 +09004139 NetworkRequest networkRequest = new NetworkRequest(
4140 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004141 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004142 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004143 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004144
4145 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004146 }
4147
4148 @Override
4149 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004150 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4151 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004152 }
4153
4154 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004155 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004156 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004157 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4158 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004159 }
4160
Robert Greenwalta67be032014-05-16 15:49:14 -07004161 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004162 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004163 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4164 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4165 }
4166
4167 @Override
4168 public void unregisterNetworkFactory(Messenger messenger) {
4169 enforceConnectivityInternalPermission();
4170 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4171 }
4172
4173 private void handleUnregisterNetworkFactory(Messenger messenger) {
4174 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4175 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004176 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004177 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004178 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004179 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004180 }
4181
Robert Greenwalt7b816022014-04-18 15:25:25 -07004182 /**
4183 * NetworkAgentInfo supporting a request by requestId.
4184 * These have already been vetted (their Capabilities satisfy the request)
4185 * and the are the highest scored network available.
4186 * the are keyed off the Requests requestId.
4187 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004188 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004189 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4190 new SparseArray<NetworkAgentInfo>();
4191
Paul Jensen31a94f42015-02-13 14:18:39 -05004192 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4193 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4195 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004196 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4197 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4198 // there may not be a strict 1:1 correlation between the two.
4199 @GuardedBy("mNetworkForNetId")
4200 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004201
Robert Greenwalt7b816022014-04-18 15:25:25 -07004202 // NetworkAgentInfo keyed off its connecting messenger
4203 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004204 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004205 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4206 new HashMap<Messenger, NetworkAgentInfo>();
4207
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004208 @GuardedBy("mBlockedAppUids")
4209 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4210
Paul Jensen2c311d62014-11-17 12:34:51 -05004211 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004212 private final NetworkRequest mDefaultRequest;
4213
Erik Klineda4bfa82015-04-30 12:58:40 +09004214 // Request used to optionally keep mobile data active even when higher
4215 // priority networks like Wi-Fi are active.
4216 private final NetworkRequest mDefaultMobileDataRequest;
4217
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004218 private NetworkAgentInfo getDefaultNetwork() {
4219 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4220 }
4221
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004222 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004223 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004224 }
4225
Paul Jensen31a94f42015-02-13 14:18:39 -05004226 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004227 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004228 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004229 enforceConnectivityInternalPermission();
4230
Paul Jensen2c311d62014-11-17 12:34:51 -05004231 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4232 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004233 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004234 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4235 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004236 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004237 synchronized (this) {
4238 nai.networkMonitor.systemReady = mSystemReady;
4239 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004240 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4241 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004242 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004243 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004244 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004245 }
4246
4247 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4248 if (VDBG) log("Got NetworkAgent Messenger");
4249 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004250 synchronized (mNetworkForNetId) {
4251 mNetworkForNetId.put(na.network.netId, na);
4252 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004253 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4254 NetworkInfo networkInfo = na.networkInfo;
4255 na.networkInfo = null;
4256 updateNetworkInfo(na, networkInfo);
4257 }
4258
4259 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4260 LinkProperties newLp = networkAgent.linkProperties;
4261 int netId = networkAgent.network.netId;
4262
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004263 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4264 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004265 if (networkAgent.clatd != null) {
4266 networkAgent.clatd.fixupLinkProperties(oldLp);
4267 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004268
Paul Jensen992f2522014-04-28 10:33:11 -04004269 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004270 updateMtu(newLp, oldLp);
4271 // TODO - figure out what to do for clat
4272// for (LinkProperties lp : newLp.getStackedLinks()) {
4273// updateMtu(lp, null);
4274// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004275 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004276
Erik Kline94887872016-04-05 13:30:49 +09004277 updateRoutes(newLp, oldLp, netId);
4278 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004279
Paul Jensen3b759822014-05-13 11:44:01 -04004280 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004281 if (isDefaultNetwork(networkAgent)) {
4282 handleApplyDefaultProxy(newLp.getHttpProxy());
4283 } else {
4284 updateProxy(newLp, oldLp, networkAgent);
4285 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004286 // TODO - move this check to cover the whole function
4287 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004288 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004289 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4290 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004291
4292 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004293 }
4294
Lorenzo Colitti95439462014-10-09 13:44:48 +09004295 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4296 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4297 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004298
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004299 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004300 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4301 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004302 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004303 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004304 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004305 }
Paul Jensen992f2522014-04-28 10:33:11 -04004306
4307 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4308 CompareResult<String> interfaceDiff = new CompareResult<String>();
4309 if (oldLp != null) {
4310 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4311 } else if (newLp != null) {
4312 interfaceDiff.added = newLp.getAllInterfaceNames();
4313 }
4314 for (String iface : interfaceDiff.added) {
4315 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004316 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004317 mNetd.addInterfaceToNetwork(iface, netId);
4318 } catch (Exception e) {
4319 loge("Exception adding interface: " + e);
4320 }
4321 }
4322 for (String iface : interfaceDiff.removed) {
4323 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004324 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004325 mNetd.removeInterfaceFromNetwork(iface, netId);
4326 } catch (Exception e) {
4327 loge("Exception removing interface: " + e);
4328 }
4329 }
4330 }
4331
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004332 /**
4333 * Have netd update routes from oldLp to newLp.
4334 * @return true if routes changed between oldLp and newLp
4335 */
4336 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004337 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4338 if (oldLp != null) {
4339 routeDiff = oldLp.compareAllRoutes(newLp);
4340 } else if (newLp != null) {
4341 routeDiff.added = newLp.getAllRoutes();
4342 }
4343
4344 // add routes before removing old in case it helps with continuous connectivity
4345
4346 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4347 for (RouteInfo route : routeDiff.added) {
4348 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004349 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004350 try {
4351 mNetd.addRoute(netId, route);
4352 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004353 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4354 loge("Exception in addRoute for non-gateway: " + e);
4355 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004356 }
4357 }
4358 for (RouteInfo route : routeDiff.added) {
4359 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004360 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004361 try {
4362 mNetd.addRoute(netId, route);
4363 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004364 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4365 loge("Exception in addRoute for gateway: " + e);
4366 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004367 }
4368 }
4369
4370 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004371 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004372 try {
4373 mNetd.removeRoute(netId, route);
4374 } catch (Exception e) {
4375 loge("Exception in removeRoute: " + e);
4376 }
4377 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004378 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004379 }
Erik Kline41368502015-06-17 13:19:54 +09004380
Erik Kline94887872016-04-05 13:30:49 +09004381 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4382 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4383 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004384 }
Erik Kline94887872016-04-05 13:30:49 +09004385
4386 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004387 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004388 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004389 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004390 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4391 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004392 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004393 }
4394 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4395 if (defaultNai != null && defaultNai.network.netId == netId) {
4396 setDefaultDnsSystemProperties(dnses);
4397 }
4398 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004399 }
4400
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004401 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4402 int last = 0;
4403 for (InetAddress dns : dnses) {
4404 ++last;
4405 String key = "net.dns" + last;
4406 String value = dns.getHostAddress();
4407 SystemProperties.set(key, value);
4408 }
4409 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4410 String key = "net.dns" + i;
4411 SystemProperties.set(key, "");
4412 }
4413 mNumDnsEntries = last;
4414 }
4415
Paul Jensen3d194ea2015-06-16 14:27:36 -04004416 /**
4417 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4418 * augmented with any stateful capabilities implied from {@code networkAgent}
4419 * (e.g., validated status and captive portal status).
4420 *
Paul Jensene0988542015-06-25 15:30:08 -04004421 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004422 * @param networkCapabilities the new network capabilities.
4423 */
Paul Jensene0988542015-06-25 15:30:08 -04004424 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004425 // Don't modify caller's NetworkCapabilities.
4426 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004427 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004428 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4429 } else {
4430 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4431 }
Paul Jensene0988542015-06-25 15:30:08 -04004432 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004433 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4434 } else {
4435 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4436 }
Paul Jensene0988542015-06-25 15:30:08 -04004437 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4438 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004439 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4440 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4441 try {
4442 mNetd.setNetworkPermission(nai.network.netId,
4443 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4444 null : NetworkManagementService.PERMISSION_SYSTEM);
4445 } catch (RemoteException e) {
4446 loge("Exception in setNetworkPermission: " + e);
4447 }
4448 }
Paul Jensene0988542015-06-25 15:30:08 -04004449 synchronized (nai) {
4450 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004451 }
Paul Jensene0988542015-06-25 15:30:08 -04004452 rematchAllNetworksAndRequests(nai, oldScore);
4453 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004454 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004455 }
4456
Paul Jensenc8b9a742014-09-30 15:37:41 -04004457 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4458 for (int i = 0; i < nai.networkRequests.size(); i++) {
4459 NetworkRequest nr = nai.networkRequests.valueAt(i);
4460 // Don't send listening requests to factories. b/17393458
4461 if (!isRequest(nr)) continue;
4462 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4463 }
4464 }
4465
Robert Greenwalt7b816022014-04-18 15:25:25 -07004466 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4467 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004468 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004469 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4470 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004471 }
4472 }
4473
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004474 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4475 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004476 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004477 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004478 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4479 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004480 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004481 sendIntent(nri.mPendingIntent, intent);
4482 }
4483 // else not handled
4484 }
4485
4486 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4487 mPendingIntentWakeLock.acquire();
4488 try {
4489 if (DBG) log("Sending " + pendingIntent);
4490 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4491 } catch (PendingIntent.CanceledException e) {
4492 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4493 mPendingIntentWakeLock.release();
4494 releasePendingNetworkRequest(pendingIntent);
4495 }
4496 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4497 }
4498
4499 @Override
4500 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4501 String resultData, Bundle resultExtras) {
4502 if (DBG) log("Finished sending " + pendingIntent);
4503 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004504 // Release with a delay so the receiving client has an opportunity to put in its
4505 // own request.
4506 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004507 }
4508
Robert Greenwalt9258c642014-03-26 16:47:06 -07004509 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004510 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004511 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004512 Bundle bundle = new Bundle();
4513 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4514 new NetworkRequest(nri.request));
4515 Message msg = Message.obtain();
4516 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4517 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4518 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4519 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004520 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004521 case ConnectivityManager.CALLBACK_LOSING: {
4522 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4523 break;
4524 }
4525 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4526 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4527 new NetworkCapabilities(networkAgent.networkCapabilities));
4528 break;
4529 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004530 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004531 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4532 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004533 break;
4534 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004535 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004536 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004537 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004538 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004539 if (VDBG) {
4540 log("sending notification " + notifyTypeToName(notificationType) +
4541 " for " + nri.request);
4542 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004543 nri.messenger.send(msg);
4544 } catch (RemoteException e) {
4545 // may occur naturally in the race of binder death.
4546 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4547 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004548 }
4549
Paul Jensenc8b9a742014-09-30 15:37:41 -04004550 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4551 for (int i = 0; i < nai.networkRequests.size(); i++) {
4552 NetworkRequest nr = nai.networkRequests.valueAt(i);
4553 // Ignore listening requests.
4554 if (!isRequest(nr)) continue;
4555 loge("Dead network still had at least " + nr);
4556 break;
4557 }
4558 nai.asyncChannel.disconnect();
4559 }
4560
Robert Greenwalt7b816022014-04-18 15:25:25 -07004561 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4562 if (oldNetwork == null) {
4563 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4564 return;
4565 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004566 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4567 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004568 }
4569
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004570 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004571 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004572 setupDataActivityTracking(newNetwork);
4573 try {
4574 mNetd.setDefaultNetId(newNetwork.network.netId);
4575 } catch (Exception e) {
4576 loge("Exception setting default network :" + e);
4577 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004578 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004579 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004580 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004581 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004582 }
4583
Paul Jensen2161a8e2014-09-11 11:00:39 -04004584 // Handles a network appearing or improving its score.
4585 //
4586 // - Evaluates all current NetworkRequests that can be
4587 // satisfied by newNetwork, and reassigns to newNetwork
4588 // any such requests for which newNetwork is the best.
4589 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004590 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004591 // needed. A network is needed if it is the best network for
4592 // one or more NetworkRequests, or if it is a VPN.
4593 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004594 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004595 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004596 //
4597 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4598 // networks that have no chance (i.e. even if validated)
4599 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004600 //
4601 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4602 // it does not remove NetworkRequests that other Networks could better satisfy.
4603 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4604 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4605 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004606 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004607 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004608 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4609 // performed to tear down unvalidated networks that have no chance (i.e. even if
4610 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004611 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004612 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Robin Lee585e2482016-05-01 23:00:00 +01004613 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004614 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004615 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004616 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004617 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004618 // Find and migrate to this Network any NetworkRequests for
4619 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004620 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004621 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004622 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004623 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004624 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4625 final boolean satisfies = newNetwork.satisfies(nri.request);
4626 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004627 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004628 log("Network " + newNetwork.name() + " was already satisfying" +
4629 " request " + nri.request.requestId + ". No change.");
4630 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004631 keep = true;
4632 continue;
4633 }
4634
4635 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004636 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004637 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004638 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004639 // This is not a request, it's a callback listener.
4640 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004641 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004642 continue;
4643 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004644
Robert Greenwalt7b816022014-04-18 15:25:25 -07004645 // next check if it's better than any current network we're using for
4646 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004647 if (VDBG) {
4648 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004649 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4650 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004651 }
4652 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004653 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004654 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004655 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004656 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004657 currentNetwork.networkRequests.remove(nri.request.requestId);
4658 currentNetwork.networkLingered.add(nri.request);
4659 affectedNetworks.add(currentNetwork);
4660 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004661 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004662 }
Paul Jensen573a0352015-01-08 10:49:34 -05004663 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004664 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004665 if (!newNetwork.addRequest(nri.request)) {
4666 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4667 }
4668 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004669 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004670 // Tell NetworkFactories about the new score, so they can stop
4671 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004672 // TODO - this could get expensive if we have alot of requests for this
4673 // network. Think about if there is a way to reduce this. Push
4674 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004675 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004676 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004677 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004678 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004679 }
4680 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004681 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4682 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4683 // mark it as no longer satisfying "nri". Because networks are processed by
4684 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4685 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4686 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4687 // This means this code doesn't have to handle the case where "currentNetwork" no
4688 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4689 if (DBG) {
4690 log("Network " + newNetwork.name() + " stopped satisfying" +
4691 " request " + nri.request.requestId);
4692 }
4693 newNetwork.networkRequests.remove(nri.request.requestId);
4694 if (currentNetwork == newNetwork) {
4695 mNetworkForRequestId.remove(nri.request.requestId);
4696 sendUpdatedScoreToFactories(nri.request, 0);
4697 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004698 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004699 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4700 newNetwork.name() +
4701 " without updating mNetworkForRequestId or factories!");
4702 }
4703 }
4704 // TODO: technically, sending CALLBACK_LOST here is
4705 // incorrect if nri is a request (not a listen) and there
4706 // is a replacement network currently connected that can
4707 // satisfy it. However, the only capability that can both
4708 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4709 // so this code is only incorrect for a network that loses
4710 // the TRUSTED capability, which is a rare case.
4711 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004712 }
4713 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004714 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004715 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004716 if (nai.lingering) {
4717 // Already lingered. Nothing to do. This can only happen if "nai" is in
4718 // "affectedNetworks" twice. The reasoning being that to get added to
4719 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4720 // (i.e. not lingered) so it could have only been lingered by this loop.
4721 // unneeded(nai) will be false and we'll call unlinger() below which would
4722 // be bad, so handle it here.
4723 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004724 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004725 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004726 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004727 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004728 }
4729 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004730 if (isNewDefault) {
4731 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004732 makeDefault(newNetwork);
4733 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4734 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004735 synchronized (ConnectivityService.this) {
4736 // have a new default network, release the transition wakelock in
4737 // a second if it's held. The second pause is to allow apps
4738 // to reconnect over the new network
4739 if (mNetTransitionWakeLock.isHeld()) {
4740 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4741 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4742 mNetTransitionWakeLockSerialNumber, 0),
4743 1000);
4744 }
4745 }
4746 }
4747
4748 // do this after the default net is switched, but
4749 // before LegacyTypeTracker sends legacy broadcasts
4750 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4751
4752 if (isNewDefault) {
4753 // Maintain the illusion: since the legacy API only
4754 // understands one network at a time, we must pretend
4755 // that the current default network disconnected before
4756 // the new one connected.
4757 if (oldDefaultNetwork != null) {
4758 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4759 oldDefaultNetwork, true);
4760 }
4761 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4762 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4763 notifyLockdownVpn(newNetwork);
4764 }
4765
Robert Greenwalt7b816022014-04-18 15:25:25 -07004766 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004767 // Notify battery stats service about this network, both the normal
4768 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004769 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004770 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004771 final IBatteryStats bs = BatteryStatsService.getService();
4772 final int type = newNetwork.networkInfo.getType();
4773
4774 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4775 bs.noteNetworkInterfaceType(baseIface, type);
4776 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4777 final String stackedIface = stacked.getInterfaceName();
4778 bs.noteNetworkInterfaceType(stackedIface, type);
4779 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4780 }
4781 } catch (RemoteException ignored) {
4782 }
4783
Robert Greenwalt152ed372014-12-17 17:19:53 -08004784 // This has to happen after the notifyNetworkCallbacks as that tickles each
4785 // ConnectivityManager instance so that legacy requests correctly bind dns
4786 // requests to this network. The legacy users are listening for this bcast
4787 // and will generally do a dns request so they can ensureRouteToHost and if
4788 // they do that before the callbacks happen they'll use the default network.
4789 //
4790 // TODO: Is there still a race here? We send the broadcast
4791 // after sending the callback, but if the app can receive the
4792 // broadcast before the callback, it might still break.
4793 //
4794 // This *does* introduce a race where if the user uses the new api
4795 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4796 // they may get old info. Reverse this after the old startUsing api is removed.
4797 // This is on top of the multiple intent sequencing referenced in the todo above.
4798 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4799 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4800 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4801 // legacy type tracker filters out repeat adds
4802 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4803 }
4804 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004805
4806 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4807 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4808 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4809 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4810 if (newNetwork.isVPN()) {
4811 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4812 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004813 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004814 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4815 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004816 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004817 if (DBG) log("Reaping " + nai.name());
4818 teardownUnneededNetwork(nai);
4819 }
4820 }
4821 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004822 }
4823
Paul Jensen1c7ba022015-06-16 14:27:36 -04004824 /**
4825 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4826 * being disconnected.
4827 * @param changed If only one Network's score or capabilities have been modified since the last
4828 * time this function was called, pass this Network in this argument, otherwise pass
4829 * null.
4830 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4831 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4832 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4833 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4834 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004835 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004836 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004837 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4838 // to avoid the slowness. It is not simply enough to process just "changed", for
4839 // example in the case where "changed"'s score decreases and another network should begin
4840 // satifying a NetworkRequest that "changed" currently satisfies.
4841
4842 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4843 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4844 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004845 if (changed != null && oldScore < changed.getCurrentScore()) {
4846 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004847 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004848 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4849 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4850 // Rematch higher scoring networks first to prevent requests first matching a lower
4851 // scoring network and then a higher scoring network, which could produce multiple
4852 // callbacks and inadvertently unlinger networks.
4853 Arrays.sort(nais);
4854 for (NetworkAgentInfo nai : nais) {
4855 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004856 // Only reap the last time through the loop. Reaping before all rematching
4857 // is complete could incorrectly teardown a network that hasn't yet been
4858 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004859 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004860 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004861 }
4862 }
4863 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004864
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004865 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004866 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004867 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004868 // For now only update icons for default connection.
4869 // TODO: Update WiFi and cellular icons separately. b/17237507
4870 if (!isDefaultNetwork(nai)) return;
4871
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004872 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004873 // Don't repeat publish.
4874 if (newInetCondition == mDefaultInetConditionPublished) return;
4875
4876 mDefaultInetConditionPublished = newInetCondition;
4877 sendInetConditionBroadcast(nai.networkInfo);
4878 }
4879
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004880 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4881 if (mLockdownTracker != null) {
4882 if (nai != null && nai.isVPN()) {
4883 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4884 } else {
4885 mLockdownTracker.onNetworkInfoChanged();
4886 }
4887 }
4888 }
4889
Robert Greenwalt7b816022014-04-18 15:25:25 -07004890 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4891 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004892 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004893 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004894 synchronized (networkAgent) {
4895 oldInfo = networkAgent.networkInfo;
4896 networkAgent.networkInfo = newInfo;
4897 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004898 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004899
4900 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004901 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4902 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4903 notifyIfacesChangedForNetworkStats();
4904 } else if (VDBG) log("ignoring duplicate network state non-change");
4905 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004906 return;
4907 }
4908 if (DBG) {
4909 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4910 (oldInfo == null ? "null" : oldInfo.getState()) +
4911 " to " + state);
4912 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004913
Robin Lee585e2482016-05-01 23:00:00 +01004914 if (!networkAgent.created
4915 && (state == NetworkInfo.State.CONNECTED
4916 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004917 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004918 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004919 if (networkAgent.isVPN()) {
4920 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004921 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4922 (networkAgent.networkMisc == null ||
4923 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004924 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004925 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4926 networkAgent.networkCapabilities.hasCapability(
4927 NET_CAPABILITY_NOT_RESTRICTED) ?
4928 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004929 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004930 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004931 loge("Error creating network " + networkAgent.network.netId + ": "
4932 + e.getMessage());
4933 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004934 }
Paul Jenseneec75412014-08-04 12:21:19 -04004935 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004936 }
4937
4938 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4939 networkAgent.everConnected = true;
4940
Robert Greenwalt7b816022014-04-18 15:25:25 -07004941 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004942 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004943
Paul Jensenca8f16a2014-05-09 12:47:55 -04004944 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004945 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004946
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004947 if (networkAgent.isVPN()) {
4948 // Temporarily disable the default proxy (not global).
4949 synchronized (mProxyLock) {
4950 if (!mDefaultProxyDisabled) {
4951 mDefaultProxyDisabled = true;
4952 if (mGlobalProxy == null && mDefaultProxy != null) {
4953 sendProxyBroadcast(null);
4954 }
4955 }
4956 }
4957 // TODO: support proxy per network.
4958 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004959
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004960 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4961 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4962 // capabilities, so it only needs to be done once on initial connect, not every time the
4963 // network's capabilities change. Note that we do this before rematching the network,
4964 // so we could decide to tear it down immediately afterwards. That's fine though - on
4965 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4966 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004967 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004968
Paul Jensen2161a8e2014-09-11 11:00:39 -04004969 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004970 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004971
4972 // This has to happen after matching the requests, because callbacks are just requests.
4973 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004974 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004975 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004976 if (networkAgent.isVPN()) {
4977 synchronized (mProxyLock) {
4978 if (mDefaultProxyDisabled) {
4979 mDefaultProxyDisabled = false;
4980 if (mGlobalProxy == null && mDefaultProxy != null) {
4981 sendProxyBroadcast(mDefaultProxy);
4982 }
4983 }
4984 }
4985 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004986 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4987 state == NetworkInfo.State.SUSPENDED) {
4988 // going into or coming out of SUSPEND: rescore and notify
4989 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004990 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004991 }
4992 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4993 ConnectivityManager.CALLBACK_SUSPENDED :
4994 ConnectivityManager.CALLBACK_RESUMED));
4995 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004996 }
4997 }
4998
Robert Greenwaltac96c522014-06-03 16:43:57 -07004999 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005000 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005001 if (score < 0) {
5002 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5003 "). Bumping score to min of 0");
5004 score = 0;
5005 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005006
Paul Jensen2161a8e2014-09-11 11:00:39 -04005007 final int oldScore = nai.getCurrentScore();
5008 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005009
Paul Jensen85cf78e2015-06-25 13:25:07 -04005010 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005011
Paul Jensenc8b9a742014-09-30 15:37:41 -04005012 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005013 }
5014
Robert Greenwalt9258c642014-03-26 16:47:06 -07005015 // notify only this one new request of the current state
5016 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5017 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
5018 // TODO - read state from monitor to decide what to send.
5019// if (nai.networkMonitor.isLingering()) {
5020// notifyType = NetworkCallbacks.LOSING;
5021// } else if (nai.networkMonitor.isEvaluating()) {
5022// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5023// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005024 if (nri.mPendingIntent == null) {
5025 callCallbackForRequest(nri, nai, notifyType);
5026 } else {
5027 sendPendingIntentForRequest(nri, nai, notifyType);
5028 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005029 }
5030
Robert Greenwalt8d482522015-06-24 13:23:42 -07005031 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005032 // The NetworkInfo we actually send out has no bearing on the real
5033 // state of affairs. For example, if the default connection is mobile,
5034 // and a request for HIPRI has just gone away, we need to pretend that
5035 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5036 // the state to DISCONNECTED, even though the network is of type MOBILE
5037 // and is still connected.
5038 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5039 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005040 if (state != DetailedState.DISCONNECTED) {
5041 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005042 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005043 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005044 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005045 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5046 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5047 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5048 if (info.isFailover()) {
5049 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5050 nai.networkInfo.setFailover(false);
5051 }
5052 if (info.getReason() != null) {
5053 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5054 }
5055 if (info.getExtraInfo() != null) {
5056 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5057 }
5058 NetworkAgentInfo newDefaultAgent = null;
5059 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005060 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005061 if (newDefaultAgent != null) {
5062 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5063 newDefaultAgent.networkInfo);
5064 } else {
5065 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5066 }
5067 }
5068 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5069 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005070 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005071 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005072 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005073 }
5074 }
5075 }
5076
Robert Greenwalt7b816022014-04-18 15:25:25 -07005077 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005078 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005079 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005080 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
5081 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5082 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005083 if (nri.mPendingIntent == null) {
5084 callCallbackForRequest(nri, networkAgent, notifyType);
5085 } else {
5086 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5087 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005088 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005089 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005090
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005091 private String notifyTypeToName(int notifyType) {
5092 switch (notifyType) {
5093 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5094 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5095 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5096 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5097 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5098 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5099 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5100 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5101 }
5102 return "UNKNOWN";
5103 }
5104
Jeff Sharkey69736342014-12-08 14:50:12 -08005105 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005106 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5107 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005108 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005109 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005110 try {
5111 mStatsService.forceUpdateIfaces();
5112 } catch (Exception ignored) {
5113 }
5114 }
5115
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005116 @Override
5117 public boolean addVpnAddress(String address, int prefixLength) {
5118 throwIfLockdownEnabled();
5119 int user = UserHandle.getUserId(Binder.getCallingUid());
5120 synchronized (mVpns) {
5121 return mVpns.get(user).addAddress(address, prefixLength);
5122 }
5123 }
5124
5125 @Override
5126 public boolean removeVpnAddress(String address, int prefixLength) {
5127 throwIfLockdownEnabled();
5128 int user = UserHandle.getUserId(Binder.getCallingUid());
5129 synchronized (mVpns) {
5130 return mVpns.get(user).removeAddress(address, prefixLength);
5131 }
5132 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005133
5134 @Override
5135 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5136 throwIfLockdownEnabled();
5137 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005138 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005139 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005140 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005141 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005142 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005143 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005144 }
5145 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005146 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005147
5148 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005149 public String getCaptivePortalServerUrl() {
5150 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5151 }
5152
5153 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005154 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5155 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5156 enforceKeepalivePermission();
5157 mKeepaliveTracker.startNattKeepalive(
5158 getNetworkAgentInfoForNetwork(network),
5159 intervalSeconds, messenger, binder,
5160 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5161 }
5162
5163 @Override
5164 public void stopKeepalive(Network network, int slot) {
5165 mHandler.sendMessage(mHandler.obtainMessage(
5166 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5167 }
5168
5169 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005170 public void factoryReset() {
5171 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005172
5173 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5174 return;
5175 }
5176
Robin Lee3b3dd942015-05-12 18:14:58 +01005177 final int userId = UserHandle.getCallingUserId();
5178
Stuart Scottf1fb3972015-04-02 18:00:02 -07005179 // Turn airplane mode off
5180 setAirplaneMode(false);
5181
Stuart Scotte3e314d2015-04-20 14:07:45 -07005182 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5183 // Untether
5184 for (String tether : getTetheredIfaces()) {
5185 untether(tether);
5186 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005187 }
5188
Stuart Scotte3e314d2015-04-20 14:07:45 -07005189 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005190 // Remove always-on package
5191 synchronized (mVpns) {
5192 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5193 if (alwaysOnPackage != null) {
5194 setAlwaysOnVpnPackage(userId, null, false);
5195 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5196 }
5197 }
5198
Stuart Scotte3e314d2015-04-20 14:07:45 -07005199 // Turn VPN off
5200 VpnConfig vpnConfig = getVpnConfig(userId);
5201 if (vpnConfig != null) {
5202 if (vpnConfig.legacy) {
5203 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5204 } else {
5205 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5206 // in the future without user intervention.
5207 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005208
Victor Changb04a5ea2016-05-30 20:36:30 +01005209 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005210 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005211 }
5212 }
5213 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005214
5215 @VisibleForTesting
5216 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5217 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5218 return new NetworkMonitor(context, handler, nai, defaultRequest);
5219 }
Erik Kline48f12f22016-04-14 17:30:59 +09005220
Hugo Benichi5f16f762016-04-20 12:09:33 +09005221 private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5222 int newNetid = NETID_UNSET;
5223 int prevNetid = NETID_UNSET;
5224 int[] transports = new int[0];
5225 boolean hadIPv4 = false;
5226 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005227
Hugo Benichi5f16f762016-04-20 12:09:33 +09005228 if (newNai != null) {
5229 newNetid = newNai.network.netId;
5230 transports = newNai.networkCapabilities.getTransportTypes();
5231 }
5232 if (prevNai != null) {
5233 prevNetid = prevNai.network.netId;
5234 final LinkProperties lp = prevNai.linkProperties;
5235 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5236 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5237 }
5238
5239 DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
Erik Kline48f12f22016-04-14 17:30:59 +09005240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005241}