blob: 7abb9671f9394c8029b80cf8bd51ae66f093eb96 [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 Benichicfddd682016-05-31 16:28:06 +090079import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090080import android.net.metrics.NetworkEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080082import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070083import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040084import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070086import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070088import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.Looper;
90import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070091import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070092import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070093import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070094import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070095import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080096import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070098import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040099import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700101import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700102import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700103import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700104import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600105import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700106import android.util.LocalLog;
107import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600108import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700109import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800110import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700111import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500112import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700114import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Wink Savilleab9321d2013-06-29 21:10:57 -0700116import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400117import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400118import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700119import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700120import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700122import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800123import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700124import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700125import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700126import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900127import com.android.internal.util.MessageUtils;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700128import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700129import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400130import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900131import com.android.server.connectivity.KeepaliveTracker;
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
Hugo Benichicfddd682016-05-31 16:28:06 +0900458 private final IpConnectivityLog mMetricsLog = new IpConnectivityLog();
459
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700460 /**
461 * Implements support for the legacy "one network per network type" model.
462 *
463 * We used to have a static array of NetworkStateTrackers, one for each
464 * network type, but that doesn't work any more now that we can have,
465 * for example, more that one wifi network. This class stores all the
466 * NetworkAgentInfo objects that support a given type, but the legacy
467 * API will only see the first one.
468 *
469 * It serves two main purposes:
470 *
471 * 1. Provide information about "the network for a given type" (since this
472 * API only supports one).
473 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
474 * the first network for a given type changes, or if the default network
475 * changes.
476 */
477 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900478
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900479 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900480 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900481
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700482 /**
483 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
484 * Each list holds references to all NetworkAgentInfos that are used to
485 * satisfy requests for that network type.
486 *
487 * This array is built out at startup such that an unsupported network
488 * doesn't get an ArrayList instance, making this a tristate:
489 * unsupported, supported but not active and active.
490 *
491 * The actual lists are populated when we scan the network types that
492 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900493 *
494 * Threading model:
495 * - addSupportedType() is only called in the constructor
496 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
497 * They are therefore not thread-safe with respect to each other.
498 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
499 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
500 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700501 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900502 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700503
504 public LegacyTypeTracker() {
505 mTypeLists = (ArrayList<NetworkAgentInfo>[])
506 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
507 }
508
509 public void addSupportedType(int type) {
510 if (mTypeLists[type] != null) {
511 throw new IllegalStateException(
512 "legacy list for type " + type + "already initialized");
513 }
514 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
515 }
516
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700517 public boolean isTypeSupported(int type) {
518 return isNetworkTypeValid(type) && mTypeLists[type] != null;
519 }
520
521 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900522 synchronized (mTypeLists) {
523 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
524 return mTypeLists[type].get(0);
525 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700526 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900527 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700528 }
529
Robert Greenwalt8d482522015-06-24 13:23:42 -0700530 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900531 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900532 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700533 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900534 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900535 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900536 }
537 }
538
539 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700540 public void add(int type, NetworkAgentInfo nai) {
541 if (!isTypeSupported(type)) {
542 return; // Invalid network type.
543 }
544 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
545
546 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
547 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700548 return;
549 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900550 synchronized (mTypeLists) {
551 list.add(nai);
552 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900553
554 // 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 +0900555 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900556 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700557 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
558 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 }
561
Lorenzo Colittia793a672014-07-31 23:20:17 +0900562 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900563 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900564 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
565 if (list == null || list.isEmpty()) {
566 return;
567 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900568 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900569
Hugo Benichi78caa2582016-06-21 09:48:07 +0900570 synchronized (mTypeLists) {
571 if (!list.remove(nai)) {
572 return;
573 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900574 }
575
Robert Greenwalt8d482522015-06-24 13:23:42 -0700576 final DetailedState state = DetailedState.DISCONNECTED;
577
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900578 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700579 maybeLogBroadcast(nai, state, type, wasDefault);
580 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900581 }
582
583 if (!list.isEmpty() && wasFirstNetwork) {
584 if (DBG) log("Other network available for type " + type +
585 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900586 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700587 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
588 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900589 }
590 }
591
592 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900593 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
594 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700595 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900596 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 }
598 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700599
Robert Greenwalt8d482522015-06-24 13:23:42 -0700600 // send out another legacy broadcast - currently only used for suspend/unsuspend
601 // toggle
602 public void update(NetworkAgentInfo nai) {
603 final boolean isDefault = isDefaultNetwork(nai);
604 final DetailedState state = nai.networkInfo.getDetailedState();
605 for (int type = 0; type < mTypeLists.length; type++) {
606 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700607 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900608 final boolean isFirst = contains && (nai == list.get(0));
609 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700610 maybeLogBroadcast(nai, state, type, isDefault);
611 sendLegacyNetworkBroadcast(nai, state, type);
612 }
613 }
614 }
615
Lorenzo Colittia793a672014-07-31 23:20:17 +0900616 private String naiToString(NetworkAgentInfo nai) {
617 String name = (nai != null) ? nai.name() : "null";
618 String state = (nai.networkInfo != null) ?
619 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
620 "???/???";
621 return name + " " + state;
622 }
623
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700624 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900625 pw.println("mLegacyTypeTracker:");
626 pw.increaseIndent();
627 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700628 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900629 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700630 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900631 pw.println();
632 pw.println("Current state:");
633 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900634 synchronized (mTypeLists) {
635 for (int type = 0; type < mTypeLists.length; type++) {
636 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
637 for (NetworkAgentInfo nai : mTypeLists[type]) {
638 pw.println(type + " " + naiToString(nai));
639 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900640 }
641 }
642 pw.decreaseIndent();
643 pw.decreaseIndent();
644 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700645 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700646 }
647 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
648
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900649 @VisibleForTesting
650 protected HandlerThread createHandlerThread() {
651 return new HandlerThread("ConnectivityServiceThread");
652 }
653
Jeff Sharkey899223b2012-08-04 15:24:58 -0700654 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700655 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800656 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800657
Erik Klineda4bfa82015-04-30 12:58:40 +0900658 mDefaultRequest = createInternetRequestForTransport(-1);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900659 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900660 mNetworkRequests.put(mDefaultRequest, defaultNRI);
661 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900662
663 mDefaultMobileDataRequest = createInternetRequestForTransport(
664 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700665
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900666 mHandlerThread = createHandlerThread();
667 mHandlerThread.start();
668 mHandler = new InternalHandler(mHandlerThread.getLooper());
669 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700670
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800671 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800672 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
673 String id = Settings.Secure.getString(context.getContentResolver(),
674 Settings.Secure.ANDROID_ID);
675 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700676 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800677 SystemProperties.set("net.hostname", name);
678 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800679 }
680
Jeremy Joslin79294842014-12-03 17:15:28 -0800681 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
682 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
683
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700684 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700685 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800686 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700687 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700688 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700689 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700690
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700691 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600692 mPolicyManager.setConnectivityListener(mPolicyListener);
693 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700694 } catch (RemoteException e) {
695 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700696 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700697 }
698
699 final PowerManager powerManager = (PowerManager) context.getSystemService(
700 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700701 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
702 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
703 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800704 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700705
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700706 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700707
Wink Saville51f456f2013-04-23 14:26:51 -0700708 // TODO: What is the "correct" way to do determine if this is a wifi only device?
709 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
710 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700711 String[] naStrings = context.getResources().getStringArray(
712 com.android.internal.R.array.networkAttributes);
713 for (String naString : naStrings) {
714 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700715 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700716 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700717 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800718 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700719 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700720 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700721 }
Wink Saville51f456f2013-04-23 14:26:51 -0700722 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
723 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
724 n.type);
725 continue;
726 }
Wink Saville975c8482011-04-07 14:23:45 -0700727 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800728 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700729 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700730 continue;
731 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700732 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700733
Wink Saville975c8482011-04-07 14:23:45 -0700734 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700735 mNetworksDefined++;
736 } catch(Exception e) {
737 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700738 }
739 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700740
741 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
742 if (mNetConfigs[TYPE_VPN] == null) {
743 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
744 // don't need to add TYPE_VPN to mNetConfigs.
745 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
746 mNetworksDefined++; // used only in the log() statement below.
747 }
748
Wink Saville5e56bc52013-07-29 15:00:57 -0700749 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700750
Robert Greenwalt50393202011-06-21 17:26:14 -0700751 mProtectedNetworks = new ArrayList<Integer>();
752 int[] protectedNetworks = context.getResources().getIntArray(
753 com.android.internal.R.array.config_protectedNetworks);
754 for (int p : protectedNetworks) {
755 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
756 mProtectedNetworks.add(p);
757 } else {
758 if (DBG) loge("Ignoring protectedNetwork " + p);
759 }
760 }
761
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700762 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
763 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700764
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800765 mTethering = new Tethering(mContext, mNetd, statsService);
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 }
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900810 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(),
811 NetworkRequest.Type.REQUEST);
Erik Klineda4bfa82015-04-30 12:58:40 +0900812 }
813
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900814 // Used only for testing.
815 // TODO: Delete this and either:
816 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
817 // changing ContentResolver to make registerContentObserver non-final).
818 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
819 // by subclassing SettingsObserver.
820 @VisibleForTesting
821 void updateMobileDataAlwaysOn() {
822 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
823 }
824
Erik Klineda4bfa82015-04-30 12:58:40 +0900825 private void handleMobileDataAlwaysOn() {
826 final boolean enable = (Settings.Global.getInt(
827 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
828 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
829 if (enable == isEnabled) {
830 return; // Nothing to do.
831 }
832
833 if (enable) {
834 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900835 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900836 } else {
837 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
838 }
839 }
840
841 private void registerSettingsCallbacks() {
842 // Watch for global HTTP proxy changes.
843 mSettingsObserver.observe(
844 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
845 EVENT_APPLY_GLOBAL_HTTP_PROXY);
846
847 // Watch for whether or not to keep mobile data always on.
848 mSettingsObserver.observe(
849 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
850 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
851 }
852
Robert Greenwalt34524f02014-05-18 16:22:10 -0700853 private synchronized int nextNetworkRequestId() {
854 return mNextNetworkRequestId++;
855 }
856
Paul Jensen67b0b072015-06-10 11:22:17 -0400857 @VisibleForTesting
858 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400859 synchronized (mNetworkForNetId) {
860 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
861 int netId = mNextNetId;
862 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
863 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500864 if (!mNetIdInUse.get(netId)) {
865 mNetIdInUse.put(netId, true);
866 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400867 }
868 }
869 }
870 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700871 }
872
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600873 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800874 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600875 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
876 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800877 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600878 state = nai.getNetworkState();
879 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800880 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600881 final NetworkInfo info = new NetworkInfo(networkType, 0,
882 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800883 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
884 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600885 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
886 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800887 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600888 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600889 return state;
890 } else {
891 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800892 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400893 }
894
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800895 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
896 if (network == null) {
897 return null;
898 }
899 synchronized (mNetworkForNetId) {
900 return mNetworkForNetId.get(network.netId);
901 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600902 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800903
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900904 private Network[] getVpnUnderlyingNetworks(int uid) {
905 if (!mLockdownEnabled) {
906 int user = UserHandle.getUserId(uid);
907 synchronized (mVpns) {
908 Vpn vpn = mVpns.get(user);
909 if (vpn != null && vpn.appliesToUid(uid)) {
910 return vpn.getUnderlyingNetworks();
911 }
912 }
913 }
914 return null;
915 }
916
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800917 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400918 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800919
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900920 final Network[] networks = getVpnUnderlyingNetworks(uid);
921 if (networks != null) {
922 // getUnderlyingNetworks() returns:
923 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
924 // empty array => the VPN explicitly said "no default network".
925 // non-empty array => the VPN specified one or more default networks; we use the
926 // first one.
927 if (networks.length > 0) {
928 nai = getNetworkAgentInfoForNetwork(networks[0]);
929 } else {
930 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800931 }
932 }
933
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600935 return nai.getNetworkState();
936 } else {
937 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800938 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400939 }
940
941 /**
942 * Check if UID should be blocked from using the network with the given LinkProperties.
943 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600944 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
945 boolean ignoreBlocked) {
946 // Networks aren't blocked when ignoring blocked status
947 if (ignoreBlocked) return false;
948 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -0700949 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600950
951 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700952 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700953
Robin Lee17e61832016-05-09 13:46:28 +0100954 synchronized (mVpns) {
955 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
956 if (vpn != null && vpn.isBlockingUid(uid)) {
957 return true;
958 }
959 }
960
Robert Greenwalt12e67352014-05-13 21:41:06 -0700961 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700962 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600963 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -0700964 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700965 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700966
Felipe Lemed31a97f2016-05-06 14:53:50 -0700967 boolean allowed = true;
968 // Check Data Saver Mode first...
969 if (networkMetered) {
970 if ((uidRules & RULE_REJECT_METERED) != 0) {
971 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
972 // Explicitly blacklisted.
973 allowed = false;
974 } else {
975 allowed = !mRestrictBackground
976 || (uidRules & RULE_ALLOW_METERED) != 0
977 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
978 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
979 + " mRestrictBackground=" + mRestrictBackground
980 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
981 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
982 + ": " + allowed);
983 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700984 }
Felipe Leme781ba142016-05-09 16:24:48 -0700985 // ...then power restrictions.
986 if (allowed) {
987 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -0700988 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -0700989 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -0700990 }
991 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700992 }
993
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900994 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
995 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
996 boolean removed = false;
997 boolean added = false;
998 synchronized (mBlockedAppUids) {
999 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1000 added = true;
1001 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1002 removed = true;
1003 }
1004 }
1005 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
1006 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
1007 }
1008
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001009 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001010 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1011 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1012 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1013 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001014 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001015 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001016 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1017
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001018 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001019 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001020 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001021 if (mLockdownTracker != null) {
1022 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001023 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001024
1025 // TODO: apply metered state closer to NetworkAgentInfo
1026 final long token = Binder.clearCallingIdentity();
1027 try {
1028 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1029 } catch (RemoteException e) {
1030 } finally {
1031 Binder.restoreCallingIdentity(token);
1032 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001033 }
1034
1035 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 * Return NetworkInfo for the active (i.e., connected) network interface.
1037 * It is assumed that at most one network is active at a time. If more
1038 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001039 * @return the info for the active network, or {@code null} if none is
1040 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001042 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001044 enforceAccessPermission();
1045 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001046 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001047 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001048 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1049 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051
Paul Jensen31a94f42015-02-13 14:18:39 -05001052 @Override
1053 public Network getActiveNetwork() {
1054 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001055 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001056 }
1057
1058 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001059 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001060 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001061 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001062 }
1063
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001064 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001065 final int user = UserHandle.getUserId(uid);
1066 int vpnNetId = NETID_UNSET;
1067 synchronized (mVpns) {
1068 final Vpn vpn = mVpns.get(user);
1069 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1070 }
1071 NetworkAgentInfo nai;
1072 if (vpnNetId != NETID_UNSET) {
1073 synchronized (mNetworkForNetId) {
1074 nai = mNetworkForNetId.get(vpnNetId);
1075 }
1076 if (nai != null) return nai.network;
1077 }
1078 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001079 if (nai != null
1080 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1081 nai = null;
1082 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001083 return nai != null ? nai.network : null;
1084 }
1085
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001086 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1087 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001088 final int uid = Binder.getCallingUid();
1089 NetworkState state = getUnfilteredActiveNetworkState(uid);
1090 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001091 }
1092
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001093 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001094 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001095 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001096 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001097 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001098 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001099 }
1100
1101 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 public NetworkInfo getNetworkInfo(int networkType) {
1103 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001104 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001105 if (getVpnUnderlyingNetworks(uid) != null) {
1106 // A VPN is active, so we may need to return one of its underlying networks. This
1107 // information is not available in LegacyTypeTracker, so we have to get it from
1108 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001109 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001110 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001111 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001112 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001113 }
1114 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001115 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001116 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
1118
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001119 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001120 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001121 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001122 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001123 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001124 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001125 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001126 return state.networkInfo;
1127 } else {
1128 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001129 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001130 }
1131
1132 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 public NetworkInfo[] getAllNetworkInfo() {
1134 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001135 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001136 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1137 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001138 NetworkInfo info = getNetworkInfo(networkType);
1139 if (info != null) {
1140 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001143 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
1145
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001146 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001147 public Network getNetworkForType(int networkType) {
1148 enforceAccessPermission();
1149 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001150 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1151 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001152 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001153 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001154 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001155 }
1156
1157 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001158 public Network[] getAllNetworks() {
1159 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001160 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001161 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001162 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001163 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001164 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001165 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001166 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001167 }
1168
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001169 @Override
1170 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1171 // The basic principle is: if an app's traffic could possibly go over a
1172 // network, without the app doing anything multinetwork-specific,
1173 // (hence, by "default"), then include that network's capabilities in
1174 // the array.
1175 //
1176 // In the normal case, app traffic only goes over the system's default
1177 // network connection, so that's the only network returned.
1178 //
1179 // With a VPN in force, some app traffic may go into the VPN, and thus
1180 // over whatever underlying networks the VPN specifies, while other app
1181 // traffic may go over the system default network (e.g.: a split-tunnel
1182 // VPN, or an app disallowed by the VPN), so the set of networks
1183 // returned includes the VPN's underlying networks and the system
1184 // default.
1185 enforceAccessPermission();
1186
1187 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1188
1189 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001190 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001191 if (nc != null) {
1192 result.put(nai.network, nc);
1193 }
1194
1195 if (!mLockdownEnabled) {
1196 synchronized (mVpns) {
1197 Vpn vpn = mVpns.get(userId);
1198 if (vpn != null) {
1199 Network[] networks = vpn.getUnderlyingNetworks();
1200 if (networks != null) {
1201 for (Network network : networks) {
1202 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001203 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001204 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001205 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001206 }
1207 }
1208 }
1209 }
1210 }
1211 }
1212
1213 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1214 out = result.values().toArray(out);
1215 return out;
1216 }
1217
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001218 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001219 public boolean isNetworkSupported(int networkType) {
1220 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001221 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001222 }
1223
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001224 /**
1225 * Return LinkProperties for the active (i.e., connected) default
1226 * network interface. It is assumed that at most one default network
1227 * is active at a time. If more than one is active, it is indeterminate
1228 * which will be returned.
1229 * @return the ip properties for the active network, or {@code null} if
1230 * none is active
1231 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001232 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001233 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001234 enforceAccessPermission();
1235 final int uid = Binder.getCallingUid();
1236 NetworkState state = getUnfilteredActiveNetworkState(uid);
1237 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001238 }
1239
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001240 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001241 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001242 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1244 if (nai != null) {
1245 synchronized (nai) {
1246 return new LinkProperties(nai.linkProperties);
1247 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001248 }
1249 return null;
1250 }
1251
Robert Greenwalt12e67352014-05-13 21:41:06 -07001252 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001253 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001254 public LinkProperties getLinkProperties(Network network) {
1255 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001256 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001257 if (nai != null) {
1258 synchronized (nai) {
1259 return new LinkProperties(nai.linkProperties);
1260 }
1261 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001262 return null;
1263 }
1264
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001265 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001266 if (nai != null) {
1267 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001268 if (nai.networkCapabilities != null) {
1269 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001270 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001271 }
1272 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001273 return null;
1274 }
1275
1276 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001277 public NetworkCapabilities getNetworkCapabilities(Network network) {
1278 enforceAccessPermission();
1279 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1280 }
1281
1282 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001283 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001284 // Require internal since we're handing out IMSI details
1285 enforceConnectivityInternalPermission();
1286
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001287 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001288 for (Network network : getAllNetworks()) {
1289 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1290 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001291 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001292 }
1293 }
1294 return result.toArray(new NetworkState[result.size()]);
1295 }
1296
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001297 @Override
1298 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1299 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001300 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001301 final long token = Binder.clearCallingIdentity();
1302 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001303 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1304 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001305 try {
1306 return mPolicyManager.getNetworkQuotaInfo(state);
1307 } catch (RemoteException e) {
1308 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001309 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001310 return null;
1311 } finally {
1312 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001313 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001314 }
1315
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001316 @Override
1317 public boolean isActiveNetworkMetered() {
1318 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001319
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001320 final NetworkInfo info = getActiveNetworkInfo();
1321 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001322 }
1323
Jeff Sharkey216c1812012-08-05 14:29:23 -07001324 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1325 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001326 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001327 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001328 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001329 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001330 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001331
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001332 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 * Ensure that a network route exists to deliver traffic to the specified
1334 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001335 * @param networkType the type of the network over which traffic to the
1336 * specified host is to be routed
1337 * @param hostAddress the IP address of the host to which the route is
1338 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 * @return {@code true} on success, {@code false} on failure
1340 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001341 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001343 if (mProtectedNetworks.contains(networkType)) {
1344 enforceConnectivityInternalPermission();
1345 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001346
Chad Brubakerc0234532014-02-14 13:24:29 -08001347 InetAddress addr;
1348 try {
1349 addr = InetAddress.getByAddress(hostAddress);
1350 } catch (UnknownHostException e) {
1351 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1352 return false;
1353 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001356 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 return false;
1358 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001359
1360 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1361 if (nai == null) {
1362 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1363 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1364 } else {
1365 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1366 }
1367 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001368 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001369
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001370 DetailedState netState;
1371 synchronized (nai) {
1372 netState = nai.networkInfo.getDetailedState();
1373 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001374
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001375 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001376 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001377 log("requestRouteToHostAddress on down network "
1378 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001379 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001380 }
1381 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001383
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001384 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001385 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001386 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001387 LinkProperties lp;
1388 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001389 synchronized (nai) {
1390 lp = nai.linkProperties;
1391 netId = nai.network.netId;
1392 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001393 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001394 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1395 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001396 } finally {
1397 Binder.restoreCallingIdentity(token);
1398 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001399 }
1400
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001401 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001402 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001403 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001404 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001405 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001406 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001407 if (bestRoute.getGateway().equals(addr)) {
1408 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001409 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001410 } else {
1411 // if we will connect to this through another route, add a direct route
1412 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001413 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001414 }
1415 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001416 if (DBG) log("Adding legacy route " + bestRoute +
1417 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001418 try {
1419 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1420 } catch (Exception e) {
1421 // never crash - catch them all
1422 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001423 return false;
1424 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001425 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
1427
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001428 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1429 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001430 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001431 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001432 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001433 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001434 }
1435
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001436 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001437 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001438 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001439 if (oldRules == uidRules) return;
1440
Felipe Leme781ba142016-05-09 16:24:48 -07001441 if (uidRules == RULE_NONE) {
1442 mUidRules.delete(uid);
1443 } else {
1444 mUidRules.put(uid, uidRules);
1445 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001446 }
1447
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001448 // TODO: notify UID when it has requested targeted updates
1449 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001450
1451 @Override
1452 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001453 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001454 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001455 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001456 }
1457
1458 synchronized (mRulesLock) {
1459 mMeteredIfaces.clear();
1460 for (String iface : meteredIfaces) {
1461 mMeteredIfaces.add(iface);
1462 }
1463 }
1464 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001465
1466 @Override
1467 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1468 // caller is NPMS, since we only register with them
1469 if (LOGD_RULES) {
1470 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1471 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001472
1473 synchronized (mRulesLock) {
1474 mRestrictBackground = restrictBackground;
1475 }
1476
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001477 if (restrictBackground) {
1478 log("onRestrictBackgroundChanged(true): disabling tethering");
1479 mTethering.untetherAll();
1480 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001481 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001482
1483 @Override
1484 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1485 if (LOGD_RULES) {
1486 // caller is NPMS, since we only register with them
1487 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1488 + whitelisted + ")");
1489 }
1490 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001491 @Override
1492 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1493 if (LOGD_RULES) {
1494 // caller is NPMS, since we only register with them
1495 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1496 + blacklisted + ")");
1497 }
1498 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001499 };
1500
Robin Lee3b3dd942015-05-12 18:14:58 +01001501 /**
1502 * Require that the caller is either in the same user or has appropriate permission to interact
1503 * across users.
1504 *
1505 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1506 */
1507 private void enforceCrossUserPermission(int userId) {
1508 if (userId == UserHandle.getCallingUserId()) {
1509 // Not a cross-user call.
1510 return;
1511 }
1512 mContext.enforceCallingOrSelfPermission(
1513 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1514 "ConnectivityService");
1515 }
1516
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001517 private void enforceInternetPermission() {
1518 mContext.enforceCallingOrSelfPermission(
1519 android.Manifest.permission.INTERNET,
1520 "ConnectivityService");
1521 }
1522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001524 mContext.enforceCallingOrSelfPermission(
1525 android.Manifest.permission.ACCESS_NETWORK_STATE,
1526 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
1528
1529 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001530 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 }
1532
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001533 private void enforceTetherAccessPermission() {
1534 mContext.enforceCallingOrSelfPermission(
1535 android.Manifest.permission.ACCESS_NETWORK_STATE,
1536 "ConnectivityService");
1537 }
1538
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001539 private void enforceConnectivityInternalPermission() {
1540 mContext.enforceCallingOrSelfPermission(
1541 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1542 "ConnectivityService");
1543 }
1544
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001545 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001546 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001547 }
1548
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001549 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001550 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001551 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001552 }
1553
1554 private void sendInetConditionBroadcast(NetworkInfo info) {
1555 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1556 }
1557
Wink Saville628b0852011-08-04 15:01:58 -07001558 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001559 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001560 info = new NetworkInfo(info);
1561 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001562 }
1563
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001564 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001565 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001566 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 if (info.isFailover()) {
1568 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1569 info.setFailover(false);
1570 }
1571 if (info.getReason() != null) {
1572 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1573 }
1574 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001575 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1576 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001578 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001579 return intent;
1580 }
1581
1582 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1583 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1584 }
1585
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001586 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001587 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1588 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1589 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001590 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001591 final long ident = Binder.clearCallingIdentity();
1592 try {
1593 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1594 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1595 } finally {
1596 Binder.restoreCallingIdentity(ident);
1597 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001598 }
1599
Mike Lockwood0f79b542009-08-14 14:18:49 -04001600 private void sendStickyBroadcast(Intent intent) {
1601 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001602 if (!mSystemReady) {
1603 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001604 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001605 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001606 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001607 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001608 }
1609
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001610 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001611 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001612 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001613 final NetworkInfo ni = intent.getParcelableExtra(
1614 ConnectivityManager.EXTRA_NETWORK_INFO);
1615 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1616 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1617 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001618 } else {
1619 BroadcastOptions opts = BroadcastOptions.makeBasic();
1620 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1621 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001622 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001623 final IBatteryStats bs = BatteryStatsService.getService();
1624 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001625 bs.noteConnectivityChanged(intent.getIntExtra(
1626 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1627 ni != null ? ni.getState().toString() : "?");
1628 } catch (RemoteException e) {
1629 }
1630 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001631 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001632 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001633 } finally {
1634 Binder.restoreCallingIdentity(ident);
1635 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001636 }
1637 }
1638
1639 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001640 loadGlobalProxy();
1641
Mike Lockwood0f79b542009-08-14 14:18:49 -04001642 synchronized(this) {
1643 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001644 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001645 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001646 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001647 }
1648 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001649 // load the global proxy at startup
1650 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001651
Robin Lee244ce8e2016-01-05 18:03:46 +00001652 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1653 // for user to unlock device too.
1654 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001655
Erik Klineda4bfa82015-04-30 12:58:40 +09001656 // Configure whether mobile data is always on.
1657 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1658
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001659 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001660
1661 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
1663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001665 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001666 *
1667 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001668 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001669 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001670 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1671 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001672
1673 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001674 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001675
Robert Greenwalt7b816022014-04-18 15:25:25 -07001676 if (networkAgent.networkCapabilities.hasTransport(
1677 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001678 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1679 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001680 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001681 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001682 } else if (networkAgent.networkCapabilities.hasTransport(
1683 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001684 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1685 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001686 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001687 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001688 } else {
1689 // do not track any other networks
1690 timeout = 0;
1691 }
1692
Robert Greenwalt7b816022014-04-18 15:25:25 -07001693 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001694 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001695 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001696 } catch (Exception e) {
1697 // You shall not crash!
1698 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001699 }
1700 }
1701 }
1702
1703 /**
1704 * Remove data activity tracking when network disconnects.
1705 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001706 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1707 final String iface = networkAgent.linkProperties.getInterfaceName();
1708 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001709
Robert Greenwalt7b816022014-04-18 15:25:25 -07001710 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1711 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001712 try {
1713 // the call fails silently if no idletimer setup for this interface
1714 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001715 } catch (Exception e) {
1716 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001717 }
1718 }
1719 }
1720
1721 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001722 * Reads the network specific MTU size from reources.
1723 * and set it on it's iface.
1724 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001725 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1726 final String iface = newLp.getInterfaceName();
1727 final int mtu = newLp.getMtu();
1728 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1729 if (VDBG) log("identical MTU - not setting");
1730 return;
1731 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001732
Robert Greenwalt43074032014-08-15 17:53:05 -07001733 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001734 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001735 return;
1736 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001737
w1997615afd812014-08-05 15:18:11 -07001738 // Cannot set MTU without interface name
1739 if (TextUtils.isEmpty(iface)) {
1740 loge("Setting MTU size with null iface.");
1741 return;
1742 }
1743
Robert Greenwalt7b816022014-04-18 15:25:25 -07001744 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001745 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001746 mNetd.setMtu(iface, mtu);
1747 } catch (Exception e) {
1748 Slog.e(TAG, "exception in setMtu()" + e);
1749 }
1750 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001751
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001752 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001753 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1754
1755 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001756 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001757 protected int getDefaultTcpRwnd() {
1758 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1759 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001760
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001761 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1762 if (isDefaultNetwork(nai) == false) {
1763 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001764 }
1765
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001766 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1767 String[] values = null;
1768 if (tcpBufferSizes != null) {
1769 values = tcpBufferSizes.split(",");
1770 }
1771
1772 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001773 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001774 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1775 values = tcpBufferSizes.split(",");
1776 }
1777
1778 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1779
1780 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001781 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001782
1783 final String prefix = "/sys/kernel/ipv4/tcp_";
1784 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1785 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1786 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1787 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1788 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1789 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1790 mCurrentTcpBufferSizes = tcpBufferSizes;
1791 } catch (IOException e) {
1792 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001793 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001794
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001795 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001796 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001797 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1798 if (rwndValue != 0) {
1799 SystemProperties.set(sysctlKey, rwndValue.toString());
1800 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001801 }
1802
Mattias Falk8b47b362011-08-23 14:15:13 +02001803 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001804 /*
1805 * Tell the VMs to toss their DNS caches
1806 */
1807 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1808 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001809 /*
1810 * Connectivity events can happen before boot has completed ...
1811 */
1812 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001813 final long ident = Binder.clearCallingIdentity();
1814 try {
1815 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1816 } finally {
1817 Binder.restoreCallingIdentity(ident);
1818 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001819 }
1820
Robert Greenwalt562cc542014-05-15 18:07:26 -07001821 @Override
1822 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001823 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1824 NETWORK_RESTORE_DELAY_PROP_NAME);
1825 if(restoreDefaultNetworkDelayStr != null &&
1826 restoreDefaultNetworkDelayStr.length() != 0) {
1827 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001828 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001829 } catch (NumberFormatException e) {
1830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001832 // if the system property isn't set, use the value for the apn type
1833 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1834
1835 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1836 (mNetConfigs[networkType] != null)) {
1837 ret = mNetConfigs[networkType].restoreTime;
1838 }
1839 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 }
1841
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001842 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001843 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001844 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001845 }
1846 return false;
1847 }
1848
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001849 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1850 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1851 final long DIAG_TIME_MS = 5000;
1852 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1853 // Start gathering diagnostic information.
1854 netDiags.add(new NetworkDiagnostics(
1855 nai.network,
1856 new LinkProperties(nai.linkProperties), // Must be a copy.
1857 DIAG_TIME_MS));
1858 }
1859
1860 for (NetworkDiagnostics netDiag : netDiags) {
1861 pw.println();
1862 netDiag.waitForMeasurements();
1863 netDiag.dump(pw);
1864 }
1865 }
1866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001868 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1869 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001870 if (mContext.checkCallingOrSelfPermission(
1871 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001873 pw.println("Permission Denial: can't dump ConnectivityService " +
1874 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1875 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 return;
1877 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001878
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001879 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001880 dumpNetworkDiagnostics(pw);
1881 return;
1882 }
Erik Kline379747a2015-06-05 17:47:34 +09001883
Lorenzo Colittie3805462015-06-03 11:18:24 +09001884 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001885 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001886 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001887 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001888 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001889 pw.println();
1890
Paul Jensen85cf78e2015-06-25 13:25:07 -04001891 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001892 pw.print("Active default network: ");
1893 if (defaultNai == null) {
1894 pw.println("none");
1895 } else {
1896 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001898 pw.println();
1899
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001900 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001901 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001902 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1903 pw.println(nai.toString());
1904 pw.increaseIndent();
1905 pw.println("Requests:");
1906 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001907 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1908 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001909 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001910 pw.decreaseIndent();
1911 pw.println("Lingered:");
1912 pw.increaseIndent();
1913 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1914 pw.decreaseIndent();
1915 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001916 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001917 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001918 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001919
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001920 pw.println("Metered Interfaces:");
1921 pw.increaseIndent();
1922 for (String value : mMeteredIfaces) {
1923 pw.println(value);
1924 }
1925 pw.decreaseIndent();
1926 pw.println();
1927
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001928 pw.print("Restrict background: ");
1929 pw.println(mRestrictBackground);
1930 pw.println();
1931
Felipe Leme46c4fc32016-05-04 09:21:43 -07001932 pw.println("Status for known UIDs:");
1933 pw.increaseIndent();
1934 final int size = mUidRules.size();
1935 for (int i = 0; i < size; i++) {
1936 final int uid = mUidRules.keyAt(i);
1937 pw.print("UID=");
1938 pw.print(uid);
1939 final int uidRules = mUidRules.get(uid, RULE_NONE);
1940 pw.print(" rules=");
1941 pw.print(uidRulesToString(uidRules));
1942 pw.println();
1943 }
1944 pw.println();
1945 pw.decreaseIndent();
1946
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001947 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001948 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001949 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1950 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001951 }
1952 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001953 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001954
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001955 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001956
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001957 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001958 pw.print("mNetTransitionWakeLock: currently " +
1959 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1960 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1961 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1962 } else {
1963 pw.println(", last requested never");
1964 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001965 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001966
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001967 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001968 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001969
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001970 pw.println();
1971 mKeepaliveTracker.dump(pw);
1972
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001973 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001974
Lorenzo Colittie3805462015-06-03 11:18:24 +09001975 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001976 pw.println();
1977 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001978 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001979 for(int i = 0; i < mInetLog.size(); i++) {
1980 pw.println(mInetLog.get(i));
1981 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001982 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001983 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001984
1985 if (argsContain(args, "--short") == false) {
1986 pw.println();
1987 synchronized (mValidationLogs) {
1988 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001989 for (ValidationLog p : mValidationLogs) {
1990 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001991 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001992 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001993 pw.decreaseIndent();
1994 }
1995 }
Erik Kline7523eb32015-07-09 18:24:03 +09001996
1997 pw.println();
1998 pw.println("mNetworkRequestInfoLogs (most recent first):");
1999 pw.increaseIndent();
2000 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2001 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
2004
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002005 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002006 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002007 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002008 if (officialNai != null && officialNai.equals(nai)) return true;
2009 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002010 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002011 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002012 " - " + nai);
2013 }
2014 return false;
2015 }
2016
Robert Greenwalt42acef32009-08-12 16:08:25 -07002017 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002018 private class NetworkStateTrackerHandler extends Handler {
2019 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002020 super(looper);
2021 }
2022
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002023 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002025 default:
2026 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002027 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002028 handleAsyncChannelHalfConnect(msg);
2029 break;
2030 }
2031 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2032 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2033 if (nai != null) nai.asyncChannel.disconnect();
2034 break;
2035 }
2036 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2037 handleAsyncChannelDisconnected(msg);
2038 break;
2039 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002040 }
2041 return true;
2042 }
2043
2044 private void maybeHandleNetworkAgentMessage(Message msg) {
2045 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2046 if (nai == null) {
2047 if (VDBG) {
2048 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2049 log(String.format("%s from unknown NetworkAgent", what));
2050 }
2051 return;
2052 }
2053
2054 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002055 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002056 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2057 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2058 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2059 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002060 }
Robin Lee585e2482016-05-01 23:00:00 +01002061 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002062 networkCapabilities)) {
2063 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2064 + nai.networkCapabilities + " -> " + networkCapabilities);
2065 }
2066 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002067 break;
2068 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002069 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002070 if (VDBG) {
2071 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002072 "; created=" + nai.created +
2073 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002074 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002075 LinkProperties oldLp = nai.linkProperties;
2076 synchronized (nai) {
2077 nai.linkProperties = (LinkProperties)msg.obj;
2078 }
Robin Lee585e2482016-05-01 23:00:00 +01002079 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002080 break;
2081 }
2082 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002083 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002084 updateNetworkInfo(nai, info);
2085 break;
2086 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002087 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002088 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002089 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002090 break;
2091 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002092 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002093 try {
2094 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002095 } catch (Exception e) {
2096 // Never crash!
2097 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002098 }
2099 break;
2100 }
2101 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002102 try {
2103 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002104 } catch (Exception e) {
2105 // Never crash!
2106 loge("Exception in removeVpnUidRanges: " + e);
2107 }
2108 break;
2109 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002110 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002111 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2112 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002113 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002114 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002115 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002116 break;
2117 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002118 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002119 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2120 break;
2121 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002122 }
2123 }
2124
2125 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2126 switch (msg.what) {
2127 default:
2128 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002129 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002130 final NetworkAgentInfo nai;
2131 synchronized (mNetworkForNetId) {
2132 nai = mNetworkForNetId.get(msg.arg2);
2133 }
2134 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002135 final boolean valid =
2136 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002137 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2138 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002139 if (valid != nai.lastValidated) {
2140 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002141 nai.lastValidated = valid;
2142 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002143 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002144 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2145 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002146 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002147 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002148 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002149 Bundle redirectUrlBundle = new Bundle();
2150 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002151 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002152 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002153 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002154 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002155 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002156 break;
2157 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002158 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002159 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002160 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002161 handleLingerComplete(nai);
2162 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002163 break;
2164 }
Paul Jensen869868be2014-05-15 10:33:05 -04002165 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002166 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002167 final boolean visible = (msg.arg1 != 0);
2168 final NetworkAgentInfo nai;
2169 synchronized (mNetworkForNetId) {
2170 nai = mNetworkForNetId.get(netId);
2171 }
2172 // If captive portal status has changed, update capabilities.
2173 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2174 nai.lastCaptivePortalDetected = visible;
2175 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002176 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002177 }
2178 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002179 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002180 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002181 if (nai == null) {
2182 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2183 break;
2184 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002185 if (!nai.networkMisc.provisioningNotificationDisabled) {
2186 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
2187 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2188 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
2189 }
Paul Jensen869868be2014-05-15 10:33:05 -04002190 }
Paul Jensen869868be2014-05-15 10:33:05 -04002191 break;
2192 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002193 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002194 return true;
2195 }
2196
2197 @Override
2198 public void handleMessage(Message msg) {
2199 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2200 maybeHandleNetworkAgentMessage(msg);
2201 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002202 }
2203 }
2204
Paul Jensen85cf78e2015-06-25 13:25:07 -04002205 private void linger(NetworkAgentInfo nai) {
2206 nai.lingering = true;
Hugo Benichicfddd682016-05-31 16:28:06 +09002207 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002208 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2209 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2210 }
2211
Paul Jensen0cc17322014-11-25 15:26:53 -05002212 // Cancel any lingering so the linger timeout doesn't teardown a network.
2213 // This should be called when a network begins satisfying a NetworkRequest.
2214 // Note: depending on what state the NetworkMonitor is in (e.g.,
2215 // if it's awaiting captive portal login, or if validation failed), this
2216 // may trigger a re-evaluation of the network.
2217 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002218 nai.networkLingered.clear();
2219 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002220 nai.lingering = false;
Hugo Benichicfddd682016-05-31 16:28:06 +09002221 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Paul Jensen0cc17322014-11-25 15:26:53 -05002222 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002223 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2224 }
2225
Robert Greenwalt7b816022014-04-18 15:25:25 -07002226 private void handleAsyncChannelHalfConnect(Message msg) {
2227 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002228 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002229 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2230 if (VDBG) log("NetworkFactory connected");
2231 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002232 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002233 if (!nri.request.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002234 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002235 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002236 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002237 }
2238 } else {
2239 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002240 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002241 }
2242 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2243 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2244 if (VDBG) log("NetworkAgent connected");
2245 // A network agent has requested a connection. Establish the connection.
2246 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2247 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2248 } else {
2249 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002250 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002251 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002252 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002253 synchronized (mNetworkForNetId) {
2254 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002255 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002256 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002257 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002258 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002259 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002260 }
2261 }
2262 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002263
Robert Greenwalt7b816022014-04-18 15:25:25 -07002264 private void handleAsyncChannelDisconnected(Message msg) {
2265 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2266 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002267 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002268 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002269 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002270 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002271 // TODO - if we move the logic to the network agent (have them disconnect
2272 // because they lost all their requests or because their score isn't good)
2273 // then they would disconnect organically, report their new state and then
2274 // disconnect the channel.
2275 if (nai.networkInfo.isConnected()) {
2276 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2277 null, null);
2278 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002279 final boolean wasDefault = isDefaultNetwork(nai);
2280 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002281 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002282 // Log default network disconnection before required book-keeping.
2283 // Let rematchAllNetworksAndRequests() below record a new default network event
2284 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2285 // whose timestamps tell how long it takes to recover a default network.
2286 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002287 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002288 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002289 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2290 // by other networks that are already connected. Perhaps that can be done by
2291 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2292 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002293 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002294 mKeepaliveTracker.handleStopAllKeepalives(nai,
2295 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002296 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002297 mNetworkAgentInfos.remove(msg.replyTo);
2298 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002299 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002300 // Remove the NetworkAgent, but don't mark the netId as
2301 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002302 mNetworkForNetId.remove(nai.network.netId);
2303 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002304 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002305 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2306 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002307 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2308 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2309 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002310 sendUpdatedScoreToFactories(request, 0);
2311 }
2312 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002313 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002314 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002315 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002316 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002317 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002318 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002319 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002320 if (nai.created) {
2321 // Tell netd to clean up the configuration for this network
2322 // (routing rules, DNS, etc).
2323 // This may be slow as it requires a lot of netd shelling out to ip and
2324 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2325 // after we've rematched networks with requests which should make a potential
2326 // fallback network the default or requested a new network from the
2327 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2328 // long time.
2329 try {
2330 mNetd.removeNetwork(nai.network.netId);
2331 } catch (Exception e) {
2332 loge("Exception removing network: " + e);
2333 }
2334 }
2335 synchronized (mNetworkForNetId) {
2336 mNetIdInUse.delete(nai.network.netId);
2337 }
2338 } else {
2339 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2340 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002341 }
2342 }
2343
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002344 // If this method proves to be too slow then we can maintain a separate
2345 // pendingIntent => NetworkRequestInfo map.
2346 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2347 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2348 Intent intent = pendingIntent.getIntent();
2349 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2350 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2351 if (existingPendingIntent != null &&
2352 existingPendingIntent.getIntent().filterEquals(intent)) {
2353 return entry.getValue();
2354 }
2355 }
2356 return null;
2357 }
2358
2359 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2360 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2361
2362 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2363 if (existingRequest != null) { // remove the existing request.
2364 if (DBG) log("Replacing " + existingRequest.request + " with "
2365 + nri.request + " because their intents matched.");
2366 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2367 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002368 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002369 }
2370
Erik Klineda4bfa82015-04-30 12:58:40 +09002371 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002372 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002373 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002374 if (!nri.request.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002375 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002376 if (nri.request.networkCapabilities.hasSignalStrength() &&
2377 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2378 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002379 }
2380 }
2381 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002382 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002383 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002384 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002385 }
2386 }
2387
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002388 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2389 int callingUid) {
2390 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2391 if (nri != null) {
2392 handleReleaseNetworkRequest(nri.request, callingUid);
2393 }
2394 }
2395
Paul Jensen99364842014-12-09 11:43:45 -05002396 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002397 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2398 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002399 private boolean unneeded(NetworkAgentInfo nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002400 if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002401 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2402 // If this Network is already the highest scoring Network for a request, or if
2403 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002404 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002405 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002406 // Note that this catches two important cases:
2407 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2408 // is currently satisfying the request. This is desirable when
2409 // cellular ends up validating but WiFi does not.
2410 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002411 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002412 // WiFi ends up validating and out scoring cellular.
2413 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2414 nai.getCurrentScoreAsValidated())) {
2415 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002416 }
2417 }
Paul Jensene0988542015-06-25 15:30:08 -04002418 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002419 }
2420
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002421 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2422 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002423 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002424 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002425 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2426 return;
2427 }
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002428 if (VDBG || (DBG && nri.request.isRequest())) log("releasing " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002429 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002430 mNetworkRequests.remove(request);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002431 synchronized (mUidToNetworkRequestCount) {
2432 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2433 if (requests < 1) {
2434 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2435 nri.mUid);
2436 } else if (requests == 1) {
2437 mUidToNetworkRequestCount.removeAt(
2438 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2439 } else {
2440 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2441 }
2442 }
Erik Kline7523eb32015-07-09 18:24:03 +09002443 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002444 if (nri.request.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002445 // Find all networks that are satisfying this request and remove the request
2446 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002447 // TODO - it's my understanding that for a request there is only a single
2448 // network satisfying it, so this loop is wasteful
2449 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002450 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002451 if (nai.isSatisfyingRequest(nri.request.requestId)) {
2452 nai.removeRequest(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002453 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002454 log(" Removing from current network " + nai.name() +
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002455 ", leaving " + nai.numNetworkRequests() + " requests.");
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002456 }
Paul Jensen99364842014-12-09 11:43:45 -05002457 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002458 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002459 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002460 } else {
2461 // suspect there should only be one pass through here
2462 // but if any were kept do the check below
2463 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002464 }
2465 }
2466 }
2467
Robert Greenwalt51481852015-01-08 14:43:31 -08002468 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2469 if (nai != null) {
2470 mNetworkForRequestId.remove(nri.request.requestId);
2471 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002472 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002473 // that a network connected to serve it, even though the network was already
2474 // connected. Now that this request has gone away, we might have to pretend
2475 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002476 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002477 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2478 boolean doRemove = true;
2479 if (wasKept) {
2480 // check if any of the remaining requests for this network are for the
2481 // same legacy type - if so, don't remove the nai
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002482 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2483 NetworkRequest otherRequest = nai.requestAt(i);
Robert Greenwalt51481852015-01-08 14:43:31 -08002484 if (otherRequest.legacyType == nri.request.legacyType &&
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002485 otherRequest.isRequest()) {
Robert Greenwalt51481852015-01-08 14:43:31 -08002486 if (DBG) log(" still have other legacy request - leaving");
2487 doRemove = false;
2488 }
2489 }
2490 }
2491
2492 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002493 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002494 }
2495 }
2496
Robert Greenwalta67be032014-05-16 15:49:14 -07002497 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002498 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2499 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002500 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002501 } else {
2502 // listens don't have a singular affectedNetwork. Check all networks to see
2503 // if this listen request applies and remove it.
2504 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002505 nai.removeRequest(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002506 if (nri.request.networkCapabilities.hasSignalStrength() &&
2507 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2508 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002509 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002510 }
2511 }
2512 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2513 }
2514 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002515
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002516 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2517 enforceConnectivityInternalPermission();
2518 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2519 accept ? 1 : 0, always ? 1: 0, network));
2520 }
2521
2522 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2523 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2524 " accept=" + accept + " always=" + always);
2525
2526 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2527 if (nai == null) {
2528 // Nothing to do.
2529 return;
2530 }
2531
2532 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002533 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002534 return;
2535 }
2536
2537 if (!nai.networkMisc.explicitlySelected) {
2538 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2539 }
2540
2541 if (accept != nai.networkMisc.acceptUnvalidated) {
2542 int oldScore = nai.getCurrentScore();
2543 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002544 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002545 sendUpdatedScoreToFactories(nai);
2546 }
2547
2548 if (always) {
2549 nai.asyncChannel.sendMessage(
2550 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2551 }
2552
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002553 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002554 // Tell the NetworkAgent to not automatically reconnect to the network.
2555 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2556 // Teardown the nework.
2557 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002558 }
2559
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002560 }
2561
2562 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002563 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002564 mHandler.sendMessageDelayed(
2565 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2566 PROMPT_UNVALIDATED_DELAY_MS);
2567 }
2568
2569 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002570 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002571 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2572
2573 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2574 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002575 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002576 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002577 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2578 return;
2579 }
2580
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002581 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002582 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002583 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2584 intent.setClassName("com.android.settings",
2585 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002586
2587 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2588 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
fionaxu1bf6ec22016-05-23 16:33:16 -07002589
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002590 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002591 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002592 }
2593
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002594 private class InternalHandler extends Handler {
2595 public InternalHandler(Looper looper) {
2596 super(looper);
2597 }
2598
2599 @Override
2600 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002601 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002602 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002603 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002604 String causedBy = null;
2605 synchronized (ConnectivityService.this) {
2606 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2607 mNetTransitionWakeLock.isHeld()) {
2608 mNetTransitionWakeLock.release();
2609 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002610 } else {
2611 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002612 }
2613 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002614 if (VDBG) {
2615 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2616 log("Failed to find a new network - expiring NetTransition Wakelock");
2617 } else {
2618 log("NetTransition Wakelock (" +
2619 (causedBy == null ? "unknown" : causedBy) +
2620 " cleared because we found a replacement network");
2621 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002622 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002623 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002624 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002625 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002626 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002627 break;
2628 }
Jason Monkdecd2952013-10-10 14:02:51 -04002629 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002630 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002631 break;
2632 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002633 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002634 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2635 break;
2636 }
2637 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2638 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002639 break;
2640 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002641 case EVENT_REGISTER_NETWORK_AGENT: {
2642 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2643 break;
2644 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002645 case EVENT_REGISTER_NETWORK_REQUEST:
2646 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002647 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002648 break;
2649 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002650 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2651 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002652 handleRegisterNetworkRequestWithIntent(msg);
2653 break;
2654 }
2655 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2656 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2657 break;
2658 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002659 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002660 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002661 break;
2662 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002663 case EVENT_SET_ACCEPT_UNVALIDATED: {
2664 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2665 break;
2666 }
2667 case EVENT_PROMPT_UNVALIDATED: {
2668 handlePromptUnvalidated((Network) msg.obj);
2669 break;
2670 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002671 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2672 handleMobileDataAlwaysOn();
2673 break;
2674 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002675 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2676 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2677 mKeepaliveTracker.handleStartKeepalive(msg);
2678 break;
2679 }
2680 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2681 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2682 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2683 int slot = msg.arg1;
2684 int reason = msg.arg2;
2685 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2686 break;
2687 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002688 case EVENT_SYSTEM_READY: {
2689 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2690 nai.networkMonitor.systemReady = true;
2691 }
2692 break;
2693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 }
2695 }
2696 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002697
2698 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002699 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002700 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002701 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002702 final int status = mTethering.tether(iface);
2703 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2704 try {
2705 mPolicyManager.onTetheringChanged(iface, true);
2706 } catch (RemoteException e) {
2707 }
2708 }
2709 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002710 } else {
2711 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2712 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002713 }
2714
2715 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002716 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002717 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002718
2719 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002720 final int status = mTethering.untether(iface);
2721 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2722 try {
2723 mPolicyManager.onTetheringChanged(iface, false);
2724 } catch (RemoteException e) {
2725 }
2726 }
2727 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002728 } else {
2729 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2730 }
2731 }
2732
2733 // javadoc from interface
2734 public int getLastTetherError(String iface) {
2735 enforceTetherAccessPermission();
2736
2737 if (isTetheringSupported()) {
2738 return mTethering.getLastTetherError(iface);
2739 } else {
2740 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2741 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002742 }
2743
2744 // TODO - proper iface API for selection by property, inspection, etc
2745 public String[] getTetherableUsbRegexs() {
2746 enforceTetherAccessPermission();
2747 if (isTetheringSupported()) {
2748 return mTethering.getTetherableUsbRegexs();
2749 } else {
2750 return new String[0];
2751 }
2752 }
2753
2754 public String[] getTetherableWifiRegexs() {
2755 enforceTetherAccessPermission();
2756 if (isTetheringSupported()) {
2757 return mTethering.getTetherableWifiRegexs();
2758 } else {
2759 return new String[0];
2760 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002761 }
2762
Danica Chang6fdd0c62010-08-11 14:54:43 -07002763 public String[] getTetherableBluetoothRegexs() {
2764 enforceTetherAccessPermission();
2765 if (isTetheringSupported()) {
2766 return mTethering.getTetherableBluetoothRegexs();
2767 } else {
2768 return new String[0];
2769 }
2770 }
2771
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002772 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002773 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002774 if (isTetheringSupported()) {
2775 return mTethering.setUsbTethering(enable);
2776 } else {
2777 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2778 }
2779 }
2780
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002781 // TODO - move iface listing, queries, etc to new module
2782 // javadoc from interface
2783 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002784 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002785 return mTethering.getTetherableIfaces();
2786 }
2787
2788 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002789 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002790 return mTethering.getTetheredIfaces();
2791 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002792
Robert Greenwalt5a735062010-03-02 17:25:02 -08002793 public String[] getTetheringErroredIfaces() {
2794 enforceTetherAccessPermission();
2795 return mTethering.getErroredIfaces();
2796 }
2797
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002798 public String[] getTetheredDhcpRanges() {
2799 enforceConnectivityInternalPermission();
2800 return mTethering.getTetheredDhcpRanges();
2801 }
2802
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002803 // if ro.tether.denied = true we default to no tethering
2804 // gservices could set the secure setting to 1 though to enable it on a build where it
2805 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002806 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002807 public boolean isTetheringSupported() {
2808 enforceTetherAccessPermission();
2809 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002810 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002811 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2812 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002813 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2814 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002815 mTethering.getTetherableWifiRegexs().length != 0 ||
2816 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2817 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002818 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002819
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002820 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002821 public void startTethering(int type, ResultReceiver receiver,
2822 boolean showProvisioningUi) {
2823 ConnectivityManager.enforceTetherChangePermission(mContext);
2824 if (!isTetheringSupported()) {
2825 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2826 return;
2827 }
2828 mTethering.startTethering(type, receiver, showProvisioningUi);
2829 }
2830
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002831 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002832 public void stopTethering(int type) {
2833 ConnectivityManager.enforceTetherChangePermission(mContext);
2834 mTethering.stopTethering(type);
2835 }
2836
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002837 // Called when we lose the default network and have no replacement yet.
2838 // This will automatically be cleared after X seconds or a new default network
2839 // becomes CONNECTED, whichever happens first. The timer is started by the
2840 // first caller and not restarted by subsequent callers.
2841 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002842 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002843 synchronized (this) {
2844 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002845 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002846 mNetTransitionWakeLock.acquire();
2847 mNetTransitionWakeLockCausedBy = forWhom;
2848 }
2849 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002850 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002851 mNetTransitionWakeLockTimeout);
2852 return;
2853 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002854
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002855 // 100 percent is full good, 0 is full bad.
2856 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002857 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002858 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002859 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002860 }
2861
Paul Jensenbfd17b72015-04-07 12:43:13 -04002862 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002863 enforceAccessPermission();
2864 enforceInternetPermission();
2865
Paul Jensenbfd17b72015-04-07 12:43:13 -04002866 NetworkAgentInfo nai;
2867 if (network == null) {
2868 nai = getDefaultNetwork();
2869 } else {
2870 nai = getNetworkAgentInfoForNetwork(network);
2871 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002872 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2873 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2874 return;
2875 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002876 // Revalidate if the app report does not match our current validated state.
2877 if (hasConnectivity == nai.lastValidated) return;
2878 final int uid = Binder.getCallingUid();
2879 if (DBG) {
2880 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2881 ") by " + uid);
2882 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002883 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002884 // Validating a network that has not yet connected could result in a call to
2885 // rematchNetworkAndRequests() which is not meant to work on such networks.
2886 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04002887
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002888 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002889
2890 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2891 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002892 }
2893
Paul Jensencee9b512015-05-06 07:32:40 -04002894 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002895 // this information is already available as a world read/writable jvm property
2896 // so this API change wouldn't have a benifit. It also breaks the passing
2897 // of proxy info to all the JVMs.
2898 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002899 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002900 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002901 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2902 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002903 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002904 }
2905
Paul Jensencee9b512015-05-06 07:32:40 -04002906 public ProxyInfo getProxyForNetwork(Network network) {
2907 if (network == null) return getDefaultProxy();
2908 final ProxyInfo globalProxy = getGlobalProxy();
2909 if (globalProxy != null) return globalProxy;
2910 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2911 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2912 // caller may not have.
2913 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2914 if (nai == null) return null;
2915 synchronized (nai) {
2916 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2917 if (proxyInfo == null) return null;
2918 return new ProxyInfo(proxyInfo);
2919 }
2920 }
2921
Paul Jensene0bef712014-12-10 15:12:18 -05002922 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2923 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2924 // proxy is null then there is no proxy in place).
2925 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2926 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2927 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2928 proxy = null;
2929 }
2930 return proxy;
2931 }
2932
2933 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2934 // better for determining if a new proxy broadcast is necessary:
2935 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2936 // avoid unnecessary broadcasts.
2937 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2938 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2939 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2940 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2941 // all set.
2942 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2943 a = canonicalizeProxyInfo(a);
2944 b = canonicalizeProxyInfo(b);
2945 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2946 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2947 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2948 }
2949
Jason Monk207900c2014-04-25 15:00:09 -04002950 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002951 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002952
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002953 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002954 if (proxyProperties == mGlobalProxy) return;
2955 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2956 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2957
2958 String host = "";
2959 int port = 0;
2960 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002961 String pacFileUrl = "";
2962 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002963 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002964 if (!proxyProperties.isValid()) {
2965 if (DBG)
2966 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2967 return;
2968 }
Jason Monk207900c2014-04-25 15:00:09 -04002969 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002970 host = mGlobalProxy.getHost();
2971 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002972 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002973 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002974 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002975 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002976 } else {
2977 mGlobalProxy = null;
2978 }
2979 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002980 final long token = Binder.clearCallingIdentity();
2981 try {
2982 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2983 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2984 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2985 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002986 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002987 } finally {
2988 Binder.restoreCallingIdentity(token);
2989 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002990
Jason Monkcf0f97a2014-10-02 15:39:38 -04002991 if (mGlobalProxy == null) {
2992 proxyProperties = mDefaultProxy;
2993 }
2994 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002995 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002996 }
2997
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002998 private void loadGlobalProxy() {
2999 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003000 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3001 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3002 String exclList = Settings.Global.getString(res,
3003 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003004 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3005 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003006 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003007 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003008 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003009 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003010 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003011 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003012 if (!proxyProperties.isValid()) {
3013 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3014 return;
3015 }
3016
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003017 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003018 mGlobalProxy = proxyProperties;
3019 }
3020 }
3021 }
3022
Jason Monk207900c2014-04-25 15:00:09 -04003023 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003024 // this information is already available as a world read/writable jvm property
3025 // so this API change wouldn't have a benifit. It also breaks the passing
3026 // of proxy info to all the JVMs.
3027 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003028 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003029 return mGlobalProxy;
3030 }
3031 }
3032
Jason Monk207900c2014-04-25 15:00:09 -04003033 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003034 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003035 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003036 proxy = null;
3037 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003038 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003039 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003040 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003041 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003042 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3043 return;
3044 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003045
3046 // This call could be coming from the PacManager, containing the port of the local
3047 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3048 // global (to get the correct local port), and send a broadcast.
3049 // TODO: Switch PacManager to have its own message to send back rather than
3050 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003051 if ((mGlobalProxy != null) && (proxy != null)
3052 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003053 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3054 mGlobalProxy = proxy;
3055 sendProxyBroadcast(mGlobalProxy);
3056 return;
3057 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003058 mDefaultProxy = proxy;
3059
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003060 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003061 if (!mDefaultProxyDisabled) {
3062 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003063 }
3064 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003065 }
3066
Paul Jensene0bef712014-12-10 15:12:18 -05003067 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3068 // This method gets called when any network changes proxy, but the broadcast only ever contains
3069 // the default proxy (even if it hasn't changed).
3070 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3071 // world where an app might be bound to a non-default network.
3072 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3073 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3074 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3075
3076 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3077 sendProxyBroadcast(getDefaultProxy());
3078 }
3079 }
3080
Robert Greenwalt434203a2010-10-11 16:00:27 -07003081 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003082 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3083 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003084 if (!TextUtils.isEmpty(proxy)) {
3085 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003086 if (data.length == 0) {
3087 return;
3088 }
3089
Robert Greenwalt434203a2010-10-11 16:00:27 -07003090 String proxyHost = data[0];
3091 int proxyPort = 8080;
3092 if (data.length > 1) {
3093 try {
3094 proxyPort = Integer.parseInt(data[1]);
3095 } catch (NumberFormatException e) {
3096 return;
3097 }
3098 }
Jason Monk207900c2014-04-25 15:00:09 -04003099 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003100 setGlobalProxy(p);
3101 }
3102 }
3103
Jason Monk207900c2014-04-25 15:00:09 -04003104 private void sendProxyBroadcast(ProxyInfo proxy) {
3105 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003106 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003107 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003108 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003109 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3110 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003111 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003112 final long ident = Binder.clearCallingIdentity();
3113 try {
3114 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3115 } finally {
3116 Binder.restoreCallingIdentity(ident);
3117 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003118 }
3119
3120 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003121 final private HashMap<Uri, Integer> mUriEventMap;
3122 final private Context mContext;
3123 final private Handler mHandler;
3124
3125 SettingsObserver(Context context, Handler handler) {
3126 super(null);
3127 mUriEventMap = new HashMap<Uri, Integer>();
3128 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003129 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003130 }
3131
Erik Klineda4bfa82015-04-30 12:58:40 +09003132 void observe(Uri uri, int what) {
3133 mUriEventMap.put(uri, what);
3134 final ContentResolver resolver = mContext.getContentResolver();
3135 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003136 }
3137
3138 @Override
3139 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003140 Slog.wtf(TAG, "Should never be reached.");
3141 }
3142
3143 @Override
3144 public void onChange(boolean selfChange, Uri uri) {
3145 final Integer what = mUriEventMap.get(uri);
3146 if (what != null) {
3147 mHandler.obtainMessage(what.intValue()).sendToTarget();
3148 } else {
3149 loge("No matching event to send for URI=" + uri);
3150 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003151 }
3152 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003153
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003154 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003155 Slog.d(TAG, s);
3156 }
3157
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003158 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003159 Slog.e(TAG, s);
3160 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003161
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003162 private static <T> T checkNotNull(T value, String message) {
3163 if (value == null) {
3164 throw new NullPointerException(message);
3165 }
3166 return value;
3167 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003168
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003169 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003170 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003171 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3172 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3173 *
3174 * @param oldPackage Package name of the application which currently controls VPN, which will
3175 * be replaced. If there is no such application, this should should either be
3176 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3177 * @param newPackage Package name of the application which should gain control of VPN, or
3178 * {@code null} to disable.
3179 * @param userId User for whom to prepare the new VPN.
3180 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003181 * @hide
3182 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003183 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003184 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3185 int userId) {
3186 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003187 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003188
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003189 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003190 Vpn vpn = mVpns.get(userId);
3191 if (vpn != null) {
3192 return vpn.prepare(oldPackage, newPackage);
3193 } else {
3194 return false;
3195 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003196 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003197 }
3198
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003199 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003200 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3201 * This method is used by system-privileged apps.
3202 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3203 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3204 *
3205 * @param packageName The package for which authorization state should change.
3206 * @param userId User for whom {@code packageName} is installed.
3207 * @param authorized {@code true} if this app should be able to start a VPN connection without
3208 * explicit user approval, {@code false} if not.
3209 *
Jeff Davidson05542602014-08-11 14:07:27 -07003210 * @hide
3211 */
3212 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003213 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3214 enforceCrossUserPermission(userId);
3215
Jeff Davidson05542602014-08-11 14:07:27 -07003216 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003217 Vpn vpn = mVpns.get(userId);
3218 if (vpn != null) {
3219 vpn.setPackageAuthorization(packageName, authorized);
3220 }
Jeff Davidson05542602014-08-11 14:07:27 -07003221 }
3222 }
3223
3224 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003225 * Configure a TUN interface and return its file descriptor. Parameters
3226 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003227 * and not available in ConnectivityManager. Permissions are checked in
3228 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003229 * @hide
3230 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003231 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003232 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003233 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003234 int user = UserHandle.getUserId(Binder.getCallingUid());
3235 synchronized(mVpns) {
3236 return mVpns.get(user).establish(config);
3237 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003238 }
3239
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003240 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003241 * Start legacy VPN, controlling native daemons as needed. Creates a
3242 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003243 */
3244 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003245 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003246 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003247 final LinkProperties egress = getActiveLinkProperties();
3248 if (egress == null) {
3249 throw new IllegalStateException("Missing active network connection");
3250 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003251 int user = UserHandle.getUserId(Binder.getCallingUid());
3252 synchronized(mVpns) {
3253 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3254 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003255 }
3256
3257 /**
3258 * Return the information of the ongoing legacy VPN. This method is used
3259 * by VpnSettings and not available in ConnectivityManager. Permissions
3260 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003261 */
3262 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003263 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3264 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003265
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003266 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003267 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003268 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003269 }
3270
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003271 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003272 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3273 * and not available in ConnectivityManager.
3274 */
3275 @Override
3276 public VpnInfo[] getAllVpnInfo() {
3277 enforceConnectivityInternalPermission();
3278 if (mLockdownEnabled) {
3279 return new VpnInfo[0];
3280 }
3281
3282 synchronized(mVpns) {
3283 List<VpnInfo> infoList = new ArrayList<>();
3284 for (int i = 0; i < mVpns.size(); i++) {
3285 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3286 if (info != null) {
3287 infoList.add(info);
3288 }
3289 }
3290 return infoList.toArray(new VpnInfo[infoList.size()]);
3291 }
3292 }
3293
3294 /**
3295 * @return VPN information for accounting, or null if we can't retrieve all required
3296 * information, e.g primary underlying iface.
3297 */
3298 @Nullable
3299 private VpnInfo createVpnInfo(Vpn vpn) {
3300 VpnInfo info = vpn.getVpnInfo();
3301 if (info == null) {
3302 return null;
3303 }
3304 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3305 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3306 // the underlyingNetworks list.
3307 if (underlyingNetworks == null) {
3308 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3309 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3310 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3311 }
3312 } else if (underlyingNetworks.length > 0) {
3313 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3314 if (linkProperties != null) {
3315 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3316 }
3317 }
3318 return info.primaryUnderlyingIface == null ? null : info;
3319 }
3320
3321 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003322 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3323 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003324 * Permissions are checked in Vpn class.
3325 * @hide
3326 */
3327 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003328 public VpnConfig getVpnConfig(int userId) {
3329 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003330 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003331 Vpn vpn = mVpns.get(userId);
3332 if (vpn != null) {
3333 return vpn.getVpnConfig();
3334 } else {
3335 return null;
3336 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003337 }
3338 }
3339
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003340 @Override
3341 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003342 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3343 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3344 return false;
3345 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003346
3347 // Tear down existing lockdown if profile was removed
3348 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3349 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003350 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3351 final VpnProfile profile = VpnProfile.decode(
3352 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003353 if (profile == null) {
3354 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3355 setLockdownTracker(null);
3356 return true;
3357 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003358 int user = UserHandle.getUserId(Binder.getCallingUid());
3359 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003360 Vpn vpn = mVpns.get(user);
3361 if (vpn == null) {
3362 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3363 return false;
3364 }
3365 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003366 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003367 } else {
3368 setLockdownTracker(null);
3369 }
3370
3371 return true;
3372 }
3373
3374 /**
3375 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3376 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3377 */
3378 private void setLockdownTracker(LockdownVpnTracker tracker) {
3379 // Shutdown any existing tracker
3380 final LockdownVpnTracker existing = mLockdownTracker;
3381 mLockdownTracker = null;
3382 if (existing != null) {
3383 existing.shutdown();
3384 }
3385
3386 try {
3387 if (tracker != null) {
3388 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003389 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003390 mLockdownTracker = tracker;
3391 mLockdownTracker.init();
3392 } else {
3393 mNetd.setFirewallEnabled(false);
3394 }
3395 } catch (RemoteException e) {
3396 // ignored; NMS lives inside system_server
3397 }
3398 }
3399
3400 private void throwIfLockdownEnabled() {
3401 if (mLockdownEnabled) {
3402 throw new IllegalStateException("Unavailable in lockdown mode");
3403 }
3404 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003405
Robin Lee244ce8e2016-01-05 18:03:46 +00003406 /**
Robin Lee17e61832016-05-09 13:46:28 +01003407 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3408 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003409 *
Robin Lee17e61832016-05-09 13:46:28 +01003410 * @return {@code true} if the service was started, the service was already connected, or there
3411 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003412 */
Robin Lee17e61832016-05-09 13:46:28 +01003413 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003414 synchronized (mVpns) {
3415 Vpn vpn = mVpns.get(userId);
3416 if (vpn == null) {
3417 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3418 // exists already.
3419 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3420 return false;
3421 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003422
Robin Lee812800c2016-05-13 15:38:08 +01003423 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003424 }
3425 }
3426
3427 @Override
Robin Leedc679712016-05-03 13:23:03 +01003428 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003429 enforceConnectivityInternalPermission();
3430 enforceCrossUserPermission(userId);
3431
3432 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3433 if (LockdownVpnTracker.isEnabled()) {
3434 return false;
3435 }
3436
Robin Lee244ce8e2016-01-05 18:03:46 +00003437 synchronized (mVpns) {
3438 Vpn vpn = mVpns.get(userId);
3439 if (vpn == null) {
3440 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3441 return false;
3442 }
Robin Lee17e61832016-05-09 13:46:28 +01003443 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003444 return false;
3445 }
Robin Lee17e61832016-05-09 13:46:28 +01003446 if (!startAlwaysOnVpn(userId)) {
3447 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003448 return false;
3449 }
Robin Lee17e61832016-05-09 13:46:28 +01003450
Robin Lee812800c2016-05-13 15:38:08 +01003451 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003452 }
3453 return true;
3454 }
3455
3456 @Override
3457 public String getAlwaysOnVpnPackage(int userId) {
3458 enforceConnectivityInternalPermission();
3459 enforceCrossUserPermission(userId);
3460
3461 synchronized (mVpns) {
3462 Vpn vpn = mVpns.get(userId);
3463 if (vpn == null) {
3464 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3465 return null;
3466 }
3467 return vpn.getAlwaysOnPackage();
3468 }
3469 }
3470
Wink Savilleab9321d2013-06-29 21:10:57 -07003471 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003472 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003473 // TODO: Remove? Any reason to trigger a provisioning check?
3474 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003475 }
3476
3477 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003478 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003479
Paul Jensen89e0f092014-09-15 15:59:36 -04003480 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003481 Intent intent = new Intent(action);
3482 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003483 // Concatenate the range of types onto the range of NetIDs.
3484 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003485 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003486 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003487 }
3488
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003489 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003490 * Show or hide network provisioning notifications.
3491 *
3492 * We use notifications for two purposes: to notify that a network requires sign in
3493 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3494 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3495 * particular network we can display the notification type that was most recently requested.
3496 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3497 * might first display NO_INTERNET, and then when the captive portal check completes, display
3498 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003499 *
3500 * @param id an identifier that uniquely identifies this notification. This must match
3501 * between show and hide calls. We use the NetID value but for legacy callers
3502 * we concatenate the range of types with the range of NetIDs.
3503 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003504 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003505 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3506 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003507 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003508 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3509 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003510 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003511 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003512
3513 Resources r = Resources.getSystem();
3514 NotificationManager notificationManager = (NotificationManager) mContext
3515 .getSystemService(Context.NOTIFICATION_SERVICE);
3516
3517 if (visible) {
3518 CharSequence title;
3519 CharSequence details;
3520 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003521 if (notifyType == NotificationType.NO_INTERNET &&
3522 networkType == ConnectivityManager.TYPE_WIFI) {
3523 title = r.getString(R.string.wifi_no_internet, 0);
3524 details = r.getString(R.string.wifi_no_internet_detailed);
3525 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3526 } else if (notifyType == NotificationType.SIGN_IN) {
3527 switch (networkType) {
3528 case ConnectivityManager.TYPE_WIFI:
3529 title = r.getString(R.string.wifi_available_sign_in, 0);
3530 details = r.getString(R.string.network_available_sign_in_detailed,
3531 extraInfo);
3532 icon = R.drawable.stat_notify_wifi_in_range;
3533 break;
3534 case ConnectivityManager.TYPE_MOBILE:
3535 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3536 title = r.getString(R.string.network_available_sign_in, 0);
3537 // TODO: Change this to pull from NetworkInfo once a printable
3538 // name has been added to it
3539 details = mTelephonyManager.getNetworkOperatorName();
3540 icon = R.drawable.stat_notify_rssi_in_range;
3541 break;
3542 default:
3543 title = r.getString(R.string.network_available_sign_in, 0);
3544 details = r.getString(R.string.network_available_sign_in_detailed,
3545 extraInfo);
3546 icon = R.drawable.stat_notify_rssi_in_range;
3547 break;
3548 }
3549 } else {
3550 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3551 + getNetworkTypeName(networkType));
3552 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003553 }
3554
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003555 Notification notification = new Notification.Builder(mContext)
3556 .setWhen(0)
3557 .setSmallIcon(icon)
3558 .setAutoCancel(true)
3559 .setTicker(title)
3560 .setColor(mContext.getColor(
3561 com.android.internal.R.color.system_notification_accent_color))
3562 .setContentTitle(title)
3563 .setContentText(details)
3564 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003565 .setLocalOnly(true)
3566 .setPriority(highPriority ?
3567 Notification.PRIORITY_HIGH :
3568 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003569 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003570 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003571 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003572
Wink Saville948282b2013-08-29 08:55:16 -07003573 try {
Paul Jensenf8e903f2016-06-13 09:39:28 -04003574 notificationManager.notifyAsUser(NOTIFICATION_ID, id, notification, UserHandle.ALL);
Wink Saville948282b2013-08-29 08:55:16 -07003575 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003576 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003577 npe.printStackTrace();
3578 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003579 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003580 try {
Paul Jensenf8e903f2016-06-13 09:39:28 -04003581 notificationManager.cancelAsUser(NOTIFICATION_ID, id, UserHandle.ALL);
Wink Saville948282b2013-08-29 08:55:16 -07003582 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003583 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003584 npe.printStackTrace();
3585 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003586 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003587 }
3588
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003589 /** Location to an updatable file listing carrier provisioning urls.
3590 * An example:
3591 *
3592 * <?xml version="1.0" encoding="utf-8"?>
3593 * <provisioningUrls>
3594 * <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 -07003595 * </provisioningUrls>
3596 */
3597 private static final String PROVISIONING_URL_PATH =
3598 "/data/misc/radio/provisioning_urls.xml";
3599 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003600
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003601 /** XML tag for root element. */
3602 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3603 /** XML tag for individual url */
3604 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003605 /** XML attribute for mcc */
3606 private static final String ATTR_MCC = "mcc";
3607 /** XML attribute for mnc */
3608 private static final String ATTR_MNC = "mnc";
3609
Paul Jensen434dde82015-06-11 09:43:30 -04003610 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003611 FileReader fileReader = null;
3612 XmlPullParser parser = null;
3613 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003614
3615 try {
3616 fileReader = new FileReader(mProvisioningUrlFile);
3617 parser = Xml.newPullParser();
3618 parser.setInput(fileReader);
3619 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3620
3621 while (true) {
3622 XmlUtils.nextElement(parser);
3623
3624 String element = parser.getName();
3625 if (element == null) break;
3626
Paul Jensen434dde82015-06-11 09:43:30 -04003627 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003628 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3629 try {
3630 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3631 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3632 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3633 parser.next();
3634 if (parser.getEventType() == XmlPullParser.TEXT) {
3635 return parser.getText();
3636 }
3637 }
3638 }
3639 } catch (NumberFormatException e) {
3640 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3641 }
3642 }
3643 }
3644 return null;
3645 } catch (FileNotFoundException e) {
3646 loge("Carrier Provisioning Urls file not found");
3647 } catch (XmlPullParserException e) {
3648 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3649 } catch (IOException e) {
3650 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3651 } finally {
3652 if (fileReader != null) {
3653 try {
3654 fileReader.close();
3655 } catch (IOException e) {}
3656 }
3657 }
3658 return null;
3659 }
3660
Wink Saville42d4f082013-07-20 20:31:59 -07003661 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003662 public String getMobileProvisioningUrl() {
3663 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003664 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003665 if (TextUtils.isEmpty(url)) {
3666 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003667 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003668 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003669 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003670 }
Wink Saville8cf35602013-07-10 23:00:07 -07003671 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003672 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003673 String phoneNumber = mTelephonyManager.getLine1Number();
3674 if (TextUtils.isEmpty(phoneNumber)) {
3675 phoneNumber = "0000000000";
3676 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003677 url = String.format(url,
3678 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3679 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003680 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003681 }
3682
Wink Savilleab9321d2013-06-29 21:10:57 -07003683 return url;
3684 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003685
Wink Saville948282b2013-08-29 08:55:16 -07003686 @Override
3687 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003688 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003689 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003690 final long ident = Binder.clearCallingIdentity();
3691 try {
3692 setProvNotificationVisible(visible, networkType, action);
3693 } finally {
3694 Binder.restoreCallingIdentity(ident);
3695 }
Wink Saville948282b2013-08-29 08:55:16 -07003696 }
Wink Saville7788c612013-08-29 14:57:08 -07003697
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003698 @Override
3699 public void setAirplaneMode(boolean enable) {
3700 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003701 final long ident = Binder.clearCallingIdentity();
3702 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003703 final ContentResolver cr = mContext.getContentResolver();
3704 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3705 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3706 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003707 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003708 } finally {
3709 Binder.restoreCallingIdentity(ident);
3710 }
3711 }
3712
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003713 private void onUserStart(int userId) {
3714 synchronized(mVpns) {
3715 Vpn userVpn = mVpns.get(userId);
3716 if (userVpn != null) {
3717 loge("Starting user already has a VPN");
3718 return;
3719 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003720 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003721 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003722
3723 final ContentResolver cr = mContext.getContentResolver();
3724 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3725 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3726 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3727 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3728 if (alwaysOnPackage != null) {
3729 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3730 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003731 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003732 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3733 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003734 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003735 }
3736
3737 private void onUserStop(int userId) {
3738 synchronized(mVpns) {
3739 Vpn userVpn = mVpns.get(userId);
3740 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003741 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003742 return;
3743 }
Robin Lee17e61832016-05-09 13:46:28 +01003744 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003745 mVpns.delete(userId);
3746 }
3747 }
3748
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003749 private void onUserAdded(int userId) {
3750 synchronized(mVpns) {
3751 final int vpnsSize = mVpns.size();
3752 for (int i = 0; i < vpnsSize; i++) {
3753 Vpn vpn = mVpns.valueAt(i);
3754 vpn.onUserAdded(userId);
3755 }
3756 }
3757 }
3758
3759 private void onUserRemoved(int userId) {
3760 synchronized(mVpns) {
3761 final int vpnsSize = mVpns.size();
3762 for (int i = 0; i < vpnsSize; i++) {
3763 Vpn vpn = mVpns.valueAt(i);
3764 vpn.onUserRemoved(userId);
3765 }
3766 }
3767 }
3768
Robin Lee89e7a692016-02-29 14:38:17 +00003769 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003770 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3771 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3772 updateLockdownVpn();
3773 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003774 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003775 }
3776 }
3777
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003778 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3779 @Override
3780 public void onReceive(Context context, Intent intent) {
3781 final String action = intent.getAction();
3782 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3783 if (userId == UserHandle.USER_NULL) return;
3784
Robin Lee323f29d2016-05-04 16:38:06 +01003785 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003786 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003787 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003788 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003789 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3790 onUserAdded(userId);
3791 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3792 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003793 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3794 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003795 }
3796 }
3797 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003798
Robert Greenwalta67be032014-05-16 15:49:14 -07003799 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3800 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003801 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3802 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003803
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003804 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3805 // Map from UID to number of NetworkRequests that UID has filed.
3806 @GuardedBy("mUidToNetworkRequestCount")
3807 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3808
Robert Greenwalta67be032014-05-16 15:49:14 -07003809 private static class NetworkFactoryInfo {
3810 public final String name;
3811 public final Messenger messenger;
3812 public final AsyncChannel asyncChannel;
3813
3814 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3815 this.name = name;
3816 this.messenger = messenger;
3817 this.asyncChannel = asyncChannel;
3818 }
3819 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003820
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003821 /**
3822 * Tracks info about the requester.
3823 * Also used to notice when the calling process dies so we can self-expire
3824 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003825 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003826 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003827 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003828 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003829 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003830 final int mPid;
3831 final int mUid;
3832 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003833
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003834 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003835 request = r;
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003836 ensureRequestHasType();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003837 mPendingIntent = pi;
3838 messenger = null;
3839 mBinder = null;
3840 mPid = getCallingPid();
3841 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003842 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003843 }
3844
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003845 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003846 super();
3847 messenger = m;
3848 request = r;
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003849 ensureRequestHasType();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003850 mBinder = binder;
3851 mPid = getCallingPid();
3852 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003853 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003854 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003855
3856 try {
3857 mBinder.linkToDeath(this, 0);
3858 } catch (RemoteException e) {
3859 binderDied();
3860 }
3861 }
3862
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003863 private void ensureRequestHasType() {
3864 if (request.type == NetworkRequest.Type.NONE) {
3865 throw new IllegalArgumentException(
3866 "All NetworkRequests in ConnectivityService must have a type");
3867 }
3868 }
3869
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003870 private void enforceRequestCountLimit() {
3871 synchronized (mUidToNetworkRequestCount) {
3872 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3873 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3874 throw new IllegalArgumentException("Too many NetworkRequests filed");
3875 }
3876 mUidToNetworkRequestCount.put(mUid, networkRequests);
3877 }
3878 }
3879
Robert Greenwalt9258c642014-03-26 16:47:06 -07003880 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003881 if (mBinder != null) {
3882 mBinder.unlinkToDeath(this, 0);
3883 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003884 }
3885
3886 public void binderDied() {
3887 log("ConnectivityService NetworkRequestInfo binderDied(" +
3888 request + ", " + mBinder + ")");
3889 releaseNetworkRequest(request);
3890 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003891
3892 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003893 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003894 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003895 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003896 }
3897
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003898 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3899 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3900 if (badCapability != null) {
3901 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003902 }
3903 }
3904
Erik Kline9d598e12015-07-13 16:37:51 +09003905 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003906 final SortedSet<Integer> thresholds = new TreeSet();
3907 synchronized (nai) {
3908 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3909 if (nri.request.networkCapabilities.hasSignalStrength() &&
3910 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3911 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3912 }
3913 }
3914 }
Erik Kline9d598e12015-07-13 16:37:51 +09003915 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003916 }
3917
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003918 private void updateSignalStrengthThresholds(
3919 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3920 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003921 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003922 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3923
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003924 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003925 String detail;
3926 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3927 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3928 } else {
3929 detail = reason;
3930 }
3931 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3932 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3933 }
3934
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003935 nai.asyncChannel.sendMessage(
3936 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003937 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003938 }
3939
Robert Greenwalt9258c642014-03-26 16:47:06 -07003940 @Override
3941 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003942 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003943 final NetworkRequest.Type type = (networkCapabilities == null)
3944 ? NetworkRequest.Type.TRACK_DEFAULT
3945 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003946 // If the requested networkCapabilities is null, take them instead from
3947 // the default network request. This allows callers to keep track of
3948 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003949 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003950 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3951 enforceAccessPermission();
3952 } else {
3953 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3954 enforceNetworkRequestPermissions(networkCapabilities);
3955 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003956 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003957 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003958
Robert Greenwalt6078b502014-06-11 16:05:07 -07003959 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003960 throw new IllegalArgumentException("Bad timeout specified");
3961 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003962
Etan Cohenddb9ef02015-11-18 10:56:15 -08003963 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3964 .equals(networkCapabilities.getNetworkSpecifier())) {
3965 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3966 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3967 }
3968
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003969 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003970 nextNetworkRequestId(), type);
3971 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09003972 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003973
3974 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003975 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003976 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003977 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003978 }
3979 return networkRequest;
3980 }
3981
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003982 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003983 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003984 enforceConnectivityInternalPermission();
3985 } else {
3986 enforceChangePermission();
3987 }
3988 }
3989
fenglub15e72b2015-03-20 11:29:56 -07003990 @Override
fengludb571472015-04-21 17:12:05 -07003991 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003992 enforceAccessPermission();
3993 NetworkAgentInfo nai = null;
3994 if (network == null) {
3995 return false;
3996 }
3997 synchronized (mNetworkForNetId) {
3998 nai = mNetworkForNetId.get(network.netId);
3999 }
4000 if (nai != null) {
4001 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4002 return true;
4003 }
4004 return false;
4005 }
4006
Felipe Lemeee27cab2016-06-20 16:36:29 -07004007 private boolean isSystem(int uid) {
4008 return uid < Process.FIRST_APPLICATION_UID;
4009 }
fenglub15e72b2015-03-20 11:29:56 -07004010
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004011 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004012 final int uid = Binder.getCallingUid();
4013 if (isSystem(uid)) {
4014 return;
4015 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004016 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004017 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004018 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004019 synchronized(mRulesLock) {
4020 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4021 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004022 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4023 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004024 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004025 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004026 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004027 }
4028 }
4029 }
4030
Robert Greenwalt9258c642014-03-26 16:47:06 -07004031 @Override
4032 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4033 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004034 checkNotNull(operation, "PendingIntent cannot be null.");
4035 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4036 enforceNetworkRequestPermissions(networkCapabilities);
4037 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004038 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004039
4040 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004041 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4042 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004043 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004044 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4045 nri));
4046 return networkRequest;
4047 }
4048
Jeremy Joslin79294842014-12-03 17:15:28 -08004049 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4050 mHandler.sendMessageDelayed(
4051 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4052 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4053 }
4054
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004055 @Override
4056 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004057 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004058 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4059 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004060 }
4061
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004062 // In order to implement the compatibility measure for pre-M apps that call
4063 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4064 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4065 // This ensures it has permission to do so.
4066 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4067 if (nc == null) {
4068 return false;
4069 }
4070 int[] transportTypes = nc.getTransportTypes();
4071 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4072 return false;
4073 }
4074 try {
4075 mContext.enforceCallingOrSelfPermission(
4076 android.Manifest.permission.ACCESS_WIFI_STATE,
4077 "ConnectivityService");
4078 } catch (SecurityException e) {
4079 return false;
4080 }
4081 return true;
4082 }
4083
Robert Greenwalt9258c642014-03-26 16:47:06 -07004084 @Override
4085 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4086 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004087 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4088 enforceAccessPermission();
4089 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004090
Erik Kline7523eb32015-07-09 18:24:03 +09004091 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004092 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4093 NetworkRequest.Type.LISTEN);
4094 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004095 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004096
4097 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4098 return networkRequest;
4099 }
4100
4101 @Override
4102 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4103 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004104 checkNotNull(operation, "PendingIntent cannot be null.");
4105 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4106 enforceAccessPermission();
4107 }
4108
Erik Kline7523eb32015-07-09 18:24:03 +09004109 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004110 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4111 NetworkRequest.Type.LISTEN);
4112 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004113 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004114
4115 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004116 }
4117
4118 @Override
4119 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004120 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4121 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004122 }
4123
4124 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004125 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004126 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004127 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4128 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004129 }
4130
Robert Greenwalta67be032014-05-16 15:49:14 -07004131 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004132 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004133 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4134 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4135 }
4136
4137 @Override
4138 public void unregisterNetworkFactory(Messenger messenger) {
4139 enforceConnectivityInternalPermission();
4140 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4141 }
4142
4143 private void handleUnregisterNetworkFactory(Messenger messenger) {
4144 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4145 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004146 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004147 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004148 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004149 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004150 }
4151
Robert Greenwalt7b816022014-04-18 15:25:25 -07004152 /**
4153 * NetworkAgentInfo supporting a request by requestId.
4154 * These have already been vetted (their Capabilities satisfy the request)
4155 * and the are the highest scored network available.
4156 * the are keyed off the Requests requestId.
4157 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004158 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004159 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4160 new SparseArray<NetworkAgentInfo>();
4161
Paul Jensen31a94f42015-02-13 14:18:39 -05004162 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4163 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004164 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4165 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004166 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4167 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4168 // there may not be a strict 1:1 correlation between the two.
4169 @GuardedBy("mNetworkForNetId")
4170 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171
Robert Greenwalt7b816022014-04-18 15:25:25 -07004172 // NetworkAgentInfo keyed off its connecting messenger
4173 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004174 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004175 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4176 new HashMap<Messenger, NetworkAgentInfo>();
4177
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004178 @GuardedBy("mBlockedAppUids")
4179 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4180
Paul Jensen2c311d62014-11-17 12:34:51 -05004181 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004182 private final NetworkRequest mDefaultRequest;
4183
Erik Klineda4bfa82015-04-30 12:58:40 +09004184 // Request used to optionally keep mobile data active even when higher
4185 // priority networks like Wi-Fi are active.
4186 private final NetworkRequest mDefaultMobileDataRequest;
4187
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004188 private NetworkAgentInfo getDefaultNetwork() {
4189 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4190 }
4191
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004192 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004193 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004194 }
4195
Paul Jensen31a94f42015-02-13 14:18:39 -05004196 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004197 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004198 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004199 enforceConnectivityInternalPermission();
4200
Paul Jensen2c311d62014-11-17 12:34:51 -05004201 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4202 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004203 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004204 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4205 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004206 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004207 synchronized (this) {
4208 nai.networkMonitor.systemReady = mSystemReady;
4209 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004210 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4211 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004212 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004213 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004214 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004215 }
4216
4217 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4218 if (VDBG) log("Got NetworkAgent Messenger");
4219 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004220 synchronized (mNetworkForNetId) {
4221 mNetworkForNetId.put(na.network.netId, na);
4222 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004223 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4224 NetworkInfo networkInfo = na.networkInfo;
4225 na.networkInfo = null;
4226 updateNetworkInfo(na, networkInfo);
4227 }
4228
4229 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4230 LinkProperties newLp = networkAgent.linkProperties;
4231 int netId = networkAgent.network.netId;
4232
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004233 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4234 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004235 if (networkAgent.clatd != null) {
4236 networkAgent.clatd.fixupLinkProperties(oldLp);
4237 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004238
Paul Jensen992f2522014-04-28 10:33:11 -04004239 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004240 updateMtu(newLp, oldLp);
4241 // TODO - figure out what to do for clat
4242// for (LinkProperties lp : newLp.getStackedLinks()) {
4243// updateMtu(lp, null);
4244// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004245 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004246
Erik Kline94887872016-04-05 13:30:49 +09004247 updateRoutes(newLp, oldLp, netId);
4248 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004249
Paul Jensen3b759822014-05-13 11:44:01 -04004250 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004251 if (isDefaultNetwork(networkAgent)) {
4252 handleApplyDefaultProxy(newLp.getHttpProxy());
4253 } else {
4254 updateProxy(newLp, oldLp, networkAgent);
4255 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004256 // TODO - move this check to cover the whole function
4257 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004258 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004259 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4260 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004261
4262 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004263 }
4264
Lorenzo Colitti95439462014-10-09 13:44:48 +09004265 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4266 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4267 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004268
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004269 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004270 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4271 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004272 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004273 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004274 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004275 }
Paul Jensen992f2522014-04-28 10:33:11 -04004276
4277 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4278 CompareResult<String> interfaceDiff = new CompareResult<String>();
4279 if (oldLp != null) {
4280 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4281 } else if (newLp != null) {
4282 interfaceDiff.added = newLp.getAllInterfaceNames();
4283 }
4284 for (String iface : interfaceDiff.added) {
4285 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004286 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004287 mNetd.addInterfaceToNetwork(iface, netId);
4288 } catch (Exception e) {
4289 loge("Exception adding interface: " + e);
4290 }
4291 }
4292 for (String iface : interfaceDiff.removed) {
4293 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004294 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004295 mNetd.removeInterfaceFromNetwork(iface, netId);
4296 } catch (Exception e) {
4297 loge("Exception removing interface: " + e);
4298 }
4299 }
4300 }
4301
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004302 /**
4303 * Have netd update routes from oldLp to newLp.
4304 * @return true if routes changed between oldLp and newLp
4305 */
4306 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004307 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4308 if (oldLp != null) {
4309 routeDiff = oldLp.compareAllRoutes(newLp);
4310 } else if (newLp != null) {
4311 routeDiff.added = newLp.getAllRoutes();
4312 }
4313
4314 // add routes before removing old in case it helps with continuous connectivity
4315
4316 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4317 for (RouteInfo route : routeDiff.added) {
4318 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004319 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004320 try {
4321 mNetd.addRoute(netId, route);
4322 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004323 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4324 loge("Exception in addRoute for non-gateway: " + e);
4325 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004326 }
4327 }
4328 for (RouteInfo route : routeDiff.added) {
4329 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004330 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004331 try {
4332 mNetd.addRoute(netId, route);
4333 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004334 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4335 loge("Exception in addRoute for gateway: " + e);
4336 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004337 }
4338 }
4339
4340 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004341 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004342 try {
4343 mNetd.removeRoute(netId, route);
4344 } catch (Exception e) {
4345 loge("Exception in removeRoute: " + e);
4346 }
4347 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004348 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004349 }
Erik Kline41368502015-06-17 13:19:54 +09004350
Erik Kline94887872016-04-05 13:30:49 +09004351 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4352 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4353 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004354 }
Erik Kline94887872016-04-05 13:30:49 +09004355
4356 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004357 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004358 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004359 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004360 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4361 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004362 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004363 }
4364 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4365 if (defaultNai != null && defaultNai.network.netId == netId) {
4366 setDefaultDnsSystemProperties(dnses);
4367 }
4368 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004369 }
4370
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004371 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4372 int last = 0;
4373 for (InetAddress dns : dnses) {
4374 ++last;
4375 String key = "net.dns" + last;
4376 String value = dns.getHostAddress();
4377 SystemProperties.set(key, value);
4378 }
4379 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4380 String key = "net.dns" + i;
4381 SystemProperties.set(key, "");
4382 }
4383 mNumDnsEntries = last;
4384 }
4385
Paul Jensen3d194ea2015-06-16 14:27:36 -04004386 /**
4387 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4388 * augmented with any stateful capabilities implied from {@code networkAgent}
4389 * (e.g., validated status and captive portal status).
4390 *
Paul Jensene0988542015-06-25 15:30:08 -04004391 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004392 * @param networkCapabilities the new network capabilities.
4393 */
Paul Jensene0988542015-06-25 15:30:08 -04004394 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004395 // Don't modify caller's NetworkCapabilities.
4396 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004397 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004398 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4399 } else {
4400 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4401 }
Paul Jensene0988542015-06-25 15:30:08 -04004402 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004403 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4404 } else {
4405 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4406 }
Paul Jensene0988542015-06-25 15:30:08 -04004407 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4408 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004409 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4410 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4411 try {
4412 mNetd.setNetworkPermission(nai.network.netId,
4413 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4414 null : NetworkManagementService.PERMISSION_SYSTEM);
4415 } catch (RemoteException e) {
4416 loge("Exception in setNetworkPermission: " + e);
4417 }
4418 }
Paul Jensene0988542015-06-25 15:30:08 -04004419 synchronized (nai) {
4420 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004421 }
Paul Jensene0988542015-06-25 15:30:08 -04004422 rematchAllNetworksAndRequests(nai, oldScore);
4423 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004424 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004425 }
4426
Paul Jensenc8b9a742014-09-30 15:37:41 -04004427 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004428 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4429 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004430 // Don't send listening requests to factories. b/17393458
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004431 if (!nr.isRequest()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004432 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4433 }
4434 }
4435
Robert Greenwalt7b816022014-04-18 15:25:25 -07004436 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4437 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004438 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004439 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4440 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004441 }
4442 }
4443
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004444 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4445 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004446 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004447 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004448 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4449 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004450 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004451 sendIntent(nri.mPendingIntent, intent);
4452 }
4453 // else not handled
4454 }
4455
4456 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4457 mPendingIntentWakeLock.acquire();
4458 try {
4459 if (DBG) log("Sending " + pendingIntent);
4460 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4461 } catch (PendingIntent.CanceledException e) {
4462 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4463 mPendingIntentWakeLock.release();
4464 releasePendingNetworkRequest(pendingIntent);
4465 }
4466 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4467 }
4468
4469 @Override
4470 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4471 String resultData, Bundle resultExtras) {
4472 if (DBG) log("Finished sending " + pendingIntent);
4473 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004474 // Release with a delay so the receiving client has an opportunity to put in its
4475 // own request.
4476 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004477 }
4478
Robert Greenwalt9258c642014-03-26 16:47:06 -07004479 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004480 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004481 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004482 Bundle bundle = new Bundle();
4483 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4484 new NetworkRequest(nri.request));
4485 Message msg = Message.obtain();
4486 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4487 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4488 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4489 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004490 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004491 case ConnectivityManager.CALLBACK_LOSING: {
4492 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4493 break;
4494 }
4495 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4496 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4497 new NetworkCapabilities(networkAgent.networkCapabilities));
4498 break;
4499 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004500 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004501 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4502 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004503 break;
4504 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004505 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004506 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004507 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004508 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004509 if (VDBG) {
4510 log("sending notification " + notifyTypeToName(notificationType) +
4511 " for " + nri.request);
4512 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004513 nri.messenger.send(msg);
4514 } catch (RemoteException e) {
4515 // may occur naturally in the race of binder death.
4516 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4517 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004518 }
4519
Paul Jensenc8b9a742014-09-30 15:37:41 -04004520 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004521 if (nai.numRequestNetworkRequests() != 0) {
4522 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4523 NetworkRequest nr = nai.requestAt(i);
4524 // Ignore listening requests.
4525 if (!nr.isRequest()) continue;
4526 loge("Dead network still had at least " + nr);
4527 break;
4528 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004529 }
4530 nai.asyncChannel.disconnect();
4531 }
4532
Robert Greenwalt7b816022014-04-18 15:25:25 -07004533 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4534 if (oldNetwork == null) {
4535 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4536 return;
4537 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004538 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4539 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004540 }
4541
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004542 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004543 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004544 setupDataActivityTracking(newNetwork);
4545 try {
4546 mNetd.setDefaultNetId(newNetwork.network.netId);
4547 } catch (Exception e) {
4548 loge("Exception setting default network :" + e);
4549 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004550 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004551 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004552 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004553 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004554 }
4555
Paul Jensen2161a8e2014-09-11 11:00:39 -04004556 // Handles a network appearing or improving its score.
4557 //
4558 // - Evaluates all current NetworkRequests that can be
4559 // satisfied by newNetwork, and reassigns to newNetwork
4560 // any such requests for which newNetwork is the best.
4561 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004562 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004563 // needed. A network is needed if it is the best network for
4564 // one or more NetworkRequests, or if it is a VPN.
4565 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004566 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004567 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004568 //
4569 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4570 // networks that have no chance (i.e. even if validated)
4571 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004572 //
4573 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4574 // it does not remove NetworkRequests that other Networks could better satisfy.
4575 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4576 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4577 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004578 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004579 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004580 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4581 // performed to tear down unvalidated networks that have no chance (i.e. even if
4582 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004583 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004584 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Robin Lee585e2482016-05-01 23:00:00 +01004585 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004586 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004587 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004588 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004589 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004590 // Find and migrate to this Network any NetworkRequests for
4591 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004592 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004593 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004594 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004595 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004596 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4597 final boolean satisfies = newNetwork.satisfies(nri.request);
4598 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004599 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004600 log("Network " + newNetwork.name() + " was already satisfying" +
4601 " request " + nri.request.requestId + ". No change.");
4602 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004603 keep = true;
4604 continue;
4605 }
4606
4607 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004608 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004609 if (satisfies) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004610 if (!nri.request.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004611 // This is not a request, it's a callback listener.
4612 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004613 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004614 continue;
4615 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004616
Robert Greenwalt7b816022014-04-18 15:25:25 -07004617 // next check if it's better than any current network we're using for
4618 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004619 if (VDBG) {
4620 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004621 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4622 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004623 }
4624 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004625 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004626 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004627 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004628 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004629 currentNetwork.removeRequest(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004630 currentNetwork.networkLingered.add(nri.request);
4631 affectedNetworks.add(currentNetwork);
4632 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004633 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004634 }
Paul Jensen573a0352015-01-08 10:49:34 -05004635 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004636 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004637 if (!newNetwork.addRequest(nri.request)) {
4638 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4639 }
4640 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004641 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004642 // Tell NetworkFactories about the new score, so they can stop
4643 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004644 // TODO - this could get expensive if we have alot of requests for this
4645 // network. Think about if there is a way to reduce this. Push
4646 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004647 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004648 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004649 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004650 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004651 }
4652 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004653 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004654 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4655 // mark it as no longer satisfying "nri". Because networks are processed by
4656 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4657 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4658 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4659 // This means this code doesn't have to handle the case where "currentNetwork" no
4660 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4661 if (DBG) {
4662 log("Network " + newNetwork.name() + " stopped satisfying" +
4663 " request " + nri.request.requestId);
4664 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004665 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004666 if (currentNetwork == newNetwork) {
4667 mNetworkForRequestId.remove(nri.request.requestId);
4668 sendUpdatedScoreToFactories(nri.request, 0);
4669 } else {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004670 if (nri.request.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004671 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4672 newNetwork.name() +
4673 " without updating mNetworkForRequestId or factories!");
4674 }
4675 }
4676 // TODO: technically, sending CALLBACK_LOST here is
4677 // incorrect if nri is a request (not a listen) and there
4678 // is a replacement network currently connected that can
4679 // satisfy it. However, the only capability that can both
4680 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4681 // so this code is only incorrect for a network that loses
4682 // the TRUSTED capability, which is a rare case.
4683 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004684 }
4685 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004686 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004687 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004688 if (nai.lingering) {
4689 // Already lingered. Nothing to do. This can only happen if "nai" is in
4690 // "affectedNetworks" twice. The reasoning being that to get added to
4691 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4692 // (i.e. not lingered) so it could have only been lingered by this loop.
4693 // unneeded(nai) will be false and we'll call unlinger() below which would
4694 // be bad, so handle it here.
4695 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004696 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004697 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004698 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004699 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004700 }
4701 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004702 if (isNewDefault) {
4703 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004704 makeDefault(newNetwork);
4705 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4706 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004707 synchronized (ConnectivityService.this) {
4708 // have a new default network, release the transition wakelock in
4709 // a second if it's held. The second pause is to allow apps
4710 // to reconnect over the new network
4711 if (mNetTransitionWakeLock.isHeld()) {
4712 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4713 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4714 mNetTransitionWakeLockSerialNumber, 0),
4715 1000);
4716 }
4717 }
4718 }
4719
4720 // do this after the default net is switched, but
4721 // before LegacyTypeTracker sends legacy broadcasts
4722 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4723
4724 if (isNewDefault) {
4725 // Maintain the illusion: since the legacy API only
4726 // understands one network at a time, we must pretend
4727 // that the current default network disconnected before
4728 // the new one connected.
4729 if (oldDefaultNetwork != null) {
4730 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4731 oldDefaultNetwork, true);
4732 }
4733 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4734 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4735 notifyLockdownVpn(newNetwork);
4736 }
4737
Robert Greenwalt7b816022014-04-18 15:25:25 -07004738 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004739 // Notify battery stats service about this network, both the normal
4740 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004741 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004742 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004743 final IBatteryStats bs = BatteryStatsService.getService();
4744 final int type = newNetwork.networkInfo.getType();
4745
4746 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4747 bs.noteNetworkInterfaceType(baseIface, type);
4748 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4749 final String stackedIface = stacked.getInterfaceName();
4750 bs.noteNetworkInterfaceType(stackedIface, type);
4751 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4752 }
4753 } catch (RemoteException ignored) {
4754 }
4755
Robert Greenwalt152ed372014-12-17 17:19:53 -08004756 // This has to happen after the notifyNetworkCallbacks as that tickles each
4757 // ConnectivityManager instance so that legacy requests correctly bind dns
4758 // requests to this network. The legacy users are listening for this bcast
4759 // and will generally do a dns request so they can ensureRouteToHost and if
4760 // they do that before the callbacks happen they'll use the default network.
4761 //
4762 // TODO: Is there still a race here? We send the broadcast
4763 // after sending the callback, but if the app can receive the
4764 // broadcast before the callback, it might still break.
4765 //
4766 // This *does* introduce a race where if the user uses the new api
4767 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4768 // they may get old info. Reverse this after the old startUsing api is removed.
4769 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004770 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4771 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004772 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004773 // legacy type tracker filters out repeat adds
4774 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4775 }
4776 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004777
4778 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4779 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4780 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4781 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4782 if (newNetwork.isVPN()) {
4783 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4784 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004785 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004786 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4787 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004788 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004789 if (DBG) log("Reaping " + nai.name());
4790 teardownUnneededNetwork(nai);
4791 }
4792 }
4793 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004794 }
4795
Paul Jensen1c7ba022015-06-16 14:27:36 -04004796 /**
4797 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4798 * being disconnected.
4799 * @param changed If only one Network's score or capabilities have been modified since the last
4800 * time this function was called, pass this Network in this argument, otherwise pass
4801 * null.
4802 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4803 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4804 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4805 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4806 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004807 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004808 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004809 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4810 // to avoid the slowness. It is not simply enough to process just "changed", for
4811 // example in the case where "changed"'s score decreases and another network should begin
4812 // satifying a NetworkRequest that "changed" currently satisfies.
4813
4814 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4815 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4816 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004817 if (changed != null && oldScore < changed.getCurrentScore()) {
4818 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004819 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004820 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4821 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4822 // Rematch higher scoring networks first to prevent requests first matching a lower
4823 // scoring network and then a higher scoring network, which could produce multiple
4824 // callbacks and inadvertently unlinger networks.
4825 Arrays.sort(nais);
4826 for (NetworkAgentInfo nai : nais) {
4827 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004828 // Only reap the last time through the loop. Reaping before all rematching
4829 // is complete could incorrectly teardown a network that hasn't yet been
4830 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004831 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004832 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004833 }
4834 }
4835 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004836
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004837 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004838 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004839 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004840 // For now only update icons for default connection.
4841 // TODO: Update WiFi and cellular icons separately. b/17237507
4842 if (!isDefaultNetwork(nai)) return;
4843
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004844 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004845 // Don't repeat publish.
4846 if (newInetCondition == mDefaultInetConditionPublished) return;
4847
4848 mDefaultInetConditionPublished = newInetCondition;
4849 sendInetConditionBroadcast(nai.networkInfo);
4850 }
4851
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004852 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4853 if (mLockdownTracker != null) {
4854 if (nai != null && nai.isVPN()) {
4855 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4856 } else {
4857 mLockdownTracker.onNetworkInfoChanged();
4858 }
4859 }
4860 }
4861
Robert Greenwalt7b816022014-04-18 15:25:25 -07004862 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4863 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004864 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004865 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004866 synchronized (networkAgent) {
4867 oldInfo = networkAgent.networkInfo;
4868 networkAgent.networkInfo = newInfo;
4869 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004870 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004871
4872 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004873 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4874 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4875 notifyIfacesChangedForNetworkStats();
4876 } else if (VDBG) log("ignoring duplicate network state non-change");
4877 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004878 return;
4879 }
4880 if (DBG) {
4881 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4882 (oldInfo == null ? "null" : oldInfo.getState()) +
4883 " to " + state);
4884 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004885
Robin Lee585e2482016-05-01 23:00:00 +01004886 if (!networkAgent.created
4887 && (state == NetworkInfo.State.CONNECTED
4888 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004889 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004890 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004891 if (networkAgent.isVPN()) {
4892 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004893 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4894 (networkAgent.networkMisc == null ||
4895 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004896 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004897 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4898 networkAgent.networkCapabilities.hasCapability(
4899 NET_CAPABILITY_NOT_RESTRICTED) ?
4900 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004901 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004902 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004903 loge("Error creating network " + networkAgent.network.netId + ": "
4904 + e.getMessage());
4905 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004906 }
Paul Jenseneec75412014-08-04 12:21:19 -04004907 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004908 }
4909
4910 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4911 networkAgent.everConnected = true;
4912
Robert Greenwalt7b816022014-04-18 15:25:25 -07004913 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004914 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004915
Paul Jensenca8f16a2014-05-09 12:47:55 -04004916 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004917 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004918
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004919 if (networkAgent.isVPN()) {
4920 // Temporarily disable the default proxy (not global).
4921 synchronized (mProxyLock) {
4922 if (!mDefaultProxyDisabled) {
4923 mDefaultProxyDisabled = true;
4924 if (mGlobalProxy == null && mDefaultProxy != null) {
4925 sendProxyBroadcast(null);
4926 }
4927 }
4928 }
4929 // TODO: support proxy per network.
4930 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004931
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004932 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4933 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4934 // capabilities, so it only needs to be done once on initial connect, not every time the
4935 // network's capabilities change. Note that we do this before rematching the network,
4936 // so we could decide to tear it down immediately afterwards. That's fine though - on
4937 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4938 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004939 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004940
Paul Jensen2161a8e2014-09-11 11:00:39 -04004941 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004942 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004943
4944 // This has to happen after matching the requests, because callbacks are just requests.
4945 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004946 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004947 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004948 if (networkAgent.isVPN()) {
4949 synchronized (mProxyLock) {
4950 if (mDefaultProxyDisabled) {
4951 mDefaultProxyDisabled = false;
4952 if (mGlobalProxy == null && mDefaultProxy != null) {
4953 sendProxyBroadcast(mDefaultProxy);
4954 }
4955 }
4956 }
4957 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004958 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4959 state == NetworkInfo.State.SUSPENDED) {
4960 // going into or coming out of SUSPEND: rescore and notify
4961 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004962 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004963 }
4964 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4965 ConnectivityManager.CALLBACK_SUSPENDED :
4966 ConnectivityManager.CALLBACK_RESUMED));
4967 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004968 }
4969 }
4970
Robert Greenwaltac96c522014-06-03 16:43:57 -07004971 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004972 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004973 if (score < 0) {
4974 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4975 "). Bumping score to min of 0");
4976 score = 0;
4977 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004978
Paul Jensen2161a8e2014-09-11 11:00:39 -04004979 final int oldScore = nai.getCurrentScore();
4980 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004981
Paul Jensen85cf78e2015-06-25 13:25:07 -04004982 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004983
Paul Jensenc8b9a742014-09-30 15:37:41 -04004984 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004985 }
4986
Robert Greenwalt9258c642014-03-26 16:47:06 -07004987 // notify only this one new request of the current state
4988 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4989 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4990 // TODO - read state from monitor to decide what to send.
4991// if (nai.networkMonitor.isLingering()) {
4992// notifyType = NetworkCallbacks.LOSING;
4993// } else if (nai.networkMonitor.isEvaluating()) {
4994// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4995// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004996 if (nri.mPendingIntent == null) {
4997 callCallbackForRequest(nri, nai, notifyType);
4998 } else {
4999 sendPendingIntentForRequest(nri, nai, notifyType);
5000 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005001 }
5002
Robert Greenwalt8d482522015-06-24 13:23:42 -07005003 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005004 // The NetworkInfo we actually send out has no bearing on the real
5005 // state of affairs. For example, if the default connection is mobile,
5006 // and a request for HIPRI has just gone away, we need to pretend that
5007 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5008 // the state to DISCONNECTED, even though the network is of type MOBILE
5009 // and is still connected.
5010 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5011 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005012 if (state != DetailedState.DISCONNECTED) {
5013 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005014 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005015 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005016 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005017 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5018 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5019 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5020 if (info.isFailover()) {
5021 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5022 nai.networkInfo.setFailover(false);
5023 }
5024 if (info.getReason() != null) {
5025 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5026 }
5027 if (info.getExtraInfo() != null) {
5028 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5029 }
5030 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005031 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005032 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005033 if (newDefaultAgent != null) {
5034 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5035 newDefaultAgent.networkInfo);
5036 } else {
5037 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5038 }
5039 }
5040 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5041 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005042 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005043 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005044 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005045 }
5046 }
5047 }
5048
Robert Greenwalt7b816022014-04-18 15:25:25 -07005049 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005050 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005051 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5052 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005053 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5054 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005055 if (nri.mPendingIntent == null) {
5056 callCallbackForRequest(nri, networkAgent, notifyType);
5057 } else {
5058 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5059 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005060 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005061 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005062
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005063 private String notifyTypeToName(int notifyType) {
5064 switch (notifyType) {
5065 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5066 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5067 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5068 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5069 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5070 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5071 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5072 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5073 }
5074 return "UNKNOWN";
5075 }
5076
Jeff Sharkey69736342014-12-08 14:50:12 -08005077 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005078 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5079 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005080 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005081 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005082 try {
5083 mStatsService.forceUpdateIfaces();
5084 } catch (Exception ignored) {
5085 }
5086 }
5087
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005088 @Override
5089 public boolean addVpnAddress(String address, int prefixLength) {
5090 throwIfLockdownEnabled();
5091 int user = UserHandle.getUserId(Binder.getCallingUid());
5092 synchronized (mVpns) {
5093 return mVpns.get(user).addAddress(address, prefixLength);
5094 }
5095 }
5096
5097 @Override
5098 public boolean removeVpnAddress(String address, int prefixLength) {
5099 throwIfLockdownEnabled();
5100 int user = UserHandle.getUserId(Binder.getCallingUid());
5101 synchronized (mVpns) {
5102 return mVpns.get(user).removeAddress(address, prefixLength);
5103 }
5104 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005105
5106 @Override
5107 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5108 throwIfLockdownEnabled();
5109 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005110 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005111 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005112 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005113 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005114 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005115 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005116 }
5117 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005118 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005119
5120 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005121 public String getCaptivePortalServerUrl() {
5122 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5123 }
5124
5125 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005126 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5127 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5128 enforceKeepalivePermission();
5129 mKeepaliveTracker.startNattKeepalive(
5130 getNetworkAgentInfoForNetwork(network),
5131 intervalSeconds, messenger, binder,
5132 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5133 }
5134
5135 @Override
5136 public void stopKeepalive(Network network, int slot) {
5137 mHandler.sendMessage(mHandler.obtainMessage(
5138 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5139 }
5140
5141 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005142 public void factoryReset() {
5143 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005144
5145 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5146 return;
5147 }
5148
Robin Lee3b3dd942015-05-12 18:14:58 +01005149 final int userId = UserHandle.getCallingUserId();
5150
Stuart Scottf1fb3972015-04-02 18:00:02 -07005151 // Turn airplane mode off
5152 setAirplaneMode(false);
5153
Stuart Scotte3e314d2015-04-20 14:07:45 -07005154 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5155 // Untether
5156 for (String tether : getTetheredIfaces()) {
5157 untether(tether);
5158 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005159 }
5160
Stuart Scotte3e314d2015-04-20 14:07:45 -07005161 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005162 // Remove always-on package
5163 synchronized (mVpns) {
5164 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5165 if (alwaysOnPackage != null) {
5166 setAlwaysOnVpnPackage(userId, null, false);
5167 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5168 }
5169 }
5170
Stuart Scotte3e314d2015-04-20 14:07:45 -07005171 // Turn VPN off
5172 VpnConfig vpnConfig = getVpnConfig(userId);
5173 if (vpnConfig != null) {
5174 if (vpnConfig.legacy) {
5175 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5176 } else {
5177 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5178 // in the future without user intervention.
5179 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005180
Victor Changb04a5ea2016-05-30 20:36:30 +01005181 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005182 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005183 }
5184 }
5185 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005186
5187 @VisibleForTesting
5188 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5189 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5190 return new NetworkMonitor(context, handler, nai, defaultRequest);
5191 }
Erik Kline48f12f22016-04-14 17:30:59 +09005192
Hugo Benichicfddd682016-05-31 16:28:06 +09005193 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005194 int newNetid = NETID_UNSET;
5195 int prevNetid = NETID_UNSET;
5196 int[] transports = new int[0];
5197 boolean hadIPv4 = false;
5198 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005199
Hugo Benichi5f16f762016-04-20 12:09:33 +09005200 if (newNai != null) {
5201 newNetid = newNai.network.netId;
5202 transports = newNai.networkCapabilities.getTransportTypes();
5203 }
5204 if (prevNai != null) {
5205 prevNetid = prevNai.network.netId;
5206 final LinkProperties lp = prevNai.linkProperties;
5207 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5208 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5209 }
5210
Hugo Benichicfddd682016-05-31 16:28:06 +09005211 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5212 }
5213
5214 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5215 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217}