blob: 1a7a2bf88a883b5da3990182ff9891868ff44fcd [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);
Erik Kline7523eb32015-07-09 18:24:03 +0900659 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
Erik Kline371c7b72016-03-22 17:04:20 +0900660 new Binder(), NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +0900661 mNetworkRequests.put(mDefaultRequest, defaultNRI);
662 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900663
664 mDefaultMobileDataRequest = createInternetRequestForTransport(
665 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700666
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900667 mHandlerThread = createHandlerThread();
668 mHandlerThread.start();
669 mHandler = new InternalHandler(mHandlerThread.getLooper());
670 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700671
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800672 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800673 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
674 String id = Settings.Secure.getString(context.getContentResolver(),
675 Settings.Secure.ANDROID_ID);
676 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700677 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800678 SystemProperties.set("net.hostname", name);
679 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800680 }
681
Jeremy Joslin79294842014-12-03 17:15:28 -0800682 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
683 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
684
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700685 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700686 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800687 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700688 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700689 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700690 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700691
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700692 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600693 mPolicyManager.setConnectivityListener(mPolicyListener);
694 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700695 } catch (RemoteException e) {
696 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700697 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700698 }
699
700 final PowerManager powerManager = (PowerManager) context.getSystemService(
701 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700702 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
703 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
704 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800705 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700706
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700707 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700708
Wink Saville51f456f2013-04-23 14:26:51 -0700709 // TODO: What is the "correct" way to do determine if this is a wifi only device?
710 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
711 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700712 String[] naStrings = context.getResources().getStringArray(
713 com.android.internal.R.array.networkAttributes);
714 for (String naString : naStrings) {
715 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700716 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700717 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700718 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800719 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700720 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700721 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700722 }
Wink Saville51f456f2013-04-23 14:26:51 -0700723 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
724 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
725 n.type);
726 continue;
727 }
Wink Saville975c8482011-04-07 14:23:45 -0700728 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800729 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700730 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700731 continue;
732 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700733 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700734
Wink Saville975c8482011-04-07 14:23:45 -0700735 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700736 mNetworksDefined++;
737 } catch(Exception e) {
738 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700739 }
740 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700741
742 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
743 if (mNetConfigs[TYPE_VPN] == null) {
744 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
745 // don't need to add TYPE_VPN to mNetConfigs.
746 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
747 mNetworksDefined++; // used only in the log() statement below.
748 }
749
Wink Saville5e56bc52013-07-29 15:00:57 -0700750 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700751
Robert Greenwalt50393202011-06-21 17:26:14 -0700752 mProtectedNetworks = new ArrayList<Integer>();
753 int[] protectedNetworks = context.getResources().getIntArray(
754 com.android.internal.R.array.config_protectedNetworks);
755 for (int p : protectedNetworks) {
756 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
757 mProtectedNetworks.add(p);
758 } else {
759 if (DBG) loge("Ignoring protectedNetwork " + p);
760 }
761 }
762
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700763 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
764 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700765
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800766 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800767
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700768 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
769
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700770 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700771 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100772 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700773 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700774 intentFilter.addAction(Intent.ACTION_USER_ADDED);
775 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000776 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700777 mContext.registerReceiverAsUser(
778 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900779
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700780 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700781 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700782 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700783 } catch (RemoteException e) {
784 loge("Error registering observer :" + e);
785 }
786
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700787 if (DBG) {
788 mInetLog = new ArrayList();
789 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700790
Erik Klineda4bfa82015-04-30 12:58:40 +0900791 mSettingsObserver = new SettingsObserver(mContext, mHandler);
792 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800793
John Spurlockbf991a82013-06-24 14:20:23 -0400794 mDataConnectionStats = new DataConnectionStats(mContext);
795 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400796
Jason Monkdecd2952013-10-10 14:02:51 -0400797 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700798
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400799 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900800
801 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700803
Erik Klineda4bfa82015-04-30 12:58:40 +0900804 private NetworkRequest createInternetRequestForTransport(int transportType) {
805 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900806 netCap.addCapability(NET_CAPABILITY_INTERNET);
807 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900808 if (transportType > -1) {
809 netCap.addTransportType(transportType);
810 }
811 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
812 }
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(
Erik Kline371c7b72016-03-22 17:04:20 +0900835 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
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();
1907 for (int i = 0; i < nai.networkRequests.size(); i++) {
1908 pw.println(nai.networkRequests.valueAt(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
Paul Jensenc8b9a742014-09-30 15:37:41 -04002017 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09002018 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04002019 }
2020
Robert Greenwalt42acef32009-08-12 16:08:25 -07002021 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002022 private class NetworkStateTrackerHandler extends Handler {
2023 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002024 super(looper);
2025 }
2026
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002027 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002029 default:
2030 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002031 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002032 handleAsyncChannelHalfConnect(msg);
2033 break;
2034 }
2035 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2036 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2037 if (nai != null) nai.asyncChannel.disconnect();
2038 break;
2039 }
2040 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2041 handleAsyncChannelDisconnected(msg);
2042 break;
2043 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002044 }
2045 return true;
2046 }
2047
2048 private void maybeHandleNetworkAgentMessage(Message msg) {
2049 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2050 if (nai == null) {
2051 if (VDBG) {
2052 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2053 log(String.format("%s from unknown NetworkAgent", what));
2054 }
2055 return;
2056 }
2057
2058 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002059 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002060 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2061 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2062 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2063 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002064 }
Robin Lee585e2482016-05-01 23:00:00 +01002065 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002066 networkCapabilities)) {
2067 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2068 + nai.networkCapabilities + " -> " + networkCapabilities);
2069 }
2070 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002071 break;
2072 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002073 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002074 if (VDBG) {
2075 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002076 "; created=" + nai.created +
2077 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002078 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002079 LinkProperties oldLp = nai.linkProperties;
2080 synchronized (nai) {
2081 nai.linkProperties = (LinkProperties)msg.obj;
2082 }
Robin Lee585e2482016-05-01 23:00:00 +01002083 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002084 break;
2085 }
2086 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002087 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002088 updateNetworkInfo(nai, info);
2089 break;
2090 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002091 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002092 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002093 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002094 break;
2095 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002096 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002097 try {
2098 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002099 } catch (Exception e) {
2100 // Never crash!
2101 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002102 }
2103 break;
2104 }
2105 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002106 try {
2107 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002108 } catch (Exception e) {
2109 // Never crash!
2110 loge("Exception in removeVpnUidRanges: " + e);
2111 }
2112 break;
2113 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002114 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002115 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2116 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002117 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002118 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002119 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002120 break;
2121 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002122 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002123 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2124 break;
2125 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002126 }
2127 }
2128
2129 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2130 switch (msg.what) {
2131 default:
2132 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002133 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002134 final NetworkAgentInfo nai;
2135 synchronized (mNetworkForNetId) {
2136 nai = mNetworkForNetId.get(msg.arg2);
2137 }
2138 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002139 final boolean valid =
2140 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002141 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2142 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002143 if (valid != nai.lastValidated) {
2144 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002145 nai.lastValidated = valid;
2146 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002147 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002148 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2149 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002150 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002151 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002152 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002153 Bundle redirectUrlBundle = new Bundle();
2154 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002155 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002156 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002157 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002158 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002159 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002160 break;
2161 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002162 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002163 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002164 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002165 handleLingerComplete(nai);
2166 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002167 break;
2168 }
Paul Jensen869868be2014-05-15 10:33:05 -04002169 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002170 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002171 final boolean visible = (msg.arg1 != 0);
2172 final NetworkAgentInfo nai;
2173 synchronized (mNetworkForNetId) {
2174 nai = mNetworkForNetId.get(netId);
2175 }
2176 // If captive portal status has changed, update capabilities.
2177 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2178 nai.lastCaptivePortalDetected = visible;
2179 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002180 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002181 }
2182 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002183 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002184 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002185 if (nai == null) {
2186 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2187 break;
2188 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002189 if (!nai.networkMisc.provisioningNotificationDisabled) {
2190 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
2191 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2192 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
2193 }
Paul Jensen869868be2014-05-15 10:33:05 -04002194 }
Paul Jensen869868be2014-05-15 10:33:05 -04002195 break;
2196 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002197 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002198 return true;
2199 }
2200
2201 @Override
2202 public void handleMessage(Message msg) {
2203 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2204 maybeHandleNetworkAgentMessage(msg);
2205 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002206 }
2207 }
2208
Paul Jensen85cf78e2015-06-25 13:25:07 -04002209 private void linger(NetworkAgentInfo nai) {
2210 nai.lingering = true;
Hugo Benichicfddd682016-05-31 16:28:06 +09002211 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002212 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2213 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2214 }
2215
Paul Jensen0cc17322014-11-25 15:26:53 -05002216 // Cancel any lingering so the linger timeout doesn't teardown a network.
2217 // This should be called when a network begins satisfying a NetworkRequest.
2218 // Note: depending on what state the NetworkMonitor is in (e.g.,
2219 // if it's awaiting captive portal login, or if validation failed), this
2220 // may trigger a re-evaluation of the network.
2221 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002222 nai.networkLingered.clear();
2223 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002224 nai.lingering = false;
Hugo Benichicfddd682016-05-31 16:28:06 +09002225 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Paul Jensen0cc17322014-11-25 15:26:53 -05002226 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002227 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2228 }
2229
Robert Greenwalt7b816022014-04-18 15:25:25 -07002230 private void handleAsyncChannelHalfConnect(Message msg) {
2231 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002232 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002233 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2234 if (VDBG) log("NetworkFactory connected");
2235 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002236 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002237 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002238 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002239 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002240 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002241 }
2242 } else {
2243 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002244 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002245 }
2246 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2247 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2248 if (VDBG) log("NetworkAgent connected");
2249 // A network agent has requested a connection. Establish the connection.
2250 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2251 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2252 } else {
2253 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002254 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002255 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002256 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002257 synchronized (mNetworkForNetId) {
2258 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002259 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002260 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002261 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002262 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002263 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002264 }
2265 }
2266 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002267
Robert Greenwalt7b816022014-04-18 15:25:25 -07002268 private void handleAsyncChannelDisconnected(Message msg) {
2269 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2270 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002271 if (DBG) {
2272 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2273 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002274 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002275 // TODO - if we move the logic to the network agent (have them disconnect
2276 // because they lost all their requests or because their score isn't good)
2277 // then they would disconnect organically, report their new state and then
2278 // disconnect the channel.
2279 if (nai.networkInfo.isConnected()) {
2280 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2281 null, null);
2282 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002283 final boolean wasDefault = isDefaultNetwork(nai);
2284 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002285 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002286 // Log default network disconnection before required book-keeping.
2287 // Let rematchAllNetworksAndRequests() below record a new default network event
2288 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2289 // whose timestamps tell how long it takes to recover a default network.
2290 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002291 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002292 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002293 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2294 // by other networks that are already connected. Perhaps that can be done by
2295 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2296 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002297 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002298 mKeepaliveTracker.handleStopAllKeepalives(nai,
2299 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002300 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002301 mNetworkAgentInfos.remove(msg.replyTo);
2302 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002303 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002304 // Remove the NetworkAgent, but don't mark the netId as
2305 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002306 mNetworkForNetId.remove(nai.network.netId);
2307 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002308 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002309 for (int i = 0; i < nai.networkRequests.size(); i++) {
2310 NetworkRequest request = nai.networkRequests.valueAt(i);
2311 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2312 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2313 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002314 sendUpdatedScoreToFactories(request, 0);
2315 }
2316 }
2317 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2318 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002319 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002320 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002321 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002322 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002323 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002324 if (nai.created) {
2325 // Tell netd to clean up the configuration for this network
2326 // (routing rules, DNS, etc).
2327 // This may be slow as it requires a lot of netd shelling out to ip and
2328 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2329 // after we've rematched networks with requests which should make a potential
2330 // fallback network the default or requested a new network from the
2331 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2332 // long time.
2333 try {
2334 mNetd.removeNetwork(nai.network.netId);
2335 } catch (Exception e) {
2336 loge("Exception removing network: " + e);
2337 }
2338 }
2339 synchronized (mNetworkForNetId) {
2340 mNetIdInUse.delete(nai.network.netId);
2341 }
2342 } else {
2343 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2344 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002345 }
2346 }
2347
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002348 // If this method proves to be too slow then we can maintain a separate
2349 // pendingIntent => NetworkRequestInfo map.
2350 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2351 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2352 Intent intent = pendingIntent.getIntent();
2353 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2354 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2355 if (existingPendingIntent != null &&
2356 existingPendingIntent.getIntent().filterEquals(intent)) {
2357 return entry.getValue();
2358 }
2359 }
2360 return null;
2361 }
2362
2363 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2364 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2365
2366 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2367 if (existingRequest != null) { // remove the existing request.
2368 if (DBG) log("Replacing " + existingRequest.request + " with "
2369 + nri.request + " because their intents matched.");
2370 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2371 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002372 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002373 }
2374
Erik Klineda4bfa82015-04-30 12:58:40 +09002375 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002376 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002377 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002378 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002379 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002380 if (nri.request.networkCapabilities.hasSignalStrength() &&
2381 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2382 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002383 }
2384 }
2385 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002386 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002387 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002388 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002389 }
2390 }
2391
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002392 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2393 int callingUid) {
2394 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2395 if (nri != null) {
2396 handleReleaseNetworkRequest(nri.request, callingUid);
2397 }
2398 }
2399
Paul Jensen99364842014-12-09 11:43:45 -05002400 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002401 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2402 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002403 private boolean unneeded(NetworkAgentInfo nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002404 if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002405 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2406 // If this Network is already the highest scoring Network for a request, or if
2407 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002408 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002409 (nai.networkRequests.get(nri.request.requestId) != null ||
2410 // Note that this catches two important cases:
2411 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2412 // is currently satisfying the request. This is desirable when
2413 // cellular ends up validating but WiFi does not.
2414 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002415 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002416 // WiFi ends up validating and out scoring cellular.
2417 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2418 nai.getCurrentScoreAsValidated())) {
2419 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002420 }
2421 }
Paul Jensene0988542015-06-25 15:30:08 -04002422 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002423 }
2424
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002425 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2426 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002427 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002428 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002429 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2430 return;
2431 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002432 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002433 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002434 mNetworkRequests.remove(request);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002435 synchronized (mUidToNetworkRequestCount) {
2436 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2437 if (requests < 1) {
2438 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2439 nri.mUid);
2440 } else if (requests == 1) {
2441 mUidToNetworkRequestCount.removeAt(
2442 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2443 } else {
2444 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2445 }
2446 }
Erik Kline7523eb32015-07-09 18:24:03 +09002447 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002448 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002449 // Find all networks that are satisfying this request and remove the request
2450 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002451 // TODO - it's my understanding that for a request there is only a single
2452 // network satisfying it, so this loop is wasteful
2453 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002454 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2455 if (nai.networkRequests.get(nri.request.requestId) != null) {
2456 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002457 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002458 log(" Removing from current network " + nai.name() +
2459 ", leaving " + nai.networkRequests.size() +
2460 " requests.");
2461 }
Paul Jensen99364842014-12-09 11:43:45 -05002462 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002463 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002464 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002465 } else {
2466 // suspect there should only be one pass through here
2467 // but if any were kept do the check below
2468 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002469 }
2470 }
2471 }
2472
Robert Greenwalt51481852015-01-08 14:43:31 -08002473 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2474 if (nai != null) {
2475 mNetworkForRequestId.remove(nri.request.requestId);
2476 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002477 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002478 // that a network connected to serve it, even though the network was already
2479 // connected. Now that this request has gone away, we might have to pretend
2480 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002481 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002482 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2483 boolean doRemove = true;
2484 if (wasKept) {
2485 // check if any of the remaining requests for this network are for the
2486 // same legacy type - if so, don't remove the nai
2487 for (int i = 0; i < nai.networkRequests.size(); i++) {
2488 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2489 if (otherRequest.legacyType == nri.request.legacyType &&
2490 isRequest(otherRequest)) {
2491 if (DBG) log(" still have other legacy request - leaving");
2492 doRemove = false;
2493 }
2494 }
2495 }
2496
2497 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002498 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002499 }
2500 }
2501
Robert Greenwalta67be032014-05-16 15:49:14 -07002502 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002503 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2504 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002505 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002506 } else {
2507 // listens don't have a singular affectedNetwork. Check all networks to see
2508 // if this listen request applies and remove it.
2509 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2510 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002511 if (nri.request.networkCapabilities.hasSignalStrength() &&
2512 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2513 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002514 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002515 }
2516 }
2517 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2518 }
2519 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002520
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002521 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2522 enforceConnectivityInternalPermission();
2523 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2524 accept ? 1 : 0, always ? 1: 0, network));
2525 }
2526
2527 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2528 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2529 " accept=" + accept + " always=" + always);
2530
2531 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2532 if (nai == null) {
2533 // Nothing to do.
2534 return;
2535 }
2536
2537 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002538 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002539 return;
2540 }
2541
2542 if (!nai.networkMisc.explicitlySelected) {
2543 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2544 }
2545
2546 if (accept != nai.networkMisc.acceptUnvalidated) {
2547 int oldScore = nai.getCurrentScore();
2548 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002549 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002550 sendUpdatedScoreToFactories(nai);
2551 }
2552
2553 if (always) {
2554 nai.asyncChannel.sendMessage(
2555 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2556 }
2557
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002558 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002559 // Tell the NetworkAgent to not automatically reconnect to the network.
2560 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2561 // Teardown the nework.
2562 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002563 }
2564
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002565 }
2566
2567 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002568 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002569 mHandler.sendMessageDelayed(
2570 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2571 PROMPT_UNVALIDATED_DELAY_MS);
2572 }
2573
2574 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002575 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002576 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2577
2578 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2579 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002580 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002581 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002582 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2583 return;
2584 }
2585
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002586 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002587 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002588 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2589 intent.setClassName("com.android.settings",
2590 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002591
2592 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2593 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
fionaxu1bf6ec22016-05-23 16:33:16 -07002594
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002595 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002596 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002597 }
2598
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002599 private class InternalHandler extends Handler {
2600 public InternalHandler(Looper looper) {
2601 super(looper);
2602 }
2603
2604 @Override
2605 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002606 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002607 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002608 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002609 String causedBy = null;
2610 synchronized (ConnectivityService.this) {
2611 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2612 mNetTransitionWakeLock.isHeld()) {
2613 mNetTransitionWakeLock.release();
2614 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002615 } else {
2616 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002617 }
2618 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002619 if (VDBG) {
2620 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2621 log("Failed to find a new network - expiring NetTransition Wakelock");
2622 } else {
2623 log("NetTransition Wakelock (" +
2624 (causedBy == null ? "unknown" : causedBy) +
2625 " cleared because we found a replacement network");
2626 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002627 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002628 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002629 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002630 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002631 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002632 break;
2633 }
Jason Monkdecd2952013-10-10 14:02:51 -04002634 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002635 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002636 break;
2637 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002638 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002639 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2640 break;
2641 }
2642 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2643 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002644 break;
2645 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002646 case EVENT_REGISTER_NETWORK_AGENT: {
2647 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2648 break;
2649 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002650 case EVENT_REGISTER_NETWORK_REQUEST:
2651 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002652 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002653 break;
2654 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002655 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2656 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002657 handleRegisterNetworkRequestWithIntent(msg);
2658 break;
2659 }
2660 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2661 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2662 break;
2663 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002664 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002665 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002666 break;
2667 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002668 case EVENT_SET_ACCEPT_UNVALIDATED: {
2669 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2670 break;
2671 }
2672 case EVENT_PROMPT_UNVALIDATED: {
2673 handlePromptUnvalidated((Network) msg.obj);
2674 break;
2675 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002676 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2677 handleMobileDataAlwaysOn();
2678 break;
2679 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002680 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2681 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2682 mKeepaliveTracker.handleStartKeepalive(msg);
2683 break;
2684 }
2685 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2686 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2687 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2688 int slot = msg.arg1;
2689 int reason = msg.arg2;
2690 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2691 break;
2692 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002693 case EVENT_SYSTEM_READY: {
2694 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2695 nai.networkMonitor.systemReady = true;
2696 }
2697 break;
2698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 }
2700 }
2701 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002702
2703 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002704 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002705 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002706 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002707 final int status = mTethering.tether(iface);
2708 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2709 try {
2710 mPolicyManager.onTetheringChanged(iface, true);
2711 } catch (RemoteException e) {
2712 }
2713 }
2714 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002715 } else {
2716 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2717 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002718 }
2719
2720 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002721 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002722 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002723
2724 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002725 final int status = mTethering.untether(iface);
2726 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2727 try {
2728 mPolicyManager.onTetheringChanged(iface, false);
2729 } catch (RemoteException e) {
2730 }
2731 }
2732 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002733 } else {
2734 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2735 }
2736 }
2737
2738 // javadoc from interface
2739 public int getLastTetherError(String iface) {
2740 enforceTetherAccessPermission();
2741
2742 if (isTetheringSupported()) {
2743 return mTethering.getLastTetherError(iface);
2744 } else {
2745 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2746 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002747 }
2748
2749 // TODO - proper iface API for selection by property, inspection, etc
2750 public String[] getTetherableUsbRegexs() {
2751 enforceTetherAccessPermission();
2752 if (isTetheringSupported()) {
2753 return mTethering.getTetherableUsbRegexs();
2754 } else {
2755 return new String[0];
2756 }
2757 }
2758
2759 public String[] getTetherableWifiRegexs() {
2760 enforceTetherAccessPermission();
2761 if (isTetheringSupported()) {
2762 return mTethering.getTetherableWifiRegexs();
2763 } else {
2764 return new String[0];
2765 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002766 }
2767
Danica Chang6fdd0c62010-08-11 14:54:43 -07002768 public String[] getTetherableBluetoothRegexs() {
2769 enforceTetherAccessPermission();
2770 if (isTetheringSupported()) {
2771 return mTethering.getTetherableBluetoothRegexs();
2772 } else {
2773 return new String[0];
2774 }
2775 }
2776
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002777 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002778 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002779 if (isTetheringSupported()) {
2780 return mTethering.setUsbTethering(enable);
2781 } else {
2782 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2783 }
2784 }
2785
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002786 // TODO - move iface listing, queries, etc to new module
2787 // javadoc from interface
2788 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002789 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002790 return mTethering.getTetherableIfaces();
2791 }
2792
2793 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002794 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002795 return mTethering.getTetheredIfaces();
2796 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002797
Robert Greenwalt5a735062010-03-02 17:25:02 -08002798 public String[] getTetheringErroredIfaces() {
2799 enforceTetherAccessPermission();
2800 return mTethering.getErroredIfaces();
2801 }
2802
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002803 public String[] getTetheredDhcpRanges() {
2804 enforceConnectivityInternalPermission();
2805 return mTethering.getTetheredDhcpRanges();
2806 }
2807
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002808 // if ro.tether.denied = true we default to no tethering
2809 // gservices could set the secure setting to 1 though to enable it on a build where it
2810 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002811 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002812 public boolean isTetheringSupported() {
2813 enforceTetherAccessPermission();
2814 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002815 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002816 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2817 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002818 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2819 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002820 mTethering.getTetherableWifiRegexs().length != 0 ||
2821 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2822 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002823 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002824
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002825 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002826 public void startTethering(int type, ResultReceiver receiver,
2827 boolean showProvisioningUi) {
2828 ConnectivityManager.enforceTetherChangePermission(mContext);
2829 if (!isTetheringSupported()) {
2830 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2831 return;
2832 }
2833 mTethering.startTethering(type, receiver, showProvisioningUi);
2834 }
2835
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002836 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002837 public void stopTethering(int type) {
2838 ConnectivityManager.enforceTetherChangePermission(mContext);
2839 mTethering.stopTethering(type);
2840 }
2841
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002842 // Called when we lose the default network and have no replacement yet.
2843 // This will automatically be cleared after X seconds or a new default network
2844 // becomes CONNECTED, whichever happens first. The timer is started by the
2845 // first caller and not restarted by subsequent callers.
2846 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002847 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002848 synchronized (this) {
2849 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002850 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002851 mNetTransitionWakeLock.acquire();
2852 mNetTransitionWakeLockCausedBy = forWhom;
2853 }
2854 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002855 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002856 mNetTransitionWakeLockTimeout);
2857 return;
2858 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002859
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002860 // 100 percent is full good, 0 is full bad.
2861 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002862 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002863 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002864 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002865 }
2866
Paul Jensenbfd17b72015-04-07 12:43:13 -04002867 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002868 enforceAccessPermission();
2869 enforceInternetPermission();
2870
Paul Jensenbfd17b72015-04-07 12:43:13 -04002871 NetworkAgentInfo nai;
2872 if (network == null) {
2873 nai = getDefaultNetwork();
2874 } else {
2875 nai = getNetworkAgentInfoForNetwork(network);
2876 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002877 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2878 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2879 return;
2880 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002881 // Revalidate if the app report does not match our current validated state.
2882 if (hasConnectivity == nai.lastValidated) return;
2883 final int uid = Binder.getCallingUid();
2884 if (DBG) {
2885 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2886 ") by " + uid);
2887 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002888 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002889 // Validating a network that has not yet connected could result in a call to
2890 // rematchNetworkAndRequests() which is not meant to work on such networks.
2891 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04002892
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002893 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002894
2895 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2896 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002897 }
2898
Paul Jensencee9b512015-05-06 07:32:40 -04002899 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002900 // this information is already available as a world read/writable jvm property
2901 // so this API change wouldn't have a benifit. It also breaks the passing
2902 // of proxy info to all the JVMs.
2903 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002904 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002905 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002906 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2907 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002908 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002909 }
2910
Paul Jensencee9b512015-05-06 07:32:40 -04002911 public ProxyInfo getProxyForNetwork(Network network) {
2912 if (network == null) return getDefaultProxy();
2913 final ProxyInfo globalProxy = getGlobalProxy();
2914 if (globalProxy != null) return globalProxy;
2915 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2916 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2917 // caller may not have.
2918 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2919 if (nai == null) return null;
2920 synchronized (nai) {
2921 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2922 if (proxyInfo == null) return null;
2923 return new ProxyInfo(proxyInfo);
2924 }
2925 }
2926
Paul Jensene0bef712014-12-10 15:12:18 -05002927 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2928 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2929 // proxy is null then there is no proxy in place).
2930 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2931 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2932 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2933 proxy = null;
2934 }
2935 return proxy;
2936 }
2937
2938 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2939 // better for determining if a new proxy broadcast is necessary:
2940 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2941 // avoid unnecessary broadcasts.
2942 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2943 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2944 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2945 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2946 // all set.
2947 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2948 a = canonicalizeProxyInfo(a);
2949 b = canonicalizeProxyInfo(b);
2950 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2951 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2952 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2953 }
2954
Jason Monk207900c2014-04-25 15:00:09 -04002955 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002956 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002957
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002958 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002959 if (proxyProperties == mGlobalProxy) return;
2960 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2961 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2962
2963 String host = "";
2964 int port = 0;
2965 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002966 String pacFileUrl = "";
2967 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002968 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002969 if (!proxyProperties.isValid()) {
2970 if (DBG)
2971 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2972 return;
2973 }
Jason Monk207900c2014-04-25 15:00:09 -04002974 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002975 host = mGlobalProxy.getHost();
2976 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002977 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002978 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002979 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002980 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002981 } else {
2982 mGlobalProxy = null;
2983 }
2984 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002985 final long token = Binder.clearCallingIdentity();
2986 try {
2987 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2988 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2989 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2990 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002991 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002992 } finally {
2993 Binder.restoreCallingIdentity(token);
2994 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002995
Jason Monkcf0f97a2014-10-02 15:39:38 -04002996 if (mGlobalProxy == null) {
2997 proxyProperties = mDefaultProxy;
2998 }
2999 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003000 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003001 }
3002
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003003 private void loadGlobalProxy() {
3004 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003005 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3006 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3007 String exclList = Settings.Global.getString(res,
3008 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003009 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3010 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003011 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003012 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003013 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003014 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003015 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003016 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003017 if (!proxyProperties.isValid()) {
3018 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3019 return;
3020 }
3021
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003022 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003023 mGlobalProxy = proxyProperties;
3024 }
3025 }
3026 }
3027
Jason Monk207900c2014-04-25 15:00:09 -04003028 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003029 // this information is already available as a world read/writable jvm property
3030 // so this API change wouldn't have a benifit. It also breaks the passing
3031 // of proxy info to all the JVMs.
3032 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003033 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003034 return mGlobalProxy;
3035 }
3036 }
3037
Jason Monk207900c2014-04-25 15:00:09 -04003038 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003039 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003040 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003041 proxy = null;
3042 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003043 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003044 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003045 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003046 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003047 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3048 return;
3049 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003050
3051 // This call could be coming from the PacManager, containing the port of the local
3052 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3053 // global (to get the correct local port), and send a broadcast.
3054 // TODO: Switch PacManager to have its own message to send back rather than
3055 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003056 if ((mGlobalProxy != null) && (proxy != null)
3057 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003058 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3059 mGlobalProxy = proxy;
3060 sendProxyBroadcast(mGlobalProxy);
3061 return;
3062 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003063 mDefaultProxy = proxy;
3064
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003065 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003066 if (!mDefaultProxyDisabled) {
3067 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003068 }
3069 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003070 }
3071
Paul Jensene0bef712014-12-10 15:12:18 -05003072 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3073 // This method gets called when any network changes proxy, but the broadcast only ever contains
3074 // the default proxy (even if it hasn't changed).
3075 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3076 // world where an app might be bound to a non-default network.
3077 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3078 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3079 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3080
3081 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3082 sendProxyBroadcast(getDefaultProxy());
3083 }
3084 }
3085
Robert Greenwalt434203a2010-10-11 16:00:27 -07003086 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003087 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3088 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003089 if (!TextUtils.isEmpty(proxy)) {
3090 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003091 if (data.length == 0) {
3092 return;
3093 }
3094
Robert Greenwalt434203a2010-10-11 16:00:27 -07003095 String proxyHost = data[0];
3096 int proxyPort = 8080;
3097 if (data.length > 1) {
3098 try {
3099 proxyPort = Integer.parseInt(data[1]);
3100 } catch (NumberFormatException e) {
3101 return;
3102 }
3103 }
Jason Monk207900c2014-04-25 15:00:09 -04003104 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003105 setGlobalProxy(p);
3106 }
3107 }
3108
Jason Monk207900c2014-04-25 15:00:09 -04003109 private void sendProxyBroadcast(ProxyInfo proxy) {
3110 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003111 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003112 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003113 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003114 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3115 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003116 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003117 final long ident = Binder.clearCallingIdentity();
3118 try {
3119 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3120 } finally {
3121 Binder.restoreCallingIdentity(ident);
3122 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003123 }
3124
3125 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003126 final private HashMap<Uri, Integer> mUriEventMap;
3127 final private Context mContext;
3128 final private Handler mHandler;
3129
3130 SettingsObserver(Context context, Handler handler) {
3131 super(null);
3132 mUriEventMap = new HashMap<Uri, Integer>();
3133 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003134 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003135 }
3136
Erik Klineda4bfa82015-04-30 12:58:40 +09003137 void observe(Uri uri, int what) {
3138 mUriEventMap.put(uri, what);
3139 final ContentResolver resolver = mContext.getContentResolver();
3140 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003141 }
3142
3143 @Override
3144 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003145 Slog.wtf(TAG, "Should never be reached.");
3146 }
3147
3148 @Override
3149 public void onChange(boolean selfChange, Uri uri) {
3150 final Integer what = mUriEventMap.get(uri);
3151 if (what != null) {
3152 mHandler.obtainMessage(what.intValue()).sendToTarget();
3153 } else {
3154 loge("No matching event to send for URI=" + uri);
3155 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003156 }
3157 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003158
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003159 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003160 Slog.d(TAG, s);
3161 }
3162
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003163 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003164 Slog.e(TAG, s);
3165 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003166
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003167 private static <T> T checkNotNull(T value, String message) {
3168 if (value == null) {
3169 throw new NullPointerException(message);
3170 }
3171 return value;
3172 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003173
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003174 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003175 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003176 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3177 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3178 *
3179 * @param oldPackage Package name of the application which currently controls VPN, which will
3180 * be replaced. If there is no such application, this should should either be
3181 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3182 * @param newPackage Package name of the application which should gain control of VPN, or
3183 * {@code null} to disable.
3184 * @param userId User for whom to prepare the new VPN.
3185 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003186 * @hide
3187 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003188 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003189 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3190 int userId) {
3191 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003192 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003193
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003194 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003195 Vpn vpn = mVpns.get(userId);
3196 if (vpn != null) {
3197 return vpn.prepare(oldPackage, newPackage);
3198 } else {
3199 return false;
3200 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003201 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003202 }
3203
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003204 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003205 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3206 * This method is used by system-privileged apps.
3207 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3208 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3209 *
3210 * @param packageName The package for which authorization state should change.
3211 * @param userId User for whom {@code packageName} is installed.
3212 * @param authorized {@code true} if this app should be able to start a VPN connection without
3213 * explicit user approval, {@code false} if not.
3214 *
Jeff Davidson05542602014-08-11 14:07:27 -07003215 * @hide
3216 */
3217 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003218 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3219 enforceCrossUserPermission(userId);
3220
Jeff Davidson05542602014-08-11 14:07:27 -07003221 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003222 Vpn vpn = mVpns.get(userId);
3223 if (vpn != null) {
3224 vpn.setPackageAuthorization(packageName, authorized);
3225 }
Jeff Davidson05542602014-08-11 14:07:27 -07003226 }
3227 }
3228
3229 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003230 * Configure a TUN interface and return its file descriptor. Parameters
3231 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003232 * and not available in ConnectivityManager. Permissions are checked in
3233 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003234 * @hide
3235 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003236 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003237 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003238 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003239 int user = UserHandle.getUserId(Binder.getCallingUid());
3240 synchronized(mVpns) {
3241 return mVpns.get(user).establish(config);
3242 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003243 }
3244
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003245 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003246 * Start legacy VPN, controlling native daemons as needed. Creates a
3247 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003248 */
3249 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003250 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003251 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003252 final LinkProperties egress = getActiveLinkProperties();
3253 if (egress == null) {
3254 throw new IllegalStateException("Missing active network connection");
3255 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003256 int user = UserHandle.getUserId(Binder.getCallingUid());
3257 synchronized(mVpns) {
3258 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3259 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003260 }
3261
3262 /**
3263 * Return the information of the ongoing legacy VPN. This method is used
3264 * by VpnSettings and not available in ConnectivityManager. Permissions
3265 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003266 */
3267 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003268 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3269 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003270
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003271 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003272 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003273 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003274 }
3275
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003276 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003277 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3278 * and not available in ConnectivityManager.
3279 */
3280 @Override
3281 public VpnInfo[] getAllVpnInfo() {
3282 enforceConnectivityInternalPermission();
3283 if (mLockdownEnabled) {
3284 return new VpnInfo[0];
3285 }
3286
3287 synchronized(mVpns) {
3288 List<VpnInfo> infoList = new ArrayList<>();
3289 for (int i = 0; i < mVpns.size(); i++) {
3290 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3291 if (info != null) {
3292 infoList.add(info);
3293 }
3294 }
3295 return infoList.toArray(new VpnInfo[infoList.size()]);
3296 }
3297 }
3298
3299 /**
3300 * @return VPN information for accounting, or null if we can't retrieve all required
3301 * information, e.g primary underlying iface.
3302 */
3303 @Nullable
3304 private VpnInfo createVpnInfo(Vpn vpn) {
3305 VpnInfo info = vpn.getVpnInfo();
3306 if (info == null) {
3307 return null;
3308 }
3309 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3310 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3311 // the underlyingNetworks list.
3312 if (underlyingNetworks == null) {
3313 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3314 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3315 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3316 }
3317 } else if (underlyingNetworks.length > 0) {
3318 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3319 if (linkProperties != null) {
3320 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3321 }
3322 }
3323 return info.primaryUnderlyingIface == null ? null : info;
3324 }
3325
3326 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003327 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3328 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003329 * Permissions are checked in Vpn class.
3330 * @hide
3331 */
3332 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003333 public VpnConfig getVpnConfig(int userId) {
3334 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003335 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003336 Vpn vpn = mVpns.get(userId);
3337 if (vpn != null) {
3338 return vpn.getVpnConfig();
3339 } else {
3340 return null;
3341 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003342 }
3343 }
3344
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003345 @Override
3346 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003347 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3348 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3349 return false;
3350 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003351
3352 // Tear down existing lockdown if profile was removed
3353 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3354 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003355 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3356 final VpnProfile profile = VpnProfile.decode(
3357 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003358 if (profile == null) {
3359 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3360 setLockdownTracker(null);
3361 return true;
3362 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003363 int user = UserHandle.getUserId(Binder.getCallingUid());
3364 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003365 Vpn vpn = mVpns.get(user);
3366 if (vpn == null) {
3367 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3368 return false;
3369 }
3370 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003371 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003372 } else {
3373 setLockdownTracker(null);
3374 }
3375
3376 return true;
3377 }
3378
3379 /**
3380 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3381 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3382 */
3383 private void setLockdownTracker(LockdownVpnTracker tracker) {
3384 // Shutdown any existing tracker
3385 final LockdownVpnTracker existing = mLockdownTracker;
3386 mLockdownTracker = null;
3387 if (existing != null) {
3388 existing.shutdown();
3389 }
3390
3391 try {
3392 if (tracker != null) {
3393 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003394 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003395 mLockdownTracker = tracker;
3396 mLockdownTracker.init();
3397 } else {
3398 mNetd.setFirewallEnabled(false);
3399 }
3400 } catch (RemoteException e) {
3401 // ignored; NMS lives inside system_server
3402 }
3403 }
3404
3405 private void throwIfLockdownEnabled() {
3406 if (mLockdownEnabled) {
3407 throw new IllegalStateException("Unavailable in lockdown mode");
3408 }
3409 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003410
Robin Lee244ce8e2016-01-05 18:03:46 +00003411 /**
Robin Lee17e61832016-05-09 13:46:28 +01003412 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3413 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003414 *
Robin Lee17e61832016-05-09 13:46:28 +01003415 * @return {@code true} if the service was started, the service was already connected, or there
3416 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003417 */
Robin Lee17e61832016-05-09 13:46:28 +01003418 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003419 synchronized (mVpns) {
3420 Vpn vpn = mVpns.get(userId);
3421 if (vpn == null) {
3422 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3423 // exists already.
3424 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3425 return false;
3426 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003427
Robin Lee812800c2016-05-13 15:38:08 +01003428 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003429 }
3430 }
3431
3432 @Override
Robin Leedc679712016-05-03 13:23:03 +01003433 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003434 enforceConnectivityInternalPermission();
3435 enforceCrossUserPermission(userId);
3436
3437 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3438 if (LockdownVpnTracker.isEnabled()) {
3439 return false;
3440 }
3441
Robin Lee244ce8e2016-01-05 18:03:46 +00003442 synchronized (mVpns) {
3443 Vpn vpn = mVpns.get(userId);
3444 if (vpn == null) {
3445 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3446 return false;
3447 }
Robin Lee17e61832016-05-09 13:46:28 +01003448 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003449 return false;
3450 }
Robin Lee17e61832016-05-09 13:46:28 +01003451 if (!startAlwaysOnVpn(userId)) {
3452 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003453 return false;
3454 }
Robin Lee17e61832016-05-09 13:46:28 +01003455
Robin Lee812800c2016-05-13 15:38:08 +01003456 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003457 }
3458 return true;
3459 }
3460
3461 @Override
3462 public String getAlwaysOnVpnPackage(int userId) {
3463 enforceConnectivityInternalPermission();
3464 enforceCrossUserPermission(userId);
3465
3466 synchronized (mVpns) {
3467 Vpn vpn = mVpns.get(userId);
3468 if (vpn == null) {
3469 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3470 return null;
3471 }
3472 return vpn.getAlwaysOnPackage();
3473 }
3474 }
3475
Wink Savilleab9321d2013-06-29 21:10:57 -07003476 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003477 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003478 // TODO: Remove? Any reason to trigger a provisioning check?
3479 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003480 }
3481
3482 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003483 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003484
Paul Jensen89e0f092014-09-15 15:59:36 -04003485 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003486 Intent intent = new Intent(action);
3487 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003488 // Concatenate the range of types onto the range of NetIDs.
3489 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003490 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003491 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003492 }
3493
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003494 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003495 * Show or hide network provisioning notifications.
3496 *
3497 * We use notifications for two purposes: to notify that a network requires sign in
3498 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3499 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3500 * particular network we can display the notification type that was most recently requested.
3501 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3502 * might first display NO_INTERNET, and then when the captive portal check completes, display
3503 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003504 *
3505 * @param id an identifier that uniquely identifies this notification. This must match
3506 * between show and hide calls. We use the NetID value but for legacy callers
3507 * we concatenate the range of types with the range of NetIDs.
3508 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003509 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003510 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3511 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003512 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003513 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3514 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003515 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003516 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003517
3518 Resources r = Resources.getSystem();
3519 NotificationManager notificationManager = (NotificationManager) mContext
3520 .getSystemService(Context.NOTIFICATION_SERVICE);
3521
3522 if (visible) {
3523 CharSequence title;
3524 CharSequence details;
3525 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003526 if (notifyType == NotificationType.NO_INTERNET &&
3527 networkType == ConnectivityManager.TYPE_WIFI) {
3528 title = r.getString(R.string.wifi_no_internet, 0);
3529 details = r.getString(R.string.wifi_no_internet_detailed);
3530 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3531 } else if (notifyType == NotificationType.SIGN_IN) {
3532 switch (networkType) {
3533 case ConnectivityManager.TYPE_WIFI:
3534 title = r.getString(R.string.wifi_available_sign_in, 0);
3535 details = r.getString(R.string.network_available_sign_in_detailed,
3536 extraInfo);
3537 icon = R.drawable.stat_notify_wifi_in_range;
3538 break;
3539 case ConnectivityManager.TYPE_MOBILE:
3540 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3541 title = r.getString(R.string.network_available_sign_in, 0);
3542 // TODO: Change this to pull from NetworkInfo once a printable
3543 // name has been added to it
3544 details = mTelephonyManager.getNetworkOperatorName();
3545 icon = R.drawable.stat_notify_rssi_in_range;
3546 break;
3547 default:
3548 title = r.getString(R.string.network_available_sign_in, 0);
3549 details = r.getString(R.string.network_available_sign_in_detailed,
3550 extraInfo);
3551 icon = R.drawable.stat_notify_rssi_in_range;
3552 break;
3553 }
3554 } else {
3555 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3556 + getNetworkTypeName(networkType));
3557 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003558 }
3559
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003560 Notification notification = new Notification.Builder(mContext)
3561 .setWhen(0)
3562 .setSmallIcon(icon)
3563 .setAutoCancel(true)
3564 .setTicker(title)
3565 .setColor(mContext.getColor(
3566 com.android.internal.R.color.system_notification_accent_color))
3567 .setContentTitle(title)
3568 .setContentText(details)
3569 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003570 .setLocalOnly(true)
3571 .setPriority(highPriority ?
3572 Notification.PRIORITY_HIGH :
3573 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003574 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003575 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003576 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003577
Wink Saville948282b2013-08-29 08:55:16 -07003578 try {
Paul Jensenf8e903f2016-06-13 09:39:28 -04003579 notificationManager.notifyAsUser(NOTIFICATION_ID, id, notification, UserHandle.ALL);
Wink Saville948282b2013-08-29 08:55:16 -07003580 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003581 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003582 npe.printStackTrace();
3583 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003584 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003585 try {
Paul Jensenf8e903f2016-06-13 09:39:28 -04003586 notificationManager.cancelAsUser(NOTIFICATION_ID, id, UserHandle.ALL);
Wink Saville948282b2013-08-29 08:55:16 -07003587 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003588 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003589 npe.printStackTrace();
3590 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003591 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003592 }
3593
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003594 /** Location to an updatable file listing carrier provisioning urls.
3595 * An example:
3596 *
3597 * <?xml version="1.0" encoding="utf-8"?>
3598 * <provisioningUrls>
3599 * <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 -07003600 * </provisioningUrls>
3601 */
3602 private static final String PROVISIONING_URL_PATH =
3603 "/data/misc/radio/provisioning_urls.xml";
3604 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003605
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003606 /** XML tag for root element. */
3607 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3608 /** XML tag for individual url */
3609 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003610 /** XML attribute for mcc */
3611 private static final String ATTR_MCC = "mcc";
3612 /** XML attribute for mnc */
3613 private static final String ATTR_MNC = "mnc";
3614
Paul Jensen434dde82015-06-11 09:43:30 -04003615 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003616 FileReader fileReader = null;
3617 XmlPullParser parser = null;
3618 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003619
3620 try {
3621 fileReader = new FileReader(mProvisioningUrlFile);
3622 parser = Xml.newPullParser();
3623 parser.setInput(fileReader);
3624 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3625
3626 while (true) {
3627 XmlUtils.nextElement(parser);
3628
3629 String element = parser.getName();
3630 if (element == null) break;
3631
Paul Jensen434dde82015-06-11 09:43:30 -04003632 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003633 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3634 try {
3635 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3636 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3637 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3638 parser.next();
3639 if (parser.getEventType() == XmlPullParser.TEXT) {
3640 return parser.getText();
3641 }
3642 }
3643 }
3644 } catch (NumberFormatException e) {
3645 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3646 }
3647 }
3648 }
3649 return null;
3650 } catch (FileNotFoundException e) {
3651 loge("Carrier Provisioning Urls file not found");
3652 } catch (XmlPullParserException e) {
3653 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3654 } catch (IOException e) {
3655 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3656 } finally {
3657 if (fileReader != null) {
3658 try {
3659 fileReader.close();
3660 } catch (IOException e) {}
3661 }
3662 }
3663 return null;
3664 }
3665
Wink Saville42d4f082013-07-20 20:31:59 -07003666 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003667 public String getMobileProvisioningUrl() {
3668 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003669 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003670 if (TextUtils.isEmpty(url)) {
3671 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003672 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003673 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003674 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003675 }
Wink Saville8cf35602013-07-10 23:00:07 -07003676 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003677 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003678 String phoneNumber = mTelephonyManager.getLine1Number();
3679 if (TextUtils.isEmpty(phoneNumber)) {
3680 phoneNumber = "0000000000";
3681 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003682 url = String.format(url,
3683 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3684 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003685 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003686 }
3687
Wink Savilleab9321d2013-06-29 21:10:57 -07003688 return url;
3689 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003690
Wink Saville948282b2013-08-29 08:55:16 -07003691 @Override
3692 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003693 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003694 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003695 final long ident = Binder.clearCallingIdentity();
3696 try {
3697 setProvNotificationVisible(visible, networkType, action);
3698 } finally {
3699 Binder.restoreCallingIdentity(ident);
3700 }
Wink Saville948282b2013-08-29 08:55:16 -07003701 }
Wink Saville7788c612013-08-29 14:57:08 -07003702
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003703 @Override
3704 public void setAirplaneMode(boolean enable) {
3705 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003706 final long ident = Binder.clearCallingIdentity();
3707 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003708 final ContentResolver cr = mContext.getContentResolver();
3709 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3710 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3711 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003712 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003713 } finally {
3714 Binder.restoreCallingIdentity(ident);
3715 }
3716 }
3717
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003718 private void onUserStart(int userId) {
3719 synchronized(mVpns) {
3720 Vpn userVpn = mVpns.get(userId);
3721 if (userVpn != null) {
3722 loge("Starting user already has a VPN");
3723 return;
3724 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003725 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003726 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003727
3728 final ContentResolver cr = mContext.getContentResolver();
3729 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3730 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3731 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3732 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3733 if (alwaysOnPackage != null) {
3734 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3735 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003736 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003737 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3738 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003739 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003740 }
3741
3742 private void onUserStop(int userId) {
3743 synchronized(mVpns) {
3744 Vpn userVpn = mVpns.get(userId);
3745 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003746 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003747 return;
3748 }
Robin Lee17e61832016-05-09 13:46:28 +01003749 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003750 mVpns.delete(userId);
3751 }
3752 }
3753
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003754 private void onUserAdded(int userId) {
3755 synchronized(mVpns) {
3756 final int vpnsSize = mVpns.size();
3757 for (int i = 0; i < vpnsSize; i++) {
3758 Vpn vpn = mVpns.valueAt(i);
3759 vpn.onUserAdded(userId);
3760 }
3761 }
3762 }
3763
3764 private void onUserRemoved(int userId) {
3765 synchronized(mVpns) {
3766 final int vpnsSize = mVpns.size();
3767 for (int i = 0; i < vpnsSize; i++) {
3768 Vpn vpn = mVpns.valueAt(i);
3769 vpn.onUserRemoved(userId);
3770 }
3771 }
3772 }
3773
Robin Lee89e7a692016-02-29 14:38:17 +00003774 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003775 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3776 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3777 updateLockdownVpn();
3778 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003779 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003780 }
3781 }
3782
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003783 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3784 @Override
3785 public void onReceive(Context context, Intent intent) {
3786 final String action = intent.getAction();
3787 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3788 if (userId == UserHandle.USER_NULL) return;
3789
Robin Lee323f29d2016-05-04 16:38:06 +01003790 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003791 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003792 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003793 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003794 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3795 onUserAdded(userId);
3796 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3797 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003798 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3799 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003800 }
3801 }
3802 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003803
Robert Greenwalta67be032014-05-16 15:49:14 -07003804 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3805 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003806 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3807 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003808
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003809 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3810 // Map from UID to number of NetworkRequests that UID has filed.
3811 @GuardedBy("mUidToNetworkRequestCount")
3812 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3813
Robert Greenwalta67be032014-05-16 15:49:14 -07003814 private static class NetworkFactoryInfo {
3815 public final String name;
3816 public final Messenger messenger;
3817 public final AsyncChannel asyncChannel;
3818
3819 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3820 this.name = name;
3821 this.messenger = messenger;
3822 this.asyncChannel = asyncChannel;
3823 }
3824 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003825
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003826 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003827 * A NetworkRequest as registered by an application can be one of three
3828 * types:
3829 *
3830 * - "listen", for which the framework will issue callbacks about any
3831 * and all networks that match the specified NetworkCapabilities,
3832 *
3833 * - "request", capable of causing a specific network to be created
3834 * first (e.g. a telephony DUN request), the framework will issue
3835 * callbacks about the single, highest scoring current network
3836 * (if any) that matches the specified NetworkCapabilities, or
3837 *
3838 * - "track the default network", a hybrid of the two designed such
3839 * that the framework will issue callbacks for the single, highest
3840 * scoring current network (if any) that matches the capabilities of
3841 * the default Internet request (mDefaultRequest), but which cannot
3842 * cause the framework to either create or retain the existence of
3843 * any specific network.
3844 *
3845 */
3846 private static enum NetworkRequestType {
3847 LISTEN,
3848 TRACK_DEFAULT,
3849 REQUEST
3850 };
3851
3852 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003853 * Tracks info about the requester.
3854 * Also used to notice when the calling process dies so we can self-expire
3855 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003856 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003857 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003858 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003859 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003860 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003861 final int mPid;
3862 final int mUid;
3863 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003864 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003865
Erik Kline371c7b72016-03-22 17:04:20 +09003866 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003867 request = r;
3868 mPendingIntent = pi;
3869 messenger = null;
3870 mBinder = null;
3871 mPid = getCallingPid();
3872 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003873 mType = type;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003874 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003875 }
3876
Erik Kline371c7b72016-03-22 17:04:20 +09003877 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003878 super();
3879 messenger = m;
3880 request = r;
3881 mBinder = binder;
3882 mPid = getCallingPid();
3883 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003884 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003885 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003886 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003887
3888 try {
3889 mBinder.linkToDeath(this, 0);
3890 } catch (RemoteException e) {
3891 binderDied();
3892 }
3893 }
3894
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003895 private void enforceRequestCountLimit() {
3896 synchronized (mUidToNetworkRequestCount) {
3897 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3898 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3899 throw new IllegalArgumentException("Too many NetworkRequests filed");
3900 }
3901 mUidToNetworkRequestCount.put(mUid, networkRequests);
3902 }
3903 }
3904
Erik Kline371c7b72016-03-22 17:04:20 +09003905 private String typeString() {
3906 switch (mType) {
3907 case LISTEN: return "Listen";
3908 case REQUEST: return "Request";
3909 case TRACK_DEFAULT: return "Track default";
3910 default:
3911 return "unknown type";
3912 }
3913 }
3914
Robert Greenwalt9258c642014-03-26 16:47:06 -07003915 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003916 if (mBinder != null) {
3917 mBinder.unlinkToDeath(this, 0);
3918 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003919 }
3920
3921 public void binderDied() {
3922 log("ConnectivityService NetworkRequestInfo binderDied(" +
3923 request + ", " + mBinder + ")");
3924 releaseNetworkRequest(request);
3925 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003926
Erik Kline371c7b72016-03-22 17:04:20 +09003927 /**
3928 * Returns true iff. the contained NetworkRequest is one that:
3929 *
3930 * - should be associated with at most one satisfying network
3931 * at a time;
3932 *
3933 * - should cause a network to be kept up if it is the only network
3934 * which can satisfy the NetworkReqeust.
3935 *
3936 * For full detail of how isRequest() is used for pairing Networks with
3937 * NetworkRequests read rematchNetworkAndRequests().
3938 *
3939 * TODO: Rename to something more properly descriptive.
3940 */
3941 public boolean isRequest() {
3942 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3943 (mType == NetworkRequestType.REQUEST);
3944 }
3945
Robert Greenwalta67be032014-05-16 15:49:14 -07003946 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003947 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003948 " from uid/pid:" + mUid + "/" + mPid +
3949 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003950 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003951 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003952 }
3953
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003954 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3955 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3956 if (badCapability != null) {
3957 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003958 }
3959 }
3960
Erik Kline9d598e12015-07-13 16:37:51 +09003961 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003962 final SortedSet<Integer> thresholds = new TreeSet();
3963 synchronized (nai) {
3964 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3965 if (nri.request.networkCapabilities.hasSignalStrength() &&
3966 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3967 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3968 }
3969 }
3970 }
Erik Kline9d598e12015-07-13 16:37:51 +09003971 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003972 }
3973
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003974 private void updateSignalStrengthThresholds(
3975 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3976 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003977 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003978 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3979
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003980 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003981 String detail;
3982 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3983 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3984 } else {
3985 detail = reason;
3986 }
3987 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3988 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3989 }
3990
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003991 nai.asyncChannel.sendMessage(
3992 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003993 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003994 }
3995
Robert Greenwalt9258c642014-03-26 16:47:06 -07003996 @Override
3997 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003998 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003999 final NetworkRequestType type = (networkCapabilities == null)
4000 ? NetworkRequestType.TRACK_DEFAULT
4001 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004002 // If the requested networkCapabilities is null, take them instead from
4003 // the default network request. This allows callers to keep track of
4004 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09004005 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004006 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4007 enforceAccessPermission();
4008 } else {
4009 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4010 enforceNetworkRequestPermissions(networkCapabilities);
4011 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004012 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004013 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004014
Robert Greenwalt6078b502014-06-11 16:05:07 -07004015 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004016 throw new IllegalArgumentException("Bad timeout specified");
4017 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004018
Etan Cohenddb9ef02015-11-18 10:56:15 -08004019 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4020 .equals(networkCapabilities.getNetworkSpecifier())) {
4021 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4022 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4023 }
4024
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004025 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
4026 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09004027 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09004028 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004029
4030 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004031 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004032 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004033 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004034 }
4035 return networkRequest;
4036 }
4037
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004038 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004039 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004040 enforceConnectivityInternalPermission();
4041 } else {
4042 enforceChangePermission();
4043 }
4044 }
4045
fenglub15e72b2015-03-20 11:29:56 -07004046 @Override
fengludb571472015-04-21 17:12:05 -07004047 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004048 enforceAccessPermission();
4049 NetworkAgentInfo nai = null;
4050 if (network == null) {
4051 return false;
4052 }
4053 synchronized (mNetworkForNetId) {
4054 nai = mNetworkForNetId.get(network.netId);
4055 }
4056 if (nai != null) {
4057 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4058 return true;
4059 }
4060 return false;
4061 }
4062
Felipe Lemeee27cab2016-06-20 16:36:29 -07004063 private boolean isSystem(int uid) {
4064 return uid < Process.FIRST_APPLICATION_UID;
4065 }
fenglub15e72b2015-03-20 11:29:56 -07004066
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004067 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004068 final int uid = Binder.getCallingUid();
4069 if (isSystem(uid)) {
4070 return;
4071 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004072 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004073 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004074 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004075 synchronized(mRulesLock) {
4076 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4077 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004078 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4079 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004080 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004081 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004082 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004083 }
4084 }
4085 }
4086
Robert Greenwalt9258c642014-03-26 16:47:06 -07004087 @Override
4088 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4089 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004090 checkNotNull(operation, "PendingIntent cannot be null.");
4091 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4092 enforceNetworkRequestPermissions(networkCapabilities);
4093 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004094 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004095
4096 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
4097 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004098 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004099 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09004100 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004101 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4102 nri));
4103 return networkRequest;
4104 }
4105
Jeremy Joslin79294842014-12-03 17:15:28 -08004106 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4107 mHandler.sendMessageDelayed(
4108 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4109 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4110 }
4111
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004112 @Override
4113 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004114 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004115 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4116 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004117 }
4118
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004119 // In order to implement the compatibility measure for pre-M apps that call
4120 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4121 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4122 // This ensures it has permission to do so.
4123 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4124 if (nc == null) {
4125 return false;
4126 }
4127 int[] transportTypes = nc.getTransportTypes();
4128 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4129 return false;
4130 }
4131 try {
4132 mContext.enforceCallingOrSelfPermission(
4133 android.Manifest.permission.ACCESS_WIFI_STATE,
4134 "ConnectivityService");
4135 } catch (SecurityException e) {
4136 return false;
4137 }
4138 return true;
4139 }
4140
Robert Greenwalt9258c642014-03-26 16:47:06 -07004141 @Override
4142 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4143 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004144 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4145 enforceAccessPermission();
4146 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004147
Erik Kline7523eb32015-07-09 18:24:03 +09004148 NetworkRequest networkRequest = new NetworkRequest(
4149 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004150 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09004151 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004152 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004153
4154 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4155 return networkRequest;
4156 }
4157
4158 @Override
4159 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4160 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004161 checkNotNull(operation, "PendingIntent cannot be null.");
4162 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4163 enforceAccessPermission();
4164 }
4165
Erik Kline7523eb32015-07-09 18:24:03 +09004166 NetworkRequest networkRequest = new NetworkRequest(
4167 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004168 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004169 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004170 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004171
4172 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004173 }
4174
4175 @Override
4176 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004177 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4178 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004179 }
4180
4181 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004182 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004183 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004184 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4185 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004186 }
4187
Robert Greenwalta67be032014-05-16 15:49:14 -07004188 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004189 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004190 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4191 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4192 }
4193
4194 @Override
4195 public void unregisterNetworkFactory(Messenger messenger) {
4196 enforceConnectivityInternalPermission();
4197 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4198 }
4199
4200 private void handleUnregisterNetworkFactory(Messenger messenger) {
4201 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4202 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004203 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004204 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004205 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004206 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004207 }
4208
Robert Greenwalt7b816022014-04-18 15:25:25 -07004209 /**
4210 * NetworkAgentInfo supporting a request by requestId.
4211 * These have already been vetted (their Capabilities satisfy the request)
4212 * and the are the highest scored network available.
4213 * the are keyed off the Requests requestId.
4214 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004215 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004216 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4217 new SparseArray<NetworkAgentInfo>();
4218
Paul Jensen31a94f42015-02-13 14:18:39 -05004219 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4220 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004221 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4222 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004223 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4224 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4225 // there may not be a strict 1:1 correlation between the two.
4226 @GuardedBy("mNetworkForNetId")
4227 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004228
Robert Greenwalt7b816022014-04-18 15:25:25 -07004229 // NetworkAgentInfo keyed off its connecting messenger
4230 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004231 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004232 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4233 new HashMap<Messenger, NetworkAgentInfo>();
4234
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004235 @GuardedBy("mBlockedAppUids")
4236 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4237
Paul Jensen2c311d62014-11-17 12:34:51 -05004238 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004239 private final NetworkRequest mDefaultRequest;
4240
Erik Klineda4bfa82015-04-30 12:58:40 +09004241 // Request used to optionally keep mobile data active even when higher
4242 // priority networks like Wi-Fi are active.
4243 private final NetworkRequest mDefaultMobileDataRequest;
4244
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004245 private NetworkAgentInfo getDefaultNetwork() {
4246 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4247 }
4248
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004249 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004250 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004251 }
4252
Paul Jensen31a94f42015-02-13 14:18:39 -05004253 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004254 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004255 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004256 enforceConnectivityInternalPermission();
4257
Paul Jensen2c311d62014-11-17 12:34:51 -05004258 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4259 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004260 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004261 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4262 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004263 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004264 synchronized (this) {
4265 nai.networkMonitor.systemReady = mSystemReady;
4266 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004267 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4268 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004269 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004270 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004271 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004272 }
4273
4274 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4275 if (VDBG) log("Got NetworkAgent Messenger");
4276 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004277 synchronized (mNetworkForNetId) {
4278 mNetworkForNetId.put(na.network.netId, na);
4279 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004280 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4281 NetworkInfo networkInfo = na.networkInfo;
4282 na.networkInfo = null;
4283 updateNetworkInfo(na, networkInfo);
4284 }
4285
4286 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4287 LinkProperties newLp = networkAgent.linkProperties;
4288 int netId = networkAgent.network.netId;
4289
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004290 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4291 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004292 if (networkAgent.clatd != null) {
4293 networkAgent.clatd.fixupLinkProperties(oldLp);
4294 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004295
Paul Jensen992f2522014-04-28 10:33:11 -04004296 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004297 updateMtu(newLp, oldLp);
4298 // TODO - figure out what to do for clat
4299// for (LinkProperties lp : newLp.getStackedLinks()) {
4300// updateMtu(lp, null);
4301// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004302 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004303
Erik Kline94887872016-04-05 13:30:49 +09004304 updateRoutes(newLp, oldLp, netId);
4305 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004306
Paul Jensen3b759822014-05-13 11:44:01 -04004307 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004308 if (isDefaultNetwork(networkAgent)) {
4309 handleApplyDefaultProxy(newLp.getHttpProxy());
4310 } else {
4311 updateProxy(newLp, oldLp, networkAgent);
4312 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004313 // TODO - move this check to cover the whole function
4314 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004315 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004316 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4317 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004318
4319 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004320 }
4321
Lorenzo Colitti95439462014-10-09 13:44:48 +09004322 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4323 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4324 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004325
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004326 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004327 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4328 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004329 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004330 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004331 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004332 }
Paul Jensen992f2522014-04-28 10:33:11 -04004333
4334 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4335 CompareResult<String> interfaceDiff = new CompareResult<String>();
4336 if (oldLp != null) {
4337 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4338 } else if (newLp != null) {
4339 interfaceDiff.added = newLp.getAllInterfaceNames();
4340 }
4341 for (String iface : interfaceDiff.added) {
4342 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004343 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004344 mNetd.addInterfaceToNetwork(iface, netId);
4345 } catch (Exception e) {
4346 loge("Exception adding interface: " + e);
4347 }
4348 }
4349 for (String iface : interfaceDiff.removed) {
4350 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004351 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004352 mNetd.removeInterfaceFromNetwork(iface, netId);
4353 } catch (Exception e) {
4354 loge("Exception removing interface: " + e);
4355 }
4356 }
4357 }
4358
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004359 /**
4360 * Have netd update routes from oldLp to newLp.
4361 * @return true if routes changed between oldLp and newLp
4362 */
4363 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004364 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4365 if (oldLp != null) {
4366 routeDiff = oldLp.compareAllRoutes(newLp);
4367 } else if (newLp != null) {
4368 routeDiff.added = newLp.getAllRoutes();
4369 }
4370
4371 // add routes before removing old in case it helps with continuous connectivity
4372
4373 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4374 for (RouteInfo route : routeDiff.added) {
4375 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004376 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004377 try {
4378 mNetd.addRoute(netId, route);
4379 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004380 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4381 loge("Exception in addRoute for non-gateway: " + e);
4382 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004383 }
4384 }
4385 for (RouteInfo route : routeDiff.added) {
4386 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004387 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004388 try {
4389 mNetd.addRoute(netId, route);
4390 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004391 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4392 loge("Exception in addRoute for gateway: " + e);
4393 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004394 }
4395 }
4396
4397 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004398 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004399 try {
4400 mNetd.removeRoute(netId, route);
4401 } catch (Exception e) {
4402 loge("Exception in removeRoute: " + e);
4403 }
4404 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004405 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004406 }
Erik Kline41368502015-06-17 13:19:54 +09004407
Erik Kline94887872016-04-05 13:30:49 +09004408 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4409 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4410 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004411 }
Erik Kline94887872016-04-05 13:30:49 +09004412
4413 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004414 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004415 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004416 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004417 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4418 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004419 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004420 }
4421 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4422 if (defaultNai != null && defaultNai.network.netId == netId) {
4423 setDefaultDnsSystemProperties(dnses);
4424 }
4425 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004426 }
4427
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004428 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4429 int last = 0;
4430 for (InetAddress dns : dnses) {
4431 ++last;
4432 String key = "net.dns" + last;
4433 String value = dns.getHostAddress();
4434 SystemProperties.set(key, value);
4435 }
4436 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4437 String key = "net.dns" + i;
4438 SystemProperties.set(key, "");
4439 }
4440 mNumDnsEntries = last;
4441 }
4442
Paul Jensen3d194ea2015-06-16 14:27:36 -04004443 /**
4444 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4445 * augmented with any stateful capabilities implied from {@code networkAgent}
4446 * (e.g., validated status and captive portal status).
4447 *
Paul Jensene0988542015-06-25 15:30:08 -04004448 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004449 * @param networkCapabilities the new network capabilities.
4450 */
Paul Jensene0988542015-06-25 15:30:08 -04004451 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004452 // Don't modify caller's NetworkCapabilities.
4453 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004454 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004455 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4456 } else {
4457 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4458 }
Paul Jensene0988542015-06-25 15:30:08 -04004459 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004460 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4461 } else {
4462 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4463 }
Paul Jensene0988542015-06-25 15:30:08 -04004464 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4465 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004466 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4467 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4468 try {
4469 mNetd.setNetworkPermission(nai.network.netId,
4470 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4471 null : NetworkManagementService.PERMISSION_SYSTEM);
4472 } catch (RemoteException e) {
4473 loge("Exception in setNetworkPermission: " + e);
4474 }
4475 }
Paul Jensene0988542015-06-25 15:30:08 -04004476 synchronized (nai) {
4477 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004478 }
Paul Jensene0988542015-06-25 15:30:08 -04004479 rematchAllNetworksAndRequests(nai, oldScore);
4480 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004481 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004482 }
4483
Paul Jensenc8b9a742014-09-30 15:37:41 -04004484 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4485 for (int i = 0; i < nai.networkRequests.size(); i++) {
4486 NetworkRequest nr = nai.networkRequests.valueAt(i);
4487 // Don't send listening requests to factories. b/17393458
4488 if (!isRequest(nr)) continue;
4489 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4490 }
4491 }
4492
Robert Greenwalt7b816022014-04-18 15:25:25 -07004493 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4494 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004495 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004496 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4497 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004498 }
4499 }
4500
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004501 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4502 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004503 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004504 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004505 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4506 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004507 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004508 sendIntent(nri.mPendingIntent, intent);
4509 }
4510 // else not handled
4511 }
4512
4513 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4514 mPendingIntentWakeLock.acquire();
4515 try {
4516 if (DBG) log("Sending " + pendingIntent);
4517 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4518 } catch (PendingIntent.CanceledException e) {
4519 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4520 mPendingIntentWakeLock.release();
4521 releasePendingNetworkRequest(pendingIntent);
4522 }
4523 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4524 }
4525
4526 @Override
4527 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4528 String resultData, Bundle resultExtras) {
4529 if (DBG) log("Finished sending " + pendingIntent);
4530 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004531 // Release with a delay so the receiving client has an opportunity to put in its
4532 // own request.
4533 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004534 }
4535
Robert Greenwalt9258c642014-03-26 16:47:06 -07004536 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004537 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004538 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004539 Bundle bundle = new Bundle();
4540 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4541 new NetworkRequest(nri.request));
4542 Message msg = Message.obtain();
4543 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4544 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4545 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4546 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004547 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004548 case ConnectivityManager.CALLBACK_LOSING: {
4549 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4550 break;
4551 }
4552 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4553 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4554 new NetworkCapabilities(networkAgent.networkCapabilities));
4555 break;
4556 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004557 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004558 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4559 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004560 break;
4561 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004562 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004563 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004564 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004565 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004566 if (VDBG) {
4567 log("sending notification " + notifyTypeToName(notificationType) +
4568 " for " + nri.request);
4569 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004570 nri.messenger.send(msg);
4571 } catch (RemoteException e) {
4572 // may occur naturally in the race of binder death.
4573 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4574 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004575 }
4576
Paul Jensenc8b9a742014-09-30 15:37:41 -04004577 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4578 for (int i = 0; i < nai.networkRequests.size(); i++) {
4579 NetworkRequest nr = nai.networkRequests.valueAt(i);
4580 // Ignore listening requests.
4581 if (!isRequest(nr)) continue;
4582 loge("Dead network still had at least " + nr);
4583 break;
4584 }
4585 nai.asyncChannel.disconnect();
4586 }
4587
Robert Greenwalt7b816022014-04-18 15:25:25 -07004588 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4589 if (oldNetwork == null) {
4590 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4591 return;
4592 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004593 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4594 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004595 }
4596
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004597 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004598 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004599 setupDataActivityTracking(newNetwork);
4600 try {
4601 mNetd.setDefaultNetId(newNetwork.network.netId);
4602 } catch (Exception e) {
4603 loge("Exception setting default network :" + e);
4604 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004605 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004606 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004607 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004608 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004609 }
4610
Paul Jensen2161a8e2014-09-11 11:00:39 -04004611 // Handles a network appearing or improving its score.
4612 //
4613 // - Evaluates all current NetworkRequests that can be
4614 // satisfied by newNetwork, and reassigns to newNetwork
4615 // any such requests for which newNetwork is the best.
4616 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004617 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004618 // needed. A network is needed if it is the best network for
4619 // one or more NetworkRequests, or if it is a VPN.
4620 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004621 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004622 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004623 //
4624 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4625 // networks that have no chance (i.e. even if validated)
4626 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004627 //
4628 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4629 // it does not remove NetworkRequests that other Networks could better satisfy.
4630 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4631 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4632 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004633 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004634 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004635 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4636 // performed to tear down unvalidated networks that have no chance (i.e. even if
4637 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004638 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004639 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Robin Lee585e2482016-05-01 23:00:00 +01004640 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004641 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004642 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004643 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004644 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004645 // Find and migrate to this Network any NetworkRequests for
4646 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004647 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004648 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004649 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004650 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004651 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4652 final boolean satisfies = newNetwork.satisfies(nri.request);
4653 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004654 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004655 log("Network " + newNetwork.name() + " was already satisfying" +
4656 " request " + nri.request.requestId + ". No change.");
4657 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004658 keep = true;
4659 continue;
4660 }
4661
4662 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004663 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004664 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004665 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004666 // This is not a request, it's a callback listener.
4667 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004668 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004669 continue;
4670 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004671
Robert Greenwalt7b816022014-04-18 15:25:25 -07004672 // next check if it's better than any current network we're using for
4673 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004674 if (VDBG) {
4675 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004676 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4677 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004678 }
4679 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004680 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004681 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004682 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004683 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004684 currentNetwork.networkRequests.remove(nri.request.requestId);
4685 currentNetwork.networkLingered.add(nri.request);
4686 affectedNetworks.add(currentNetwork);
4687 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004688 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004689 }
Paul Jensen573a0352015-01-08 10:49:34 -05004690 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004691 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004692 if (!newNetwork.addRequest(nri.request)) {
4693 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4694 }
4695 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004696 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004697 // Tell NetworkFactories about the new score, so they can stop
4698 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004699 // TODO - this could get expensive if we have alot of requests for this
4700 // network. Think about if there is a way to reduce this. Push
4701 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004702 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004703 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004704 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004705 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004706 }
4707 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004708 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4709 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4710 // mark it as no longer satisfying "nri". Because networks are processed by
4711 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4712 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4713 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4714 // This means this code doesn't have to handle the case where "currentNetwork" no
4715 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4716 if (DBG) {
4717 log("Network " + newNetwork.name() + " stopped satisfying" +
4718 " request " + nri.request.requestId);
4719 }
4720 newNetwork.networkRequests.remove(nri.request.requestId);
4721 if (currentNetwork == newNetwork) {
4722 mNetworkForRequestId.remove(nri.request.requestId);
4723 sendUpdatedScoreToFactories(nri.request, 0);
4724 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004725 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004726 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4727 newNetwork.name() +
4728 " without updating mNetworkForRequestId or factories!");
4729 }
4730 }
4731 // TODO: technically, sending CALLBACK_LOST here is
4732 // incorrect if nri is a request (not a listen) and there
4733 // is a replacement network currently connected that can
4734 // satisfy it. However, the only capability that can both
4735 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4736 // so this code is only incorrect for a network that loses
4737 // the TRUSTED capability, which is a rare case.
4738 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004739 }
4740 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004741 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004742 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004743 if (nai.lingering) {
4744 // Already lingered. Nothing to do. This can only happen if "nai" is in
4745 // "affectedNetworks" twice. The reasoning being that to get added to
4746 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4747 // (i.e. not lingered) so it could have only been lingered by this loop.
4748 // unneeded(nai) will be false and we'll call unlinger() below which would
4749 // be bad, so handle it here.
4750 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004751 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004752 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004753 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004754 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004755 }
4756 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004757 if (isNewDefault) {
4758 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004759 makeDefault(newNetwork);
4760 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4761 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004762 synchronized (ConnectivityService.this) {
4763 // have a new default network, release the transition wakelock in
4764 // a second if it's held. The second pause is to allow apps
4765 // to reconnect over the new network
4766 if (mNetTransitionWakeLock.isHeld()) {
4767 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4768 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4769 mNetTransitionWakeLockSerialNumber, 0),
4770 1000);
4771 }
4772 }
4773 }
4774
4775 // do this after the default net is switched, but
4776 // before LegacyTypeTracker sends legacy broadcasts
4777 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4778
4779 if (isNewDefault) {
4780 // Maintain the illusion: since the legacy API only
4781 // understands one network at a time, we must pretend
4782 // that the current default network disconnected before
4783 // the new one connected.
4784 if (oldDefaultNetwork != null) {
4785 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4786 oldDefaultNetwork, true);
4787 }
4788 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4789 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4790 notifyLockdownVpn(newNetwork);
4791 }
4792
Robert Greenwalt7b816022014-04-18 15:25:25 -07004793 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004794 // Notify battery stats service about this network, both the normal
4795 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004796 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004797 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004798 final IBatteryStats bs = BatteryStatsService.getService();
4799 final int type = newNetwork.networkInfo.getType();
4800
4801 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4802 bs.noteNetworkInterfaceType(baseIface, type);
4803 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4804 final String stackedIface = stacked.getInterfaceName();
4805 bs.noteNetworkInterfaceType(stackedIface, type);
4806 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4807 }
4808 } catch (RemoteException ignored) {
4809 }
4810
Robert Greenwalt152ed372014-12-17 17:19:53 -08004811 // This has to happen after the notifyNetworkCallbacks as that tickles each
4812 // ConnectivityManager instance so that legacy requests correctly bind dns
4813 // requests to this network. The legacy users are listening for this bcast
4814 // and will generally do a dns request so they can ensureRouteToHost and if
4815 // they do that before the callbacks happen they'll use the default network.
4816 //
4817 // TODO: Is there still a race here? We send the broadcast
4818 // after sending the callback, but if the app can receive the
4819 // broadcast before the callback, it might still break.
4820 //
4821 // This *does* introduce a race where if the user uses the new api
4822 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4823 // they may get old info. Reverse this after the old startUsing api is removed.
4824 // This is on top of the multiple intent sequencing referenced in the todo above.
4825 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4826 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4827 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4828 // legacy type tracker filters out repeat adds
4829 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4830 }
4831 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004832
4833 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4834 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4835 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4836 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4837 if (newNetwork.isVPN()) {
4838 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4839 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004840 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004841 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4842 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004843 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004844 if (DBG) log("Reaping " + nai.name());
4845 teardownUnneededNetwork(nai);
4846 }
4847 }
4848 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004849 }
4850
Paul Jensen1c7ba022015-06-16 14:27:36 -04004851 /**
4852 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4853 * being disconnected.
4854 * @param changed If only one Network's score or capabilities have been modified since the last
4855 * time this function was called, pass this Network in this argument, otherwise pass
4856 * null.
4857 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4858 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4859 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4860 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4861 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004862 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004863 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004864 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4865 // to avoid the slowness. It is not simply enough to process just "changed", for
4866 // example in the case where "changed"'s score decreases and another network should begin
4867 // satifying a NetworkRequest that "changed" currently satisfies.
4868
4869 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4870 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4871 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004872 if (changed != null && oldScore < changed.getCurrentScore()) {
4873 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004874 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004875 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4876 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4877 // Rematch higher scoring networks first to prevent requests first matching a lower
4878 // scoring network and then a higher scoring network, which could produce multiple
4879 // callbacks and inadvertently unlinger networks.
4880 Arrays.sort(nais);
4881 for (NetworkAgentInfo nai : nais) {
4882 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004883 // Only reap the last time through the loop. Reaping before all rematching
4884 // is complete could incorrectly teardown a network that hasn't yet been
4885 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004886 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004887 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004888 }
4889 }
4890 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004891
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004892 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004893 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004894 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004895 // For now only update icons for default connection.
4896 // TODO: Update WiFi and cellular icons separately. b/17237507
4897 if (!isDefaultNetwork(nai)) return;
4898
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004899 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004900 // Don't repeat publish.
4901 if (newInetCondition == mDefaultInetConditionPublished) return;
4902
4903 mDefaultInetConditionPublished = newInetCondition;
4904 sendInetConditionBroadcast(nai.networkInfo);
4905 }
4906
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004907 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4908 if (mLockdownTracker != null) {
4909 if (nai != null && nai.isVPN()) {
4910 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4911 } else {
4912 mLockdownTracker.onNetworkInfoChanged();
4913 }
4914 }
4915 }
4916
Robert Greenwalt7b816022014-04-18 15:25:25 -07004917 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4918 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004919 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004920 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004921 synchronized (networkAgent) {
4922 oldInfo = networkAgent.networkInfo;
4923 networkAgent.networkInfo = newInfo;
4924 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004925 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004926
4927 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004928 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4929 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4930 notifyIfacesChangedForNetworkStats();
4931 } else if (VDBG) log("ignoring duplicate network state non-change");
4932 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004933 return;
4934 }
4935 if (DBG) {
4936 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4937 (oldInfo == null ? "null" : oldInfo.getState()) +
4938 " to " + state);
4939 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004940
Robin Lee585e2482016-05-01 23:00:00 +01004941 if (!networkAgent.created
4942 && (state == NetworkInfo.State.CONNECTED
4943 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004944 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004945 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004946 if (networkAgent.isVPN()) {
4947 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004948 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4949 (networkAgent.networkMisc == null ||
4950 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004951 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004952 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4953 networkAgent.networkCapabilities.hasCapability(
4954 NET_CAPABILITY_NOT_RESTRICTED) ?
4955 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004956 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004957 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004958 loge("Error creating network " + networkAgent.network.netId + ": "
4959 + e.getMessage());
4960 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004961 }
Paul Jenseneec75412014-08-04 12:21:19 -04004962 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004963 }
4964
4965 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4966 networkAgent.everConnected = true;
4967
Robert Greenwalt7b816022014-04-18 15:25:25 -07004968 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004969 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004970
Paul Jensenca8f16a2014-05-09 12:47:55 -04004971 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004972 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004973
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004974 if (networkAgent.isVPN()) {
4975 // Temporarily disable the default proxy (not global).
4976 synchronized (mProxyLock) {
4977 if (!mDefaultProxyDisabled) {
4978 mDefaultProxyDisabled = true;
4979 if (mGlobalProxy == null && mDefaultProxy != null) {
4980 sendProxyBroadcast(null);
4981 }
4982 }
4983 }
4984 // TODO: support proxy per network.
4985 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004986
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004987 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4988 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4989 // capabilities, so it only needs to be done once on initial connect, not every time the
4990 // network's capabilities change. Note that we do this before rematching the network,
4991 // so we could decide to tear it down immediately afterwards. That's fine though - on
4992 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4993 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004994 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004995
Paul Jensen2161a8e2014-09-11 11:00:39 -04004996 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004997 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004998
4999 // This has to happen after matching the requests, because callbacks are just requests.
5000 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005001 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005002 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005003 if (networkAgent.isVPN()) {
5004 synchronized (mProxyLock) {
5005 if (mDefaultProxyDisabled) {
5006 mDefaultProxyDisabled = false;
5007 if (mGlobalProxy == null && mDefaultProxy != null) {
5008 sendProxyBroadcast(mDefaultProxy);
5009 }
5010 }
5011 }
5012 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005013 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5014 state == NetworkInfo.State.SUSPENDED) {
5015 // going into or coming out of SUSPEND: rescore and notify
5016 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005017 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005018 }
5019 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5020 ConnectivityManager.CALLBACK_SUSPENDED :
5021 ConnectivityManager.CALLBACK_RESUMED));
5022 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005023 }
5024 }
5025
Robert Greenwaltac96c522014-06-03 16:43:57 -07005026 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005027 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005028 if (score < 0) {
5029 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5030 "). Bumping score to min of 0");
5031 score = 0;
5032 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005033
Paul Jensen2161a8e2014-09-11 11:00:39 -04005034 final int oldScore = nai.getCurrentScore();
5035 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005036
Paul Jensen85cf78e2015-06-25 13:25:07 -04005037 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005038
Paul Jensenc8b9a742014-09-30 15:37:41 -04005039 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005040 }
5041
Robert Greenwalt9258c642014-03-26 16:47:06 -07005042 // notify only this one new request of the current state
5043 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5044 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
5045 // TODO - read state from monitor to decide what to send.
5046// if (nai.networkMonitor.isLingering()) {
5047// notifyType = NetworkCallbacks.LOSING;
5048// } else if (nai.networkMonitor.isEvaluating()) {
5049// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5050// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005051 if (nri.mPendingIntent == null) {
5052 callCallbackForRequest(nri, nai, notifyType);
5053 } else {
5054 sendPendingIntentForRequest(nri, nai, notifyType);
5055 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005056 }
5057
Robert Greenwalt8d482522015-06-24 13:23:42 -07005058 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005059 // The NetworkInfo we actually send out has no bearing on the real
5060 // state of affairs. For example, if the default connection is mobile,
5061 // and a request for HIPRI has just gone away, we need to pretend that
5062 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5063 // the state to DISCONNECTED, even though the network is of type MOBILE
5064 // and is still connected.
5065 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5066 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005067 if (state != DetailedState.DISCONNECTED) {
5068 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005069 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005070 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005071 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005072 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5073 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5074 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5075 if (info.isFailover()) {
5076 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5077 nai.networkInfo.setFailover(false);
5078 }
5079 if (info.getReason() != null) {
5080 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5081 }
5082 if (info.getExtraInfo() != null) {
5083 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5084 }
5085 NetworkAgentInfo newDefaultAgent = null;
5086 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005087 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005088 if (newDefaultAgent != null) {
5089 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5090 newDefaultAgent.networkInfo);
5091 } else {
5092 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5093 }
5094 }
5095 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5096 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005097 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005098 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005099 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005100 }
5101 }
5102 }
5103
Robert Greenwalt7b816022014-04-18 15:25:25 -07005104 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005105 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005106 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005107 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
5108 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5109 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005110 if (nri.mPendingIntent == null) {
5111 callCallbackForRequest(nri, networkAgent, notifyType);
5112 } else {
5113 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5114 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005115 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005116 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005117
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005118 private String notifyTypeToName(int notifyType) {
5119 switch (notifyType) {
5120 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5121 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5122 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5123 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5124 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5125 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5126 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5127 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5128 }
5129 return "UNKNOWN";
5130 }
5131
Jeff Sharkey69736342014-12-08 14:50:12 -08005132 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005133 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5134 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005135 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005136 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005137 try {
5138 mStatsService.forceUpdateIfaces();
5139 } catch (Exception ignored) {
5140 }
5141 }
5142
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005143 @Override
5144 public boolean addVpnAddress(String address, int prefixLength) {
5145 throwIfLockdownEnabled();
5146 int user = UserHandle.getUserId(Binder.getCallingUid());
5147 synchronized (mVpns) {
5148 return mVpns.get(user).addAddress(address, prefixLength);
5149 }
5150 }
5151
5152 @Override
5153 public boolean removeVpnAddress(String address, int prefixLength) {
5154 throwIfLockdownEnabled();
5155 int user = UserHandle.getUserId(Binder.getCallingUid());
5156 synchronized (mVpns) {
5157 return mVpns.get(user).removeAddress(address, prefixLength);
5158 }
5159 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005160
5161 @Override
5162 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5163 throwIfLockdownEnabled();
5164 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005165 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005166 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005167 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005168 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005169 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005170 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005171 }
5172 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005173 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005174
5175 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005176 public String getCaptivePortalServerUrl() {
5177 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5178 }
5179
5180 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005181 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5182 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5183 enforceKeepalivePermission();
5184 mKeepaliveTracker.startNattKeepalive(
5185 getNetworkAgentInfoForNetwork(network),
5186 intervalSeconds, messenger, binder,
5187 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5188 }
5189
5190 @Override
5191 public void stopKeepalive(Network network, int slot) {
5192 mHandler.sendMessage(mHandler.obtainMessage(
5193 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5194 }
5195
5196 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005197 public void factoryReset() {
5198 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005199
5200 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5201 return;
5202 }
5203
Robin Lee3b3dd942015-05-12 18:14:58 +01005204 final int userId = UserHandle.getCallingUserId();
5205
Stuart Scottf1fb3972015-04-02 18:00:02 -07005206 // Turn airplane mode off
5207 setAirplaneMode(false);
5208
Stuart Scotte3e314d2015-04-20 14:07:45 -07005209 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5210 // Untether
5211 for (String tether : getTetheredIfaces()) {
5212 untether(tether);
5213 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005214 }
5215
Stuart Scotte3e314d2015-04-20 14:07:45 -07005216 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005217 // Remove always-on package
5218 synchronized (mVpns) {
5219 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5220 if (alwaysOnPackage != null) {
5221 setAlwaysOnVpnPackage(userId, null, false);
5222 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5223 }
5224 }
5225
Stuart Scotte3e314d2015-04-20 14:07:45 -07005226 // Turn VPN off
5227 VpnConfig vpnConfig = getVpnConfig(userId);
5228 if (vpnConfig != null) {
5229 if (vpnConfig.legacy) {
5230 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5231 } else {
5232 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5233 // in the future without user intervention.
5234 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005235
Victor Changb04a5ea2016-05-30 20:36:30 +01005236 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005237 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005238 }
5239 }
5240 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005241
5242 @VisibleForTesting
5243 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5244 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5245 return new NetworkMonitor(context, handler, nai, defaultRequest);
5246 }
Erik Kline48f12f22016-04-14 17:30:59 +09005247
Hugo Benichicfddd682016-05-31 16:28:06 +09005248 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005249 int newNetid = NETID_UNSET;
5250 int prevNetid = NETID_UNSET;
5251 int[] transports = new int[0];
5252 boolean hadIPv4 = false;
5253 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005254
Hugo Benichi5f16f762016-04-20 12:09:33 +09005255 if (newNai != null) {
5256 newNetid = newNai.network.netId;
5257 transports = newNai.networkCapabilities.getTransportTypes();
5258 }
5259 if (prevNai != null) {
5260 prevNetid = prevNai.network.netId;
5261 final LinkProperties lp = prevNai.linkProperties;
5262 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5263 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5264 }
5265
Hugo Benichicfddd682016-05-31 16:28:06 +09005266 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5267 }
5268
5269 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5270 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272}