blob: 8763b93f31b9fa0a9be5b3dd90560d2f9e06e3de [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 Lemed31a97f2016-05-06 14:53:50 -070033import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
34import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
Felipe Leme46c4fc32016-05-04 09:21:43 -070035import static android.net.NetworkPolicyManager.RULE_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070036import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070038import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060039
Wenchao Tongf5ea3402015-03-04 13:26:38 -080040import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080041import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070042import android.app.Notification;
43import android.app.NotificationManager;
44import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070045import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.ContentResolver;
47import android.content.Context;
48import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070049import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070051import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090052import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070053import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090055import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070057import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070058import android.net.INetworkPolicyListener;
59import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070060import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080061import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070062import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070063import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070064import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070065import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070066import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070068import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070069import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070070import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070071import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070072import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070073import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070074import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040075import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070076import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040077import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040078import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090079import android.net.metrics.DefaultNetworkEvent;
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;
Felipe Lemed31a97f2016-05-06 14:53:50 -0700221 /** Flag indicating if background data is restricted due to battery savings. */
222 @GuardedBy("mRulesLock")
223 private boolean mRestrictPower;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700224
Erik Klineda4bfa82015-04-30 12:58:40 +0900225 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700227 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700228 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800230 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
232 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700233 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700235 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800236 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700237 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700238
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700239 private String mCurrentTcpBufferSizes;
240
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241 private static final int ENABLED = 1;
242 private static final int DISABLED = 0;
243
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900244 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
245 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class });
246
Paul Jensenb10e37f2014-11-25 12:33:08 -0500247 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400248 // Tear down networks that have no chance (e.g. even if validated) of becoming
249 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500250 // all networks have been rematched against all NetworkRequests.
251 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400252 // Don't reap networks. This should be passed when some networks have not yet been
253 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500254 DONT_REAP
255 };
256
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700257 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700258 * used internally to change our mobile data enabled flag
259 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700260 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700261
262 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700263 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700264 * from one net to another. Clear happens when we get a new
265 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
266 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700267 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700268 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700269
Robert Greenwalt434203a2010-10-11 16:00:27 -0700270 /**
271 * used internally to reload global proxy settings
272 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700273 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700274
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700275 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400276 * PAC manager has received new port.
277 */
278 private static final int EVENT_PROXY_HAS_CHANGED = 16;
279
Robert Greenwalte049c232014-04-11 15:53:27 -0700280 /**
281 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700282 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700283 */
284 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
285
Robert Greenwalt7b816022014-04-18 15:25:25 -0700286 /**
287 * used internally when registering NetworkAgents
288 * obj = Messenger
289 */
290 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
291
Robert Greenwalt9258c642014-03-26 16:47:06 -0700292 /**
293 * used to add a network request
294 * includes a NetworkRequestInfo
295 */
296 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
297
298 /**
299 * indicates a timeout period is over - check if we had a network yet or not
300 * and if not, call the timeout calback (but leave the request live until they
301 * cancel it.
302 * includes a NetworkRequestInfo
303 */
304 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
305
306 /**
307 * used to add a network listener - no request
308 * includes a NetworkRequestInfo
309 */
310 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
311
312 /**
313 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400314 * arg1 = UID of caller
315 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700316 */
317 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
318
Robert Greenwalta67be032014-05-16 15:49:14 -0700319 /**
320 * used internally when registering NetworkFactories
321 * obj = Messenger
322 */
323 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
324
Robert Greenwalt27711812014-06-25 16:45:57 -0700325 /**
326 * used internally to expire a wakelock when transitioning
327 * from one net to another. Expire happens when we fail to find
328 * a new network (typically after 1 minute) -
329 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
330 * a replacement network.
331 */
332 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
333
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700334 /**
335 * Used internally to indicate the system is ready.
336 */
337 private static final int EVENT_SYSTEM_READY = 25;
338
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800339 /**
340 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400341 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800342 */
343 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
344
345 /**
346 * used to remove a pending intent and its associated network request.
347 * arg1 = UID of caller
348 * obj = PendingIntent
349 */
350 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
351
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900352 /**
353 * used to specify whether a network should be used even if unvalidated.
354 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
355 * arg2 = whether to remember this choice in the future (1 or 0)
356 * obj = network
357 */
358 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
359
360 /**
361 * used to ask the user to confirm a connection to an unvalidated network.
362 * obj = network
363 */
364 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700365
Erik Klineda4bfa82015-04-30 12:58:40 +0900366 /**
367 * used internally to (re)configure mobile data always-on settings.
368 */
369 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
370
Paul Jensen694f2b82015-06-17 14:15:39 -0400371 /**
372 * used to add a network listener with a pending intent
373 * obj = NetworkRequestInfo
374 */
375 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
376
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900377 /** Handler thread used for both of the handlers below. */
378 @VisibleForTesting
379 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700380 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700381 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700382 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700383 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700384
Mike Lockwood0f79b542009-08-14 14:18:49 -0400385 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800386 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400387
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700388 private PowerManager.WakeLock mNetTransitionWakeLock;
389 private String mNetTransitionWakeLockCausedBy = "";
390 private int mNetTransitionWakeLockSerialNumber;
391 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800392 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700393
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700394 // used in DBG mode to track inet condition reports
395 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
396 private ArrayList mInetLog;
397
Robert Greenwalt434203a2010-10-11 16:00:27 -0700398 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400399 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700400 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700401 private boolean mDefaultProxyDisabled = false;
402
Robert Greenwalt434203a2010-10-11 16:00:27 -0700403 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400404 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700405
Jason Monk602b2322013-07-03 17:04:33 -0400406 private PacManager mPacManager = null;
407
Erik Klineda4bfa82015-04-30 12:58:40 +0900408 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700409
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400410 private UserManager mUserManager;
411
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700412 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700413 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700414
Robert Greenwalt50393202011-06-21 17:26:14 -0700415 // the set of network types that can only be enabled by system/sig apps
416 List mProtectedNetworks;
417
John Spurlockbf991a82013-06-24 14:20:23 -0400418 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700419
Wink Savilleab9321d2013-06-29 21:10:57 -0700420 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400421
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900422 private KeepaliveTracker mKeepaliveTracker;
423
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700424 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
425 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700426 private final static int MAX_NET_ID = 65535;
427 private int mNextNetId = MIN_NET_ID;
428
Robert Greenwalt34524f02014-05-18 16:22:10 -0700429 // sequence number of NetworkRequests
430 private int mNextNetworkRequestId = 1;
431
Erik Kline7523eb32015-07-09 18:24:03 +0900432 // NetworkRequest activity String log entries.
433 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
434 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
435
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700436 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
437 private static final int MAX_VALIDATION_LOGS = 10;
438 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
439 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
440
441 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
442 synchronized(mValidationLogs) {
443 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
444 mValidationLogs.removeLast();
445 }
446 mValidationLogs.addFirst(new Pair(network, log));
447 }
448 }
449
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700450 /**
451 * Implements support for the legacy "one network per network type" model.
452 *
453 * We used to have a static array of NetworkStateTrackers, one for each
454 * network type, but that doesn't work any more now that we can have,
455 * for example, more that one wifi network. This class stores all the
456 * NetworkAgentInfo objects that support a given type, but the legacy
457 * API will only see the first one.
458 *
459 * It serves two main purposes:
460 *
461 * 1. Provide information about "the network for a given type" (since this
462 * API only supports one).
463 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
464 * the first network for a given type changes, or if the default network
465 * changes.
466 */
467 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900468
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900469 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900470 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900471
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700472 /**
473 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
474 * Each list holds references to all NetworkAgentInfos that are used to
475 * satisfy requests for that network type.
476 *
477 * This array is built out at startup such that an unsupported network
478 * doesn't get an ArrayList instance, making this a tristate:
479 * unsupported, supported but not active and active.
480 *
481 * The actual lists are populated when we scan the network types that
482 * are supported on this device.
483 */
484 private ArrayList<NetworkAgentInfo> mTypeLists[];
485
486 public LegacyTypeTracker() {
487 mTypeLists = (ArrayList<NetworkAgentInfo>[])
488 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
489 }
490
491 public void addSupportedType(int type) {
492 if (mTypeLists[type] != null) {
493 throw new IllegalStateException(
494 "legacy list for type " + type + "already initialized");
495 }
496 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
497 }
498
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700499 public boolean isTypeSupported(int type) {
500 return isNetworkTypeValid(type) && mTypeLists[type] != null;
501 }
502
503 public NetworkAgentInfo getNetworkForType(int type) {
504 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
505 return mTypeLists[type].get(0);
506 } else {
507 return null;
508 }
509 }
510
Robert Greenwalt8d482522015-06-24 13:23:42 -0700511 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900512 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700514 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900516 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900517 }
518 }
519
520 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700521 public void add(int type, NetworkAgentInfo nai) {
522 if (!isTypeSupported(type)) {
523 return; // Invalid network type.
524 }
525 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
526
527 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
528 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700529 return;
530 }
531
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900532 list.add(nai);
533
534 // 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 +0900535 final boolean isDefaultNetwork = isDefaultNetwork(nai);
536 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700537 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
538 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700539 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700540 }
541
Lorenzo Colittia793a672014-07-31 23:20:17 +0900542 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900543 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900544 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
545 if (list == null || list.isEmpty()) {
546 return;
547 }
548
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900549 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900550
551 if (!list.remove(nai)) {
552 return;
553 }
554
Robert Greenwalt8d482522015-06-24 13:23:42 -0700555 final DetailedState state = DetailedState.DISCONNECTED;
556
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900557 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700558 maybeLogBroadcast(nai, state, type, wasDefault);
559 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900560 }
561
562 if (!list.isEmpty() && wasFirstNetwork) {
563 if (DBG) log("Other network available for type " + type +
564 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900565 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700566 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
567 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900568 }
569 }
570
571 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900572 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
573 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700574 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900575 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700576 }
577 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700578
Robert Greenwalt8d482522015-06-24 13:23:42 -0700579 // send out another legacy broadcast - currently only used for suspend/unsuspend
580 // toggle
581 public void update(NetworkAgentInfo nai) {
582 final boolean isDefault = isDefaultNetwork(nai);
583 final DetailedState state = nai.networkInfo.getDetailedState();
584 for (int type = 0; type < mTypeLists.length; type++) {
585 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700586 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700587 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700588 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700589 maybeLogBroadcast(nai, state, type, isDefault);
590 sendLegacyNetworkBroadcast(nai, state, type);
591 }
592 }
593 }
594
Lorenzo Colittia793a672014-07-31 23:20:17 +0900595 private String naiToString(NetworkAgentInfo nai) {
596 String name = (nai != null) ? nai.name() : "null";
597 String state = (nai.networkInfo != null) ?
598 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
599 "???/???";
600 return name + " " + state;
601 }
602
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700603 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900604 pw.println("mLegacyTypeTracker:");
605 pw.increaseIndent();
606 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700607 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900608 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700609 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900610 pw.println();
611 pw.println("Current state:");
612 pw.increaseIndent();
613 for (int type = 0; type < mTypeLists.length; type++) {
614 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
615 for (NetworkAgentInfo nai : mTypeLists[type]) {
616 pw.println(type + " " + naiToString(nai));
617 }
618 }
619 pw.decreaseIndent();
620 pw.decreaseIndent();
621 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700622 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700623 }
624 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
625
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900626 @VisibleForTesting
627 protected HandlerThread createHandlerThread() {
628 return new HandlerThread("ConnectivityServiceThread");
629 }
630
Jeff Sharkey899223b2012-08-04 15:24:58 -0700631 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700632 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800633 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800634
Erik Klineda4bfa82015-04-30 12:58:40 +0900635 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900636 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
Erik Kline371c7b72016-03-22 17:04:20 +0900637 new Binder(), NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +0900638 mNetworkRequests.put(mDefaultRequest, defaultNRI);
639 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900640
641 mDefaultMobileDataRequest = createInternetRequestForTransport(
642 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700643
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900644 mHandlerThread = createHandlerThread();
645 mHandlerThread.start();
646 mHandler = new InternalHandler(mHandlerThread.getLooper());
647 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700648
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800649 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800650 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
651 String id = Settings.Secure.getString(context.getContentResolver(),
652 Settings.Secure.ANDROID_ID);
653 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700654 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800655 SystemProperties.set("net.hostname", name);
656 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800657 }
658
Jeremy Joslin79294842014-12-03 17:15:28 -0800659 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
660 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
661
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700662 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700663 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800664 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700665 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700666 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700667 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700668
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700669 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600670 mPolicyManager.setConnectivityListener(mPolicyListener);
671 mRestrictBackground = mPolicyManager.getRestrictBackground();
Felipe Lemed31a97f2016-05-06 14:53:50 -0700672 mRestrictPower = mPolicyManager.getRestrictPower();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700673 } catch (RemoteException e) {
674 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700675 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700676 }
677
678 final PowerManager powerManager = (PowerManager) context.getSystemService(
679 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700680 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
681 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
682 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800683 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700684
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700685 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700686
Wink Saville51f456f2013-04-23 14:26:51 -0700687 // TODO: What is the "correct" way to do determine if this is a wifi only device?
688 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
689 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700690 String[] naStrings = context.getResources().getStringArray(
691 com.android.internal.R.array.networkAttributes);
692 for (String naString : naStrings) {
693 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700694 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700695 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700696 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800697 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700698 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700699 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700700 }
Wink Saville51f456f2013-04-23 14:26:51 -0700701 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
702 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
703 n.type);
704 continue;
705 }
Wink Saville975c8482011-04-07 14:23:45 -0700706 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800707 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700708 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700709 continue;
710 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700711 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700712
Wink Saville975c8482011-04-07 14:23:45 -0700713 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700714 mNetworksDefined++;
715 } catch(Exception e) {
716 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700717 }
718 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700719
720 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
721 if (mNetConfigs[TYPE_VPN] == null) {
722 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
723 // don't need to add TYPE_VPN to mNetConfigs.
724 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
725 mNetworksDefined++; // used only in the log() statement below.
726 }
727
Wink Saville5e56bc52013-07-29 15:00:57 -0700728 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700729
Robert Greenwalt50393202011-06-21 17:26:14 -0700730 mProtectedNetworks = new ArrayList<Integer>();
731 int[] protectedNetworks = context.getResources().getIntArray(
732 com.android.internal.R.array.config_protectedNetworks);
733 for (int p : protectedNetworks) {
734 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
735 mProtectedNetworks.add(p);
736 } else {
737 if (DBG) loge("Ignoring protectedNetwork " + p);
738 }
739 }
740
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700741 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
742 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700743
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800744 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800745
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700746 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
747
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700748 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700749 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100750 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700751 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700752 intentFilter.addAction(Intent.ACTION_USER_ADDED);
753 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000754 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700755 mContext.registerReceiverAsUser(
756 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900757
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700758 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700759 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700760 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700761 } catch (RemoteException e) {
762 loge("Error registering observer :" + e);
763 }
764
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700765 if (DBG) {
766 mInetLog = new ArrayList();
767 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700768
Erik Klineda4bfa82015-04-30 12:58:40 +0900769 mSettingsObserver = new SettingsObserver(mContext, mHandler);
770 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800771
John Spurlockbf991a82013-06-24 14:20:23 -0400772 mDataConnectionStats = new DataConnectionStats(mContext);
773 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400774
Jason Monkdecd2952013-10-10 14:02:51 -0400775 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700776
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400777 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900778
779 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700781
Erik Klineda4bfa82015-04-30 12:58:40 +0900782 private NetworkRequest createInternetRequestForTransport(int transportType) {
783 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900784 netCap.addCapability(NET_CAPABILITY_INTERNET);
785 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900786 if (transportType > -1) {
787 netCap.addTransportType(transportType);
788 }
789 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
790 }
791
792 private void handleMobileDataAlwaysOn() {
793 final boolean enable = (Settings.Global.getInt(
794 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
795 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
796 if (enable == isEnabled) {
797 return; // Nothing to do.
798 }
799
800 if (enable) {
801 handleRegisterNetworkRequest(new NetworkRequestInfo(
Erik Kline371c7b72016-03-22 17:04:20 +0900802 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
Erik Klineda4bfa82015-04-30 12:58:40 +0900803 } else {
804 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
805 }
806 }
807
808 private void registerSettingsCallbacks() {
809 // Watch for global HTTP proxy changes.
810 mSettingsObserver.observe(
811 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
812 EVENT_APPLY_GLOBAL_HTTP_PROXY);
813
814 // Watch for whether or not to keep mobile data always on.
815 mSettingsObserver.observe(
816 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
817 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
818 }
819
Robert Greenwalt34524f02014-05-18 16:22:10 -0700820 private synchronized int nextNetworkRequestId() {
821 return mNextNetworkRequestId++;
822 }
823
Paul Jensen67b0b072015-06-10 11:22:17 -0400824 @VisibleForTesting
825 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400826 synchronized (mNetworkForNetId) {
827 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
828 int netId = mNextNetId;
829 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
830 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500831 if (!mNetIdInUse.get(netId)) {
832 mNetIdInUse.put(netId, true);
833 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400834 }
835 }
836 }
837 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700838 }
839
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600840 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800841 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600842 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
843 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800844 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600845 state = nai.getNetworkState();
846 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800847 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600848 final NetworkInfo info = new NetworkInfo(networkType, 0,
849 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800850 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
851 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600852 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
853 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800854 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600855 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600856 return state;
857 } else {
858 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800859 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400860 }
861
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800862 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
863 if (network == null) {
864 return null;
865 }
866 synchronized (mNetworkForNetId) {
867 return mNetworkForNetId.get(network.netId);
868 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600869 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800870
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900871 private Network[] getVpnUnderlyingNetworks(int uid) {
872 if (!mLockdownEnabled) {
873 int user = UserHandle.getUserId(uid);
874 synchronized (mVpns) {
875 Vpn vpn = mVpns.get(user);
876 if (vpn != null && vpn.appliesToUid(uid)) {
877 return vpn.getUnderlyingNetworks();
878 }
879 }
880 }
881 return null;
882 }
883
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800884 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400885 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800886
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900887 final Network[] networks = getVpnUnderlyingNetworks(uid);
888 if (networks != null) {
889 // getUnderlyingNetworks() returns:
890 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
891 // empty array => the VPN explicitly said "no default network".
892 // non-empty array => the VPN specified one or more default networks; we use the
893 // first one.
894 if (networks.length > 0) {
895 nai = getNetworkAgentInfoForNetwork(networks[0]);
896 } else {
897 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800898 }
899 }
900
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800901 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600902 return nai.getNetworkState();
903 } else {
904 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800905 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400906 }
907
908 /**
909 * Check if UID should be blocked from using the network with the given LinkProperties.
910 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600911 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
912 boolean ignoreBlocked) {
913 // Networks aren't blocked when ignoring blocked status
914 if (ignoreBlocked) return false;
915 // Networks are never blocked for system services
916 if (uid < Process.FIRST_APPLICATION_UID) return false;
917
918 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700919 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700920
Robert Greenwalt12e67352014-05-13 21:41:06 -0700921 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700922 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600923 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -0700924 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700925 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700926
Felipe Lemed31a97f2016-05-06 14:53:50 -0700927 boolean allowed = true;
928 // Check Data Saver Mode first...
929 if (networkMetered) {
930 if ((uidRules & RULE_REJECT_METERED) != 0) {
931 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
932 // Explicitly blacklisted.
933 allowed = false;
934 } else {
935 allowed = !mRestrictBackground
936 || (uidRules & RULE_ALLOW_METERED) != 0
937 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
938 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
939 + " mRestrictBackground=" + mRestrictBackground
940 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
941 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
942 + ": " + allowed);
943 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700944 }
Felipe Lemed31a97f2016-05-06 14:53:50 -0700945 // ...then Battery Saver Mode.
946 if (allowed && mRestrictPower) {
947 allowed = (uidRules & RULE_ALLOW_ALL) != 0;
948 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
949 + " mRestrictPower=" + mRestrictPower
950 + ", whitelisted=" + ((uidRules & RULE_ALLOW_ALL) != 0)
951 + ": " + allowed);
952 }
953 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700954 }
955
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900956 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
957 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
958 boolean removed = false;
959 boolean added = false;
960 synchronized (mBlockedAppUids) {
961 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
962 added = true;
963 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
964 removed = true;
965 }
966 }
967 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
968 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
969 }
970
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700971 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600972 * Apply any relevant filters to {@link NetworkState} for the given UID. For
973 * example, this may mark the network as {@link DetailedState#BLOCKED} based
974 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
975 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700976 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600977 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600978 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
979
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600980 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600981 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700982 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600983 if (mLockdownTracker != null) {
984 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700985 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600986
987 // TODO: apply metered state closer to NetworkAgentInfo
988 final long token = Binder.clearCallingIdentity();
989 try {
990 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
991 } catch (RemoteException e) {
992 } finally {
993 Binder.restoreCallingIdentity(token);
994 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700995 }
996
997 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 * Return NetworkInfo for the active (i.e., connected) network interface.
999 * It is assumed that at most one network is active at a time. If more
1000 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001001 * @return the info for the active network, or {@code null} if none is
1002 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001004 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001006 enforceAccessPermission();
1007 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001008 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001009 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001010 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1011 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
1013
Paul Jensen31a94f42015-02-13 14:18:39 -05001014 @Override
1015 public Network getActiveNetwork() {
1016 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001017 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001018 }
1019
1020 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001021 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001022 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001023 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001024 }
1025
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001026 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001027 final int user = UserHandle.getUserId(uid);
1028 int vpnNetId = NETID_UNSET;
1029 synchronized (mVpns) {
1030 final Vpn vpn = mVpns.get(user);
1031 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1032 }
1033 NetworkAgentInfo nai;
1034 if (vpnNetId != NETID_UNSET) {
1035 synchronized (mNetworkForNetId) {
1036 nai = mNetworkForNetId.get(vpnNetId);
1037 }
1038 if (nai != null) return nai.network;
1039 }
1040 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001041 if (nai != null
1042 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1043 nai = null;
1044 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001045 return nai != null ? nai.network : null;
1046 }
1047
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001048 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1049 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001050 final int uid = Binder.getCallingUid();
1051 NetworkState state = getUnfilteredActiveNetworkState(uid);
1052 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001053 }
1054
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001055 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001056 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001057 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001058 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001059 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001060 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001061 }
1062
1063 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 public NetworkInfo getNetworkInfo(int networkType) {
1065 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001066 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001067 if (getVpnUnderlyingNetworks(uid) != null) {
1068 // A VPN is active, so we may need to return one of its underlying networks. This
1069 // information is not available in LegacyTypeTracker, so we have to get it from
1070 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001071 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001072 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001073 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001074 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001075 }
1076 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001077 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001078 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 }
1080
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001081 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001082 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001083 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001084 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001085 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001086 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001087 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001088 return state.networkInfo;
1089 } else {
1090 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001091 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001092 }
1093
1094 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 public NetworkInfo[] getAllNetworkInfo() {
1096 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001097 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001098 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1099 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001100 NetworkInfo info = getNetworkInfo(networkType);
1101 if (info != null) {
1102 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001105 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
1107
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001108 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001109 public Network getNetworkForType(int networkType) {
1110 enforceAccessPermission();
1111 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001112 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1113 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001114 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001115 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001116 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001117 }
1118
1119 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001120 public Network[] getAllNetworks() {
1121 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001122 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001123 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001124 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001125 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001126 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001127 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001128 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001129 }
1130
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001131 @Override
1132 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1133 // The basic principle is: if an app's traffic could possibly go over a
1134 // network, without the app doing anything multinetwork-specific,
1135 // (hence, by "default"), then include that network's capabilities in
1136 // the array.
1137 //
1138 // In the normal case, app traffic only goes over the system's default
1139 // network connection, so that's the only network returned.
1140 //
1141 // With a VPN in force, some app traffic may go into the VPN, and thus
1142 // over whatever underlying networks the VPN specifies, while other app
1143 // traffic may go over the system default network (e.g.: a split-tunnel
1144 // VPN, or an app disallowed by the VPN), so the set of networks
1145 // returned includes the VPN's underlying networks and the system
1146 // default.
1147 enforceAccessPermission();
1148
1149 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1150
1151 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001152 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001153 if (nc != null) {
1154 result.put(nai.network, nc);
1155 }
1156
1157 if (!mLockdownEnabled) {
1158 synchronized (mVpns) {
1159 Vpn vpn = mVpns.get(userId);
1160 if (vpn != null) {
1161 Network[] networks = vpn.getUnderlyingNetworks();
1162 if (networks != null) {
1163 for (Network network : networks) {
1164 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001165 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001166 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001167 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001168 }
1169 }
1170 }
1171 }
1172 }
1173 }
1174
1175 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1176 out = result.values().toArray(out);
1177 return out;
1178 }
1179
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001180 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001181 public boolean isNetworkSupported(int networkType) {
1182 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001183 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001184 }
1185
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001186 /**
1187 * Return LinkProperties for the active (i.e., connected) default
1188 * network interface. It is assumed that at most one default network
1189 * is active at a time. If more than one is active, it is indeterminate
1190 * which will be returned.
1191 * @return the ip properties for the active network, or {@code null} if
1192 * none is active
1193 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001194 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001195 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001196 enforceAccessPermission();
1197 final int uid = Binder.getCallingUid();
1198 NetworkState state = getUnfilteredActiveNetworkState(uid);
1199 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001200 }
1201
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001202 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001203 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001204 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001205 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1206 if (nai != null) {
1207 synchronized (nai) {
1208 return new LinkProperties(nai.linkProperties);
1209 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001210 }
1211 return null;
1212 }
1213
Robert Greenwalt12e67352014-05-13 21:41:06 -07001214 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001215 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001216 public LinkProperties getLinkProperties(Network network) {
1217 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001218 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001219 if (nai != null) {
1220 synchronized (nai) {
1221 return new LinkProperties(nai.linkProperties);
1222 }
1223 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001224 return null;
1225 }
1226
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001227 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001228 if (nai != null) {
1229 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001230 if (nai.networkCapabilities != null) {
1231 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001232 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001233 }
1234 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001235 return null;
1236 }
1237
1238 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001239 public NetworkCapabilities getNetworkCapabilities(Network network) {
1240 enforceAccessPermission();
1241 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1242 }
1243
1244 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001245 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001246 // Require internal since we're handing out IMSI details
1247 enforceConnectivityInternalPermission();
1248
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001249 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001250 for (Network network : getAllNetworks()) {
1251 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1252 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001253 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001254 }
1255 }
1256 return result.toArray(new NetworkState[result.size()]);
1257 }
1258
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001259 @Override
1260 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1261 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001262 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001263 final long token = Binder.clearCallingIdentity();
1264 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001265 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1266 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001267 try {
1268 return mPolicyManager.getNetworkQuotaInfo(state);
1269 } catch (RemoteException e) {
1270 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001271 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001272 return null;
1273 } finally {
1274 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001275 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001276 }
1277
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001278 @Override
1279 public boolean isActiveNetworkMetered() {
1280 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001281
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001282 final NetworkInfo info = getActiveNetworkInfo();
1283 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001284 }
1285
Jeff Sharkey216c1812012-08-05 14:29:23 -07001286 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1287 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001288 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001289 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001290 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001291 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001292 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001293
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001294 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 * Ensure that a network route exists to deliver traffic to the specified
1296 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001297 * @param networkType the type of the network over which traffic to the
1298 * specified host is to be routed
1299 * @param hostAddress the IP address of the host to which the route is
1300 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 * @return {@code true} on success, {@code false} on failure
1302 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001303 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001305 if (mProtectedNetworks.contains(networkType)) {
1306 enforceConnectivityInternalPermission();
1307 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001308
Chad Brubakerc0234532014-02-14 13:24:29 -08001309 InetAddress addr;
1310 try {
1311 addr = InetAddress.getByAddress(hostAddress);
1312 } catch (UnknownHostException e) {
1313 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1314 return false;
1315 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001318 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 return false;
1320 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001321
1322 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1323 if (nai == null) {
1324 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1325 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1326 } else {
1327 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1328 }
1329 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001330 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001331
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001332 DetailedState netState;
1333 synchronized (nai) {
1334 netState = nai.networkInfo.getDetailedState();
1335 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001336
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001337 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001338 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001339 log("requestRouteToHostAddress on down network "
1340 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001341 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001342 }
1343 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001345
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001346 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001347 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001348 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001349 LinkProperties lp;
1350 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001351 synchronized (nai) {
1352 lp = nai.linkProperties;
1353 netId = nai.network.netId;
1354 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001355 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001356 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1357 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001358 } finally {
1359 Binder.restoreCallingIdentity(token);
1360 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001361 }
1362
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001363 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001364 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001365 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001366 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001367 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001368 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001369 if (bestRoute.getGateway().equals(addr)) {
1370 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001371 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001372 } else {
1373 // if we will connect to this through another route, add a direct route
1374 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001375 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001376 }
1377 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001378 if (DBG) log("Adding legacy route " + bestRoute +
1379 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001380 try {
1381 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1382 } catch (Exception e) {
1383 // never crash - catch them all
1384 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001385 return false;
1386 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001387 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 }
1389
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001390 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1391 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001392 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001393 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001394 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001395 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001396 }
1397
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001398 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001399 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001400 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001401 if (oldRules == uidRules) return;
1402
1403 mUidRules.put(uid, uidRules);
1404 }
1405
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001406 // TODO: notify UID when it has requested targeted updates
1407 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001408
1409 @Override
1410 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001411 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001412 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001413 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001414 }
1415
1416 synchronized (mRulesLock) {
1417 mMeteredIfaces.clear();
1418 for (String iface : meteredIfaces) {
1419 mMeteredIfaces.add(iface);
1420 }
1421 }
1422 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001423
1424 @Override
1425 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1426 // caller is NPMS, since we only register with them
1427 if (LOGD_RULES) {
1428 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1429 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001430
1431 synchronized (mRulesLock) {
1432 mRestrictBackground = restrictBackground;
1433 }
1434
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001435 if (restrictBackground) {
1436 log("onRestrictBackgroundChanged(true): disabling tethering");
1437 mTethering.untetherAll();
1438 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001439 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001440
1441 @Override
Felipe Lemed31a97f2016-05-06 14:53:50 -07001442 public void onRestrictPowerChanged(boolean restrictPower) {
1443 // caller is NPMS, since we only register with them
1444 if (LOGD_RULES) {
1445 log("onRestrictPowerChanged(restrictPower=" + restrictPower + ")");
1446 }
1447
1448 synchronized (mRulesLock) {
1449 mRestrictPower = restrictPower;
1450 }
1451 }
1452
1453 @Override
Felipe Leme019fcd22016-04-19 10:24:39 -07001454 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1455 if (LOGD_RULES) {
1456 // caller is NPMS, since we only register with them
1457 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1458 + whitelisted + ")");
1459 }
1460 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001461 };
1462
Robin Lee3b3dd942015-05-12 18:14:58 +01001463 /**
1464 * Require that the caller is either in the same user or has appropriate permission to interact
1465 * across users.
1466 *
1467 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1468 */
1469 private void enforceCrossUserPermission(int userId) {
1470 if (userId == UserHandle.getCallingUserId()) {
1471 // Not a cross-user call.
1472 return;
1473 }
1474 mContext.enforceCallingOrSelfPermission(
1475 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1476 "ConnectivityService");
1477 }
1478
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001479 private void enforceInternetPermission() {
1480 mContext.enforceCallingOrSelfPermission(
1481 android.Manifest.permission.INTERNET,
1482 "ConnectivityService");
1483 }
1484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001486 mContext.enforceCallingOrSelfPermission(
1487 android.Manifest.permission.ACCESS_NETWORK_STATE,
1488 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490
1491 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001492 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 }
1494
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001495 private void enforceTetherAccessPermission() {
1496 mContext.enforceCallingOrSelfPermission(
1497 android.Manifest.permission.ACCESS_NETWORK_STATE,
1498 "ConnectivityService");
1499 }
1500
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001501 private void enforceConnectivityInternalPermission() {
1502 mContext.enforceCallingOrSelfPermission(
1503 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1504 "ConnectivityService");
1505 }
1506
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001507 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001508 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001509 }
1510
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001511 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001512 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001513 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001514 }
1515
1516 private void sendInetConditionBroadcast(NetworkInfo info) {
1517 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1518 }
1519
Wink Saville628b0852011-08-04 15:01:58 -07001520 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001521 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001522 info = new NetworkInfo(info);
1523 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001524 }
1525
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001526 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001527 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001528 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 if (info.isFailover()) {
1530 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1531 info.setFailover(false);
1532 }
1533 if (info.getReason() != null) {
1534 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1535 }
1536 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001537 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1538 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001540 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001541 return intent;
1542 }
1543
1544 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1545 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1546 }
1547
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001548 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001549 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1550 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1551 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001552 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001553 final long ident = Binder.clearCallingIdentity();
1554 try {
1555 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1556 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1557 } finally {
1558 Binder.restoreCallingIdentity(ident);
1559 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001560 }
1561
Mike Lockwood0f79b542009-08-14 14:18:49 -04001562 private void sendStickyBroadcast(Intent intent) {
1563 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001564 if (!mSystemReady) {
1565 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001566 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001567 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001568 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001569 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001570 }
1571
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001572 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001573 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001574 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001575 final NetworkInfo ni = intent.getParcelableExtra(
1576 ConnectivityManager.EXTRA_NETWORK_INFO);
1577 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1578 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1579 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001580 } else {
1581 BroadcastOptions opts = BroadcastOptions.makeBasic();
1582 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1583 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001584 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001585 final IBatteryStats bs = BatteryStatsService.getService();
1586 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001587 bs.noteConnectivityChanged(intent.getIntExtra(
1588 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1589 ni != null ? ni.getState().toString() : "?");
1590 } catch (RemoteException e) {
1591 }
1592 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001593 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001594 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001595 } finally {
1596 Binder.restoreCallingIdentity(ident);
1597 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001598 }
1599 }
1600
1601 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001602 loadGlobalProxy();
1603
Mike Lockwood0f79b542009-08-14 14:18:49 -04001604 synchronized(this) {
1605 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001606 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001607 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001608 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001609 }
1610 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001611 // load the global proxy at startup
1612 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001613
Robin Lee244ce8e2016-01-05 18:03:46 +00001614 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1615 // for user to unlock device too.
1616 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001617
Erik Klineda4bfa82015-04-30 12:58:40 +09001618 // Configure whether mobile data is always on.
1619 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1620
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001621 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001622
1623 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 }
1625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001627 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001628 *
1629 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001630 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001631 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001632 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1633 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001634
1635 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001636 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001637
Robert Greenwalt7b816022014-04-18 15:25:25 -07001638 if (networkAgent.networkCapabilities.hasTransport(
1639 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001640 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1641 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001642 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001643 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001644 } else if (networkAgent.networkCapabilities.hasTransport(
1645 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001646 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1647 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001648 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001649 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001650 } else {
1651 // do not track any other networks
1652 timeout = 0;
1653 }
1654
Robert Greenwalt7b816022014-04-18 15:25:25 -07001655 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001656 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001657 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001658 } catch (Exception e) {
1659 // You shall not crash!
1660 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001661 }
1662 }
1663 }
1664
1665 /**
1666 * Remove data activity tracking when network disconnects.
1667 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001668 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1669 final String iface = networkAgent.linkProperties.getInterfaceName();
1670 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001671
Robert Greenwalt7b816022014-04-18 15:25:25 -07001672 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1673 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001674 try {
1675 // the call fails silently if no idletimer setup for this interface
1676 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001677 } catch (Exception e) {
1678 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001679 }
1680 }
1681 }
1682
1683 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001684 * Reads the network specific MTU size from reources.
1685 * and set it on it's iface.
1686 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001687 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1688 final String iface = newLp.getInterfaceName();
1689 final int mtu = newLp.getMtu();
1690 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1691 if (VDBG) log("identical MTU - not setting");
1692 return;
1693 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001694
Robert Greenwalt43074032014-08-15 17:53:05 -07001695 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001696 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001697 return;
1698 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001699
w1997615afd812014-08-05 15:18:11 -07001700 // Cannot set MTU without interface name
1701 if (TextUtils.isEmpty(iface)) {
1702 loge("Setting MTU size with null iface.");
1703 return;
1704 }
1705
Robert Greenwalt7b816022014-04-18 15:25:25 -07001706 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001707 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001708 mNetd.setMtu(iface, mtu);
1709 } catch (Exception e) {
1710 Slog.e(TAG, "exception in setMtu()" + e);
1711 }
1712 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001713
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001714 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001715 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1716
1717 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001718 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001719 protected int getDefaultTcpRwnd() {
1720 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1721 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001722
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001723 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1724 if (isDefaultNetwork(nai) == false) {
1725 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001726 }
1727
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001728 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1729 String[] values = null;
1730 if (tcpBufferSizes != null) {
1731 values = tcpBufferSizes.split(",");
1732 }
1733
1734 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001735 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001736 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1737 values = tcpBufferSizes.split(",");
1738 }
1739
1740 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1741
1742 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001743 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001744
1745 final String prefix = "/sys/kernel/ipv4/tcp_";
1746 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1747 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1748 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1749 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1750 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1751 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1752 mCurrentTcpBufferSizes = tcpBufferSizes;
1753 } catch (IOException e) {
1754 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001755 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001756
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001757 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001758 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001759 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1760 if (rwndValue != 0) {
1761 SystemProperties.set(sysctlKey, rwndValue.toString());
1762 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001763 }
1764
Mattias Falk8b47b362011-08-23 14:15:13 +02001765 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001766 /*
1767 * Tell the VMs to toss their DNS caches
1768 */
1769 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1770 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001771 /*
1772 * Connectivity events can happen before boot has completed ...
1773 */
1774 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001775 final long ident = Binder.clearCallingIdentity();
1776 try {
1777 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1778 } finally {
1779 Binder.restoreCallingIdentity(ident);
1780 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001781 }
1782
Robert Greenwalt562cc542014-05-15 18:07:26 -07001783 @Override
1784 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001785 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1786 NETWORK_RESTORE_DELAY_PROP_NAME);
1787 if(restoreDefaultNetworkDelayStr != null &&
1788 restoreDefaultNetworkDelayStr.length() != 0) {
1789 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001790 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001791 } catch (NumberFormatException e) {
1792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001794 // if the system property isn't set, use the value for the apn type
1795 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1796
1797 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1798 (mNetConfigs[networkType] != null)) {
1799 ret = mNetConfigs[networkType].restoreTime;
1800 }
1801 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 }
1803
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001804 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001805 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001806 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001807 }
1808 return false;
1809 }
1810
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001811 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1812 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1813 final long DIAG_TIME_MS = 5000;
1814 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1815 // Start gathering diagnostic information.
1816 netDiags.add(new NetworkDiagnostics(
1817 nai.network,
1818 new LinkProperties(nai.linkProperties), // Must be a copy.
1819 DIAG_TIME_MS));
1820 }
1821
1822 for (NetworkDiagnostics netDiag : netDiags) {
1823 pw.println();
1824 netDiag.waitForMeasurements();
1825 netDiag.dump(pw);
1826 }
1827 }
1828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001830 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1831 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001832 if (mContext.checkCallingOrSelfPermission(
1833 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001835 pw.println("Permission Denial: can't dump ConnectivityService " +
1836 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1837 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 return;
1839 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001840
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001841 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001842 dumpNetworkDiagnostics(pw);
1843 return;
1844 }
Erik Kline379747a2015-06-05 17:47:34 +09001845
Lorenzo Colittie3805462015-06-03 11:18:24 +09001846 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001847 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001848 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001849 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001850 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001851 pw.println();
1852
Paul Jensen85cf78e2015-06-25 13:25:07 -04001853 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001854 pw.print("Active default network: ");
1855 if (defaultNai == null) {
1856 pw.println("none");
1857 } else {
1858 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001860 pw.println();
1861
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001862 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001863 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001864 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1865 pw.println(nai.toString());
1866 pw.increaseIndent();
1867 pw.println("Requests:");
1868 pw.increaseIndent();
1869 for (int i = 0; i < nai.networkRequests.size(); i++) {
1870 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001871 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001872 pw.decreaseIndent();
1873 pw.println("Lingered:");
1874 pw.increaseIndent();
1875 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1876 pw.decreaseIndent();
1877 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001878 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001879 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001880 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001881
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001882 pw.println("Metered Interfaces:");
1883 pw.increaseIndent();
1884 for (String value : mMeteredIfaces) {
1885 pw.println(value);
1886 }
1887 pw.decreaseIndent();
1888 pw.println();
1889
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001890 pw.print("Restrict background: ");
1891 pw.println(mRestrictBackground);
1892 pw.println();
1893
Felipe Lemed31a97f2016-05-06 14:53:50 -07001894 pw.print("Restrict power: ");
1895 pw.println(mRestrictPower);
1896 pw.println();
1897
Felipe Leme46c4fc32016-05-04 09:21:43 -07001898 pw.println("Status for known UIDs:");
1899 pw.increaseIndent();
1900 final int size = mUidRules.size();
1901 for (int i = 0; i < size; i++) {
1902 final int uid = mUidRules.keyAt(i);
1903 pw.print("UID=");
1904 pw.print(uid);
1905 final int uidRules = mUidRules.get(uid, RULE_NONE);
1906 pw.print(" rules=");
1907 pw.print(uidRulesToString(uidRules));
1908 pw.println();
1909 }
1910 pw.println();
1911 pw.decreaseIndent();
1912
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001913 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001914 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001915 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1916 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001917 }
1918 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001919 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001920
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001921 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001922
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001923 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001924 pw.print("mNetTransitionWakeLock: currently " +
1925 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1926 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1927 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1928 } else {
1929 pw.println(", last requested never");
1930 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001931 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001932
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001933 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001934 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001935
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001936 pw.println();
1937 mKeepaliveTracker.dump(pw);
1938
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001939 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001940
Lorenzo Colittie3805462015-06-03 11:18:24 +09001941 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001942 pw.println();
1943 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001944 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001945 for(int i = 0; i < mInetLog.size(); i++) {
1946 pw.println(mInetLog.get(i));
1947 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001948 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001949 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001950
1951 if (argsContain(args, "--short") == false) {
1952 pw.println();
1953 synchronized (mValidationLogs) {
1954 pw.println("mValidationLogs (most recent first):");
1955 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1956 pw.println(p.first);
1957 pw.increaseIndent();
1958 p.second.dump(fd, pw, args);
1959 pw.decreaseIndent();
1960 }
1961 }
Erik Kline7523eb32015-07-09 18:24:03 +09001962
1963 pw.println();
1964 pw.println("mNetworkRequestInfoLogs (most recent first):");
1965 pw.increaseIndent();
1966 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1967 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 }
1970
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001971 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001972 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001973 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001974 if (officialNai != null && officialNai.equals(nai)) return true;
1975 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001976 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001977 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001978 " - " + nai);
1979 }
1980 return false;
1981 }
1982
Paul Jensenc8b9a742014-09-30 15:37:41 -04001983 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001984 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001985 }
1986
Robert Greenwalt42acef32009-08-12 16:08:25 -07001987 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001988 private class NetworkStateTrackerHandler extends Handler {
1989 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001990 super(looper);
1991 }
1992
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001993 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001995 default:
1996 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001997 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001998 handleAsyncChannelHalfConnect(msg);
1999 break;
2000 }
2001 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2002 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2003 if (nai != null) nai.asyncChannel.disconnect();
2004 break;
2005 }
2006 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2007 handleAsyncChannelDisconnected(msg);
2008 break;
2009 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002010 }
2011 return true;
2012 }
2013
2014 private void maybeHandleNetworkAgentMessage(Message msg) {
2015 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2016 if (nai == null) {
2017 if (VDBG) {
2018 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2019 log(String.format("%s from unknown NetworkAgent", what));
2020 }
2021 return;
2022 }
2023
2024 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002025 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002026 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2027 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2028 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2029 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002030 }
Robin Lee585e2482016-05-01 23:00:00 +01002031 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002032 networkCapabilities)) {
2033 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2034 + nai.networkCapabilities + " -> " + networkCapabilities);
2035 }
2036 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002037 break;
2038 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002039 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002040 if (VDBG) {
2041 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002042 "; created=" + nai.created +
2043 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002044 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002045 LinkProperties oldLp = nai.linkProperties;
2046 synchronized (nai) {
2047 nai.linkProperties = (LinkProperties)msg.obj;
2048 }
Robin Lee585e2482016-05-01 23:00:00 +01002049 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002050 break;
2051 }
2052 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002053 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002054 updateNetworkInfo(nai, info);
2055 break;
2056 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002057 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002058 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002059 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002060 break;
2061 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002062 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002063 try {
2064 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002065 } catch (Exception e) {
2066 // Never crash!
2067 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002068 }
2069 break;
2070 }
2071 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002072 try {
2073 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002074 } catch (Exception e) {
2075 // Never crash!
2076 loge("Exception in removeVpnUidRanges: " + e);
2077 }
2078 break;
2079 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002080 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002081 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2082 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002083 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002084 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002085 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002086 break;
2087 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002088 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002089 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2090 break;
2091 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002092 }
2093 }
2094
2095 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2096 switch (msg.what) {
2097 default:
2098 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002099 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002100 final NetworkAgentInfo nai;
2101 synchronized (mNetworkForNetId) {
2102 nai = mNetworkForNetId.get(msg.arg2);
2103 }
2104 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002105 final boolean valid =
2106 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002107 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2108 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002109 if (valid != nai.lastValidated) {
2110 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002111 nai.lastValidated = valid;
2112 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002113 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002114 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2115 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002116 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002117 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002118 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002119 Bundle redirectUrlBundle = new Bundle();
2120 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002121 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002122 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002123 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002124 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002125 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002126 break;
2127 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002128 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002129 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002130 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002131 handleLingerComplete(nai);
2132 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 break;
2134 }
Paul Jensen869868be2014-05-15 10:33:05 -04002135 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002136 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002137 final boolean visible = (msg.arg1 != 0);
2138 final NetworkAgentInfo nai;
2139 synchronized (mNetworkForNetId) {
2140 nai = mNetworkForNetId.get(netId);
2141 }
2142 // If captive portal status has changed, update capabilities.
2143 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2144 nai.lastCaptivePortalDetected = visible;
2145 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002146 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002147 }
2148 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002149 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002150 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002151 if (nai == null) {
2152 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2153 break;
2154 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002155 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002156 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2157 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002158 }
Paul Jensen869868be2014-05-15 10:33:05 -04002159 break;
2160 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002161 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002162 return true;
2163 }
2164
2165 @Override
2166 public void handleMessage(Message msg) {
2167 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2168 maybeHandleNetworkAgentMessage(msg);
2169 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002170 }
2171 }
2172
Paul Jensen85cf78e2015-06-25 13:25:07 -04002173 private void linger(NetworkAgentInfo nai) {
2174 nai.lingering = true;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002175 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002176 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2177 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2178 }
2179
Paul Jensen0cc17322014-11-25 15:26:53 -05002180 // Cancel any lingering so the linger timeout doesn't teardown a network.
2181 // This should be called when a network begins satisfying a NetworkRequest.
2182 // Note: depending on what state the NetworkMonitor is in (e.g.,
2183 // if it's awaiting captive portal login, or if validation failed), this
2184 // may trigger a re-evaluation of the network.
2185 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002186 nai.networkLingered.clear();
2187 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002188 nai.lingering = false;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002189 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
Paul Jensen0cc17322014-11-25 15:26:53 -05002190 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002191 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2192 }
2193
Robert Greenwalt7b816022014-04-18 15:25:25 -07002194 private void handleAsyncChannelHalfConnect(Message msg) {
2195 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002196 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002197 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2198 if (VDBG) log("NetworkFactory connected");
2199 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002200 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002201 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002202 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002203 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002204 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002205 }
2206 } else {
2207 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002208 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002209 }
2210 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2211 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2212 if (VDBG) log("NetworkAgent connected");
2213 // A network agent has requested a connection. Establish the connection.
2214 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2215 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2216 } else {
2217 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002218 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002219 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002220 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002221 synchronized (mNetworkForNetId) {
2222 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002223 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002224 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002225 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002226 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002227 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002228 }
2229 }
2230 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002231
Robert Greenwalt7b816022014-04-18 15:25:25 -07002232 private void handleAsyncChannelDisconnected(Message msg) {
2233 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2234 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002235 if (DBG) {
2236 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2237 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002238 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002239 // TODO - if we move the logic to the network agent (have them disconnect
2240 // because they lost all their requests or because their score isn't good)
2241 // then they would disconnect organically, report their new state and then
2242 // disconnect the channel.
2243 if (nai.networkInfo.isConnected()) {
2244 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2245 null, null);
2246 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002247 final boolean wasDefault = isDefaultNetwork(nai);
2248 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002249 mDefaultInetConditionPublished = 0;
2250 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002251 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002252 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2253 // by other networks that are already connected. Perhaps that can be done by
2254 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2255 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002256 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002257 mKeepaliveTracker.handleStopAllKeepalives(nai,
2258 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002259 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002260 mNetworkAgentInfos.remove(msg.replyTo);
2261 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002262 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002263 // Remove the NetworkAgent, but don't mark the netId as
2264 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002265 mNetworkForNetId.remove(nai.network.netId);
2266 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002267 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002268 for (int i = 0; i < nai.networkRequests.size(); i++) {
2269 NetworkRequest request = nai.networkRequests.valueAt(i);
2270 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2271 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2272 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002273 sendUpdatedScoreToFactories(request, 0);
2274 }
2275 }
2276 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2277 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002278 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002279 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002280 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002281 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002282 rematchAllNetworksAndRequests(null, 0);
Pierre Imai04e222252016-04-12 18:02:58 +09002283 if (wasDefault && getDefaultNetwork() == null) {
2284 // Log that we lost the default network and there is no replacement.
Hugo Benichi5f16f762016-04-20 12:09:33 +09002285 logDefaultNetworkEvent(null, nai);
Pierre Imai04e222252016-04-12 18:02:58 +09002286 }
Paul Jensen62d30802015-06-17 14:42:30 -04002287 if (nai.created) {
2288 // Tell netd to clean up the configuration for this network
2289 // (routing rules, DNS, etc).
2290 // This may be slow as it requires a lot of netd shelling out to ip and
2291 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2292 // after we've rematched networks with requests which should make a potential
2293 // fallback network the default or requested a new network from the
2294 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2295 // long time.
2296 try {
2297 mNetd.removeNetwork(nai.network.netId);
2298 } catch (Exception e) {
2299 loge("Exception removing network: " + e);
2300 }
2301 }
2302 synchronized (mNetworkForNetId) {
2303 mNetIdInUse.delete(nai.network.netId);
2304 }
2305 } else {
2306 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2307 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002308 }
2309 }
2310
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002311 // If this method proves to be too slow then we can maintain a separate
2312 // pendingIntent => NetworkRequestInfo map.
2313 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2314 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2315 Intent intent = pendingIntent.getIntent();
2316 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2317 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2318 if (existingPendingIntent != null &&
2319 existingPendingIntent.getIntent().filterEquals(intent)) {
2320 return entry.getValue();
2321 }
2322 }
2323 return null;
2324 }
2325
2326 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2327 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2328
2329 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2330 if (existingRequest != null) { // remove the existing request.
2331 if (DBG) log("Replacing " + existingRequest.request + " with "
2332 + nri.request + " because their intents matched.");
2333 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2334 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002335 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002336 }
2337
Erik Klineda4bfa82015-04-30 12:58:40 +09002338 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002339 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002340 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002341 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002342 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002343 if (nri.request.networkCapabilities.hasSignalStrength() &&
2344 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2345 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002346 }
2347 }
2348 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002349 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002350 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002351 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002352 }
2353 }
2354
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002355 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2356 int callingUid) {
2357 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2358 if (nri != null) {
2359 handleReleaseNetworkRequest(nri.request, callingUid);
2360 }
2361 }
2362
Paul Jensen99364842014-12-09 11:43:45 -05002363 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002364 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2365 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002366 private boolean unneeded(NetworkAgentInfo nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002367 if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002368 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2369 // If this Network is already the highest scoring Network for a request, or if
2370 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002371 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002372 (nai.networkRequests.get(nri.request.requestId) != null ||
2373 // Note that this catches two important cases:
2374 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2375 // is currently satisfying the request. This is desirable when
2376 // cellular ends up validating but WiFi does not.
2377 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002378 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002379 // WiFi ends up validating and out scoring cellular.
2380 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2381 nai.getCurrentScoreAsValidated())) {
2382 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002383 }
2384 }
Paul Jensene0988542015-06-25 15:30:08 -04002385 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002386 }
2387
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002388 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2389 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002390 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002391 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002392 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2393 return;
2394 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002395 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002396 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002397 mNetworkRequests.remove(request);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002398 synchronized (mUidToNetworkRequestCount) {
2399 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2400 if (requests < 1) {
2401 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2402 nri.mUid);
2403 } else if (requests == 1) {
2404 mUidToNetworkRequestCount.removeAt(
2405 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2406 } else {
2407 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2408 }
2409 }
Erik Kline7523eb32015-07-09 18:24:03 +09002410 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002411 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002412 // Find all networks that are satisfying this request and remove the request
2413 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002414 // TODO - it's my understanding that for a request there is only a single
2415 // network satisfying it, so this loop is wasteful
2416 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002417 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2418 if (nai.networkRequests.get(nri.request.requestId) != null) {
2419 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002420 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002421 log(" Removing from current network " + nai.name() +
2422 ", leaving " + nai.networkRequests.size() +
2423 " requests.");
2424 }
Paul Jensen99364842014-12-09 11:43:45 -05002425 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002426 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002427 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002428 } else {
2429 // suspect there should only be one pass through here
2430 // but if any were kept do the check below
2431 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002432 }
2433 }
2434 }
2435
Robert Greenwalt51481852015-01-08 14:43:31 -08002436 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2437 if (nai != null) {
2438 mNetworkForRequestId.remove(nri.request.requestId);
2439 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002440 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002441 // that a network connected to serve it, even though the network was already
2442 // connected. Now that this request has gone away, we might have to pretend
2443 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002444 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002445 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2446 boolean doRemove = true;
2447 if (wasKept) {
2448 // check if any of the remaining requests for this network are for the
2449 // same legacy type - if so, don't remove the nai
2450 for (int i = 0; i < nai.networkRequests.size(); i++) {
2451 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2452 if (otherRequest.legacyType == nri.request.legacyType &&
2453 isRequest(otherRequest)) {
2454 if (DBG) log(" still have other legacy request - leaving");
2455 doRemove = false;
2456 }
2457 }
2458 }
2459
2460 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002461 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002462 }
2463 }
2464
Robert Greenwalta67be032014-05-16 15:49:14 -07002465 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002466 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2467 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002468 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002469 } else {
2470 // listens don't have a singular affectedNetwork. Check all networks to see
2471 // if this listen request applies and remove it.
2472 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2473 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002474 if (nri.request.networkCapabilities.hasSignalStrength() &&
2475 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2476 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002477 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002478 }
2479 }
2480 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2481 }
2482 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002483
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002484 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2485 enforceConnectivityInternalPermission();
2486 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2487 accept ? 1 : 0, always ? 1: 0, network));
2488 }
2489
2490 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2491 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2492 " accept=" + accept + " always=" + always);
2493
2494 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2495 if (nai == null) {
2496 // Nothing to do.
2497 return;
2498 }
2499
2500 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002501 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002502 return;
2503 }
2504
2505 if (!nai.networkMisc.explicitlySelected) {
2506 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2507 }
2508
2509 if (accept != nai.networkMisc.acceptUnvalidated) {
2510 int oldScore = nai.getCurrentScore();
2511 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002512 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002513 sendUpdatedScoreToFactories(nai);
2514 }
2515
2516 if (always) {
2517 nai.asyncChannel.sendMessage(
2518 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2519 }
2520
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002521 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002522 // Tell the NetworkAgent to not automatically reconnect to the network.
2523 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2524 // Teardown the nework.
2525 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002526 }
2527
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002528 }
2529
2530 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002531 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002532 mHandler.sendMessageDelayed(
2533 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2534 PROMPT_UNVALIDATED_DELAY_MS);
2535 }
2536
2537 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002538 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002539 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2540
2541 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2542 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002543 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002544 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002545 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2546 return;
2547 }
2548
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002549 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002550 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002551 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2552 intent.setClassName("com.android.settings",
2553 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002554
2555 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2556 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2557 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002558 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002559 }
2560
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002561 private class InternalHandler extends Handler {
2562 public InternalHandler(Looper looper) {
2563 super(looper);
2564 }
2565
2566 @Override
2567 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002568 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002569 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002570 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002571 String causedBy = null;
2572 synchronized (ConnectivityService.this) {
2573 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2574 mNetTransitionWakeLock.isHeld()) {
2575 mNetTransitionWakeLock.release();
2576 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002577 } else {
2578 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002579 }
2580 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002581 if (VDBG) {
2582 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2583 log("Failed to find a new network - expiring NetTransition Wakelock");
2584 } else {
2585 log("NetTransition Wakelock (" +
2586 (causedBy == null ? "unknown" : causedBy) +
2587 " cleared because we found a replacement network");
2588 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002589 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002590 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002591 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002592 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002593 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002594 break;
2595 }
Jason Monkdecd2952013-10-10 14:02:51 -04002596 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002597 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002598 break;
2599 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002600 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002601 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2602 break;
2603 }
2604 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2605 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002606 break;
2607 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002608 case EVENT_REGISTER_NETWORK_AGENT: {
2609 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2610 break;
2611 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002612 case EVENT_REGISTER_NETWORK_REQUEST:
2613 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002614 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002615 break;
2616 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002617 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2618 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002619 handleRegisterNetworkRequestWithIntent(msg);
2620 break;
2621 }
2622 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2623 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2624 break;
2625 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002626 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002627 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002628 break;
2629 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002630 case EVENT_SET_ACCEPT_UNVALIDATED: {
2631 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2632 break;
2633 }
2634 case EVENT_PROMPT_UNVALIDATED: {
2635 handlePromptUnvalidated((Network) msg.obj);
2636 break;
2637 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002638 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2639 handleMobileDataAlwaysOn();
2640 break;
2641 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002642 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2643 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2644 mKeepaliveTracker.handleStartKeepalive(msg);
2645 break;
2646 }
2647 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2648 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2649 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2650 int slot = msg.arg1;
2651 int reason = msg.arg2;
2652 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2653 break;
2654 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002655 case EVENT_SYSTEM_READY: {
2656 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2657 nai.networkMonitor.systemReady = true;
2658 }
2659 break;
2660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 }
2662 }
2663 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002664
2665 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002666 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002667 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002668 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002669 final int status = mTethering.tether(iface);
2670 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2671 try {
2672 mPolicyManager.onTetheringChanged(iface, true);
2673 } catch (RemoteException e) {
2674 }
2675 }
2676 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002677 } else {
2678 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2679 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002680 }
2681
2682 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002683 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002684 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002685
2686 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002687 final int status = mTethering.untether(iface);
2688 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2689 try {
2690 mPolicyManager.onTetheringChanged(iface, false);
2691 } catch (RemoteException e) {
2692 }
2693 }
2694 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002695 } else {
2696 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2697 }
2698 }
2699
2700 // javadoc from interface
2701 public int getLastTetherError(String iface) {
2702 enforceTetherAccessPermission();
2703
2704 if (isTetheringSupported()) {
2705 return mTethering.getLastTetherError(iface);
2706 } else {
2707 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2708 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002709 }
2710
2711 // TODO - proper iface API for selection by property, inspection, etc
2712 public String[] getTetherableUsbRegexs() {
2713 enforceTetherAccessPermission();
2714 if (isTetheringSupported()) {
2715 return mTethering.getTetherableUsbRegexs();
2716 } else {
2717 return new String[0];
2718 }
2719 }
2720
2721 public String[] getTetherableWifiRegexs() {
2722 enforceTetherAccessPermission();
2723 if (isTetheringSupported()) {
2724 return mTethering.getTetherableWifiRegexs();
2725 } else {
2726 return new String[0];
2727 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002728 }
2729
Danica Chang6fdd0c62010-08-11 14:54:43 -07002730 public String[] getTetherableBluetoothRegexs() {
2731 enforceTetherAccessPermission();
2732 if (isTetheringSupported()) {
2733 return mTethering.getTetherableBluetoothRegexs();
2734 } else {
2735 return new String[0];
2736 }
2737 }
2738
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002739 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002740 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002741 if (isTetheringSupported()) {
2742 return mTethering.setUsbTethering(enable);
2743 } else {
2744 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2745 }
2746 }
2747
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002748 // TODO - move iface listing, queries, etc to new module
2749 // javadoc from interface
2750 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002751 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002752 return mTethering.getTetherableIfaces();
2753 }
2754
2755 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002756 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002757 return mTethering.getTetheredIfaces();
2758 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002759
Robert Greenwalt5a735062010-03-02 17:25:02 -08002760 public String[] getTetheringErroredIfaces() {
2761 enforceTetherAccessPermission();
2762 return mTethering.getErroredIfaces();
2763 }
2764
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002765 public String[] getTetheredDhcpRanges() {
2766 enforceConnectivityInternalPermission();
2767 return mTethering.getTetheredDhcpRanges();
2768 }
2769
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002770 // if ro.tether.denied = true we default to no tethering
2771 // gservices could set the secure setting to 1 though to enable it on a build where it
2772 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002773 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002774 public boolean isTetheringSupported() {
2775 enforceTetherAccessPermission();
2776 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002777 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002778 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2779 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002780 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2781 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002782 mTethering.getTetherableWifiRegexs().length != 0 ||
2783 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2784 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002785 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002786
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002787 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002788 public void startTethering(int type, ResultReceiver receiver,
2789 boolean showProvisioningUi) {
2790 ConnectivityManager.enforceTetherChangePermission(mContext);
2791 if (!isTetheringSupported()) {
2792 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2793 return;
2794 }
2795 mTethering.startTethering(type, receiver, showProvisioningUi);
2796 }
2797
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002798 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002799 public void stopTethering(int type) {
2800 ConnectivityManager.enforceTetherChangePermission(mContext);
2801 mTethering.stopTethering(type);
2802 }
2803
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002804 // Called when we lose the default network and have no replacement yet.
2805 // This will automatically be cleared after X seconds or a new default network
2806 // becomes CONNECTED, whichever happens first. The timer is started by the
2807 // first caller and not restarted by subsequent callers.
2808 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002809 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002810 synchronized (this) {
2811 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002812 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002813 mNetTransitionWakeLock.acquire();
2814 mNetTransitionWakeLockCausedBy = forWhom;
2815 }
2816 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002817 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002818 mNetTransitionWakeLockTimeout);
2819 return;
2820 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002821
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002822 // 100 percent is full good, 0 is full bad.
2823 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002824 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002825 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002826 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002827 }
2828
Paul Jensenbfd17b72015-04-07 12:43:13 -04002829 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002830 enforceAccessPermission();
2831 enforceInternetPermission();
2832
Paul Jensenbfd17b72015-04-07 12:43:13 -04002833 NetworkAgentInfo nai;
2834 if (network == null) {
2835 nai = getDefaultNetwork();
2836 } else {
2837 nai = getNetworkAgentInfoForNetwork(network);
2838 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002839 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2840 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2841 return;
2842 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002843 // Revalidate if the app report does not match our current validated state.
2844 if (hasConnectivity == nai.lastValidated) return;
2845 final int uid = Binder.getCallingUid();
2846 if (DBG) {
2847 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2848 ") by " + uid);
2849 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002850 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002851 // Validating a network that has not yet connected could result in a call to
2852 // rematchNetworkAndRequests() which is not meant to work on such networks.
2853 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04002854
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002855 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002856
2857 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2858 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002859 }
2860
Paul Jensencee9b512015-05-06 07:32:40 -04002861 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002862 // this information is already available as a world read/writable jvm property
2863 // so this API change wouldn't have a benifit. It also breaks the passing
2864 // of proxy info to all the JVMs.
2865 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002866 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002867 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002868 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2869 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002870 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002871 }
2872
Paul Jensencee9b512015-05-06 07:32:40 -04002873 public ProxyInfo getProxyForNetwork(Network network) {
2874 if (network == null) return getDefaultProxy();
2875 final ProxyInfo globalProxy = getGlobalProxy();
2876 if (globalProxy != null) return globalProxy;
2877 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2878 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2879 // caller may not have.
2880 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2881 if (nai == null) return null;
2882 synchronized (nai) {
2883 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2884 if (proxyInfo == null) return null;
2885 return new ProxyInfo(proxyInfo);
2886 }
2887 }
2888
Paul Jensene0bef712014-12-10 15:12:18 -05002889 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2890 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2891 // proxy is null then there is no proxy in place).
2892 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2893 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2894 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2895 proxy = null;
2896 }
2897 return proxy;
2898 }
2899
2900 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2901 // better for determining if a new proxy broadcast is necessary:
2902 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2903 // avoid unnecessary broadcasts.
2904 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2905 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2906 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2907 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2908 // all set.
2909 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2910 a = canonicalizeProxyInfo(a);
2911 b = canonicalizeProxyInfo(b);
2912 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2913 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2914 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2915 }
2916
Jason Monk207900c2014-04-25 15:00:09 -04002917 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002918 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002919
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002920 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002921 if (proxyProperties == mGlobalProxy) return;
2922 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2923 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2924
2925 String host = "";
2926 int port = 0;
2927 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002928 String pacFileUrl = "";
2929 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002930 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002931 if (!proxyProperties.isValid()) {
2932 if (DBG)
2933 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2934 return;
2935 }
Jason Monk207900c2014-04-25 15:00:09 -04002936 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002937 host = mGlobalProxy.getHost();
2938 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002939 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002940 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002941 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002942 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002943 } else {
2944 mGlobalProxy = null;
2945 }
2946 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002947 final long token = Binder.clearCallingIdentity();
2948 try {
2949 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2950 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2951 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2952 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002953 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002954 } finally {
2955 Binder.restoreCallingIdentity(token);
2956 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002957
Jason Monkcf0f97a2014-10-02 15:39:38 -04002958 if (mGlobalProxy == null) {
2959 proxyProperties = mDefaultProxy;
2960 }
2961 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002962 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002963 }
2964
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002965 private void loadGlobalProxy() {
2966 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002967 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2968 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2969 String exclList = Settings.Global.getString(res,
2970 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002971 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2972 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002973 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002974 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002975 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002976 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002977 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002978 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002979 if (!proxyProperties.isValid()) {
2980 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2981 return;
2982 }
2983
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002984 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002985 mGlobalProxy = proxyProperties;
2986 }
2987 }
2988 }
2989
Jason Monk207900c2014-04-25 15:00:09 -04002990 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002991 // this information is already available as a world read/writable jvm property
2992 // so this API change wouldn't have a benifit. It also breaks the passing
2993 // of proxy info to all the JVMs.
2994 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002995 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002996 return mGlobalProxy;
2997 }
2998 }
2999
Jason Monk207900c2014-04-25 15:00:09 -04003000 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003001 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003002 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003003 proxy = null;
3004 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003005 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003006 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003007 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003008 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003009 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3010 return;
3011 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003012
3013 // This call could be coming from the PacManager, containing the port of the local
3014 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3015 // global (to get the correct local port), and send a broadcast.
3016 // TODO: Switch PacManager to have its own message to send back rather than
3017 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003018 if ((mGlobalProxy != null) && (proxy != null)
3019 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003020 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3021 mGlobalProxy = proxy;
3022 sendProxyBroadcast(mGlobalProxy);
3023 return;
3024 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003025 mDefaultProxy = proxy;
3026
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003027 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003028 if (!mDefaultProxyDisabled) {
3029 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003030 }
3031 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003032 }
3033
Paul Jensene0bef712014-12-10 15:12:18 -05003034 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3035 // This method gets called when any network changes proxy, but the broadcast only ever contains
3036 // the default proxy (even if it hasn't changed).
3037 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3038 // world where an app might be bound to a non-default network.
3039 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3040 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3041 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3042
3043 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3044 sendProxyBroadcast(getDefaultProxy());
3045 }
3046 }
3047
Robert Greenwalt434203a2010-10-11 16:00:27 -07003048 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003049 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3050 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003051 if (!TextUtils.isEmpty(proxy)) {
3052 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003053 if (data.length == 0) {
3054 return;
3055 }
3056
Robert Greenwalt434203a2010-10-11 16:00:27 -07003057 String proxyHost = data[0];
3058 int proxyPort = 8080;
3059 if (data.length > 1) {
3060 try {
3061 proxyPort = Integer.parseInt(data[1]);
3062 } catch (NumberFormatException e) {
3063 return;
3064 }
3065 }
Jason Monk207900c2014-04-25 15:00:09 -04003066 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003067 setGlobalProxy(p);
3068 }
3069 }
3070
Jason Monk207900c2014-04-25 15:00:09 -04003071 private void sendProxyBroadcast(ProxyInfo proxy) {
3072 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003073 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003074 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003075 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003076 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3077 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003078 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003079 final long ident = Binder.clearCallingIdentity();
3080 try {
3081 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3082 } finally {
3083 Binder.restoreCallingIdentity(ident);
3084 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003085 }
3086
3087 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003088 final private HashMap<Uri, Integer> mUriEventMap;
3089 final private Context mContext;
3090 final private Handler mHandler;
3091
3092 SettingsObserver(Context context, Handler handler) {
3093 super(null);
3094 mUriEventMap = new HashMap<Uri, Integer>();
3095 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003096 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003097 }
3098
Erik Klineda4bfa82015-04-30 12:58:40 +09003099 void observe(Uri uri, int what) {
3100 mUriEventMap.put(uri, what);
3101 final ContentResolver resolver = mContext.getContentResolver();
3102 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003103 }
3104
3105 @Override
3106 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003107 Slog.wtf(TAG, "Should never be reached.");
3108 }
3109
3110 @Override
3111 public void onChange(boolean selfChange, Uri uri) {
3112 final Integer what = mUriEventMap.get(uri);
3113 if (what != null) {
3114 mHandler.obtainMessage(what.intValue()).sendToTarget();
3115 } else {
3116 loge("No matching event to send for URI=" + uri);
3117 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003118 }
3119 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003120
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003121 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003122 Slog.d(TAG, s);
3123 }
3124
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003125 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003126 Slog.e(TAG, s);
3127 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003128
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003129 private static <T> T checkNotNull(T value, String message) {
3130 if (value == null) {
3131 throw new NullPointerException(message);
3132 }
3133 return value;
3134 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003135
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003136 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003137 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003138 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3139 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3140 *
3141 * @param oldPackage Package name of the application which currently controls VPN, which will
3142 * be replaced. If there is no such application, this should should either be
3143 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3144 * @param newPackage Package name of the application which should gain control of VPN, or
3145 * {@code null} to disable.
3146 * @param userId User for whom to prepare the new VPN.
3147 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003148 * @hide
3149 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003150 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003151 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3152 int userId) {
3153 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003154 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003155
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003156 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003157 Vpn vpn = mVpns.get(userId);
3158 if (vpn != null) {
3159 return vpn.prepare(oldPackage, newPackage);
3160 } else {
3161 return false;
3162 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003163 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003164 }
3165
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003166 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003167 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3168 * This method is used by system-privileged apps.
3169 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3170 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3171 *
3172 * @param packageName The package for which authorization state should change.
3173 * @param userId User for whom {@code packageName} is installed.
3174 * @param authorized {@code true} if this app should be able to start a VPN connection without
3175 * explicit user approval, {@code false} if not.
3176 *
Jeff Davidson05542602014-08-11 14:07:27 -07003177 * @hide
3178 */
3179 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003180 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3181 enforceCrossUserPermission(userId);
3182
Jeff Davidson05542602014-08-11 14:07:27 -07003183 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003184 Vpn vpn = mVpns.get(userId);
3185 if (vpn != null) {
3186 vpn.setPackageAuthorization(packageName, authorized);
3187 }
Jeff Davidson05542602014-08-11 14:07:27 -07003188 }
3189 }
3190
3191 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003192 * Configure a TUN interface and return its file descriptor. Parameters
3193 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003194 * and not available in ConnectivityManager. Permissions are checked in
3195 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003196 * @hide
3197 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003198 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003199 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003200 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003201 int user = UserHandle.getUserId(Binder.getCallingUid());
3202 synchronized(mVpns) {
3203 return mVpns.get(user).establish(config);
3204 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003205 }
3206
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003207 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003208 * Start legacy VPN, controlling native daemons as needed. Creates a
3209 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003210 */
3211 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003212 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003213 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003214 final LinkProperties egress = getActiveLinkProperties();
3215 if (egress == null) {
3216 throw new IllegalStateException("Missing active network connection");
3217 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003218 int user = UserHandle.getUserId(Binder.getCallingUid());
3219 synchronized(mVpns) {
3220 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3221 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003222 }
3223
3224 /**
3225 * Return the information of the ongoing legacy VPN. This method is used
3226 * by VpnSettings and not available in ConnectivityManager. Permissions
3227 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003228 */
3229 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003230 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3231 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003232 if (mLockdownEnabled) {
3233 return null;
3234 }
3235
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003236 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003237 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003238 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003239 }
3240
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003241 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003242 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3243 * and not available in ConnectivityManager.
3244 */
3245 @Override
3246 public VpnInfo[] getAllVpnInfo() {
3247 enforceConnectivityInternalPermission();
3248 if (mLockdownEnabled) {
3249 return new VpnInfo[0];
3250 }
3251
3252 synchronized(mVpns) {
3253 List<VpnInfo> infoList = new ArrayList<>();
3254 for (int i = 0; i < mVpns.size(); i++) {
3255 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3256 if (info != null) {
3257 infoList.add(info);
3258 }
3259 }
3260 return infoList.toArray(new VpnInfo[infoList.size()]);
3261 }
3262 }
3263
3264 /**
3265 * @return VPN information for accounting, or null if we can't retrieve all required
3266 * information, e.g primary underlying iface.
3267 */
3268 @Nullable
3269 private VpnInfo createVpnInfo(Vpn vpn) {
3270 VpnInfo info = vpn.getVpnInfo();
3271 if (info == null) {
3272 return null;
3273 }
3274 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3275 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3276 // the underlyingNetworks list.
3277 if (underlyingNetworks == null) {
3278 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3279 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3280 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3281 }
3282 } else if (underlyingNetworks.length > 0) {
3283 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3284 if (linkProperties != null) {
3285 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3286 }
3287 }
3288 return info.primaryUnderlyingIface == null ? null : info;
3289 }
3290
3291 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003292 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3293 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003294 * Permissions are checked in Vpn class.
3295 * @hide
3296 */
3297 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003298 public VpnConfig getVpnConfig(int userId) {
3299 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003300 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003301 Vpn vpn = mVpns.get(userId);
3302 if (vpn != null) {
3303 return vpn.getVpnConfig();
3304 } else {
3305 return null;
3306 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003307 }
3308 }
3309
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003310 @Override
3311 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003312 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3313 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3314 return false;
3315 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003316
3317 // Tear down existing lockdown if profile was removed
3318 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3319 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003320 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3321 final VpnProfile profile = VpnProfile.decode(
3322 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003323 if (profile == null) {
3324 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3325 setLockdownTracker(null);
3326 return true;
3327 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003328 int user = UserHandle.getUserId(Binder.getCallingUid());
3329 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003330 Vpn vpn = mVpns.get(user);
3331 if (vpn == null) {
3332 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3333 return false;
3334 }
3335 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003336 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003337 } else {
3338 setLockdownTracker(null);
3339 }
3340
3341 return true;
3342 }
3343
3344 /**
3345 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3346 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3347 */
3348 private void setLockdownTracker(LockdownVpnTracker tracker) {
3349 // Shutdown any existing tracker
3350 final LockdownVpnTracker existing = mLockdownTracker;
3351 mLockdownTracker = null;
3352 if (existing != null) {
3353 existing.shutdown();
3354 }
3355
3356 try {
3357 if (tracker != null) {
3358 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003359 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003360 mLockdownTracker = tracker;
3361 mLockdownTracker.init();
3362 } else {
3363 mNetd.setFirewallEnabled(false);
3364 }
3365 } catch (RemoteException e) {
3366 // ignored; NMS lives inside system_server
3367 }
3368 }
3369
3370 private void throwIfLockdownEnabled() {
3371 if (mLockdownEnabled) {
3372 throw new IllegalStateException("Unavailable in lockdown mode");
3373 }
3374 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003375
Robin Lee244ce8e2016-01-05 18:03:46 +00003376 /**
3377 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3378 *
3379 * @return {@code false} in case of errors; {@code true} otherwise.
3380 */
3381 private boolean updateAlwaysOnVpn(int user) {
3382 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3383 if (lockdownPackage == null) {
3384 return true;
3385 }
3386
3387 // Create an intent to start the VPN service declared in the app's manifest.
3388 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3389 serviceIntent.setPackage(lockdownPackage);
3390
3391 try {
3392 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3393 } catch (RuntimeException e) {
3394 return false;
3395 }
3396 }
3397
3398 @Override
Robin Leedc679712016-05-03 13:23:03 +01003399 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003400 enforceConnectivityInternalPermission();
3401 enforceCrossUserPermission(userId);
3402
3403 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3404 if (LockdownVpnTracker.isEnabled()) {
3405 return false;
3406 }
3407
3408 // If the current VPN package is the same as the new one, this is a no-op
3409 final String oldPackage = getAlwaysOnVpnPackage(userId);
3410 if (TextUtils.equals(oldPackage, packageName)) {
3411 return true;
3412 }
3413
3414 synchronized (mVpns) {
3415 Vpn vpn = mVpns.get(userId);
3416 if (vpn == null) {
3417 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3418 return false;
3419 }
3420 if (!vpn.setAlwaysOnPackage(packageName)) {
3421 return false;
3422 }
3423 if (!updateAlwaysOnVpn(userId)) {
3424 vpn.setAlwaysOnPackage(null);
3425 return false;
3426 }
3427 }
3428 return true;
3429 }
3430
3431 @Override
3432 public String getAlwaysOnVpnPackage(int userId) {
3433 enforceConnectivityInternalPermission();
3434 enforceCrossUserPermission(userId);
3435
3436 synchronized (mVpns) {
3437 Vpn vpn = mVpns.get(userId);
3438 if (vpn == null) {
3439 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3440 return null;
3441 }
3442 return vpn.getAlwaysOnPackage();
3443 }
3444 }
3445
Wink Savilleab9321d2013-06-29 21:10:57 -07003446 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003447 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003448 // TODO: Remove? Any reason to trigger a provisioning check?
3449 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003450 }
3451
3452 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003453 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003454
Paul Jensen89e0f092014-09-15 15:59:36 -04003455 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003456 Intent intent = new Intent(action);
3457 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003458 // Concatenate the range of types onto the range of NetIDs.
3459 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003460 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003461 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003462 }
3463
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003464 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003465 * Show or hide network provisioning notifications.
3466 *
3467 * We use notifications for two purposes: to notify that a network requires sign in
3468 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3469 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3470 * particular network we can display the notification type that was most recently requested.
3471 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3472 * might first display NO_INTERNET, and then when the captive portal check completes, display
3473 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003474 *
3475 * @param id an identifier that uniquely identifies this notification. This must match
3476 * between show and hide calls. We use the NetID value but for legacy callers
3477 * we concatenate the range of types with the range of NetIDs.
3478 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003479 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003480 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3481 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003482 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003483 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3484 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003485 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003486 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003487
3488 Resources r = Resources.getSystem();
3489 NotificationManager notificationManager = (NotificationManager) mContext
3490 .getSystemService(Context.NOTIFICATION_SERVICE);
3491
3492 if (visible) {
3493 CharSequence title;
3494 CharSequence details;
3495 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003496 if (notifyType == NotificationType.NO_INTERNET &&
3497 networkType == ConnectivityManager.TYPE_WIFI) {
3498 title = r.getString(R.string.wifi_no_internet, 0);
3499 details = r.getString(R.string.wifi_no_internet_detailed);
3500 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3501 } else if (notifyType == NotificationType.SIGN_IN) {
3502 switch (networkType) {
3503 case ConnectivityManager.TYPE_WIFI:
3504 title = r.getString(R.string.wifi_available_sign_in, 0);
3505 details = r.getString(R.string.network_available_sign_in_detailed,
3506 extraInfo);
3507 icon = R.drawable.stat_notify_wifi_in_range;
3508 break;
3509 case ConnectivityManager.TYPE_MOBILE:
3510 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3511 title = r.getString(R.string.network_available_sign_in, 0);
3512 // TODO: Change this to pull from NetworkInfo once a printable
3513 // name has been added to it
3514 details = mTelephonyManager.getNetworkOperatorName();
3515 icon = R.drawable.stat_notify_rssi_in_range;
3516 break;
3517 default:
3518 title = r.getString(R.string.network_available_sign_in, 0);
3519 details = r.getString(R.string.network_available_sign_in_detailed,
3520 extraInfo);
3521 icon = R.drawable.stat_notify_rssi_in_range;
3522 break;
3523 }
3524 } else {
3525 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3526 + getNetworkTypeName(networkType));
3527 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003528 }
3529
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003530 Notification notification = new Notification.Builder(mContext)
3531 .setWhen(0)
3532 .setSmallIcon(icon)
3533 .setAutoCancel(true)
3534 .setTicker(title)
3535 .setColor(mContext.getColor(
3536 com.android.internal.R.color.system_notification_accent_color))
3537 .setContentTitle(title)
3538 .setContentText(details)
3539 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003540 .setLocalOnly(true)
3541 .setPriority(highPriority ?
3542 Notification.PRIORITY_HIGH :
3543 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003544 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003545 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003546 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003547
Wink Saville948282b2013-08-29 08:55:16 -07003548 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003549 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003550 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003551 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003552 npe.printStackTrace();
3553 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003554 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003555 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003556 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003557 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003558 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003559 npe.printStackTrace();
3560 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003561 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003562 }
3563
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003564 /** Location to an updatable file listing carrier provisioning urls.
3565 * An example:
3566 *
3567 * <?xml version="1.0" encoding="utf-8"?>
3568 * <provisioningUrls>
3569 * <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 -07003570 * </provisioningUrls>
3571 */
3572 private static final String PROVISIONING_URL_PATH =
3573 "/data/misc/radio/provisioning_urls.xml";
3574 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003575
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003576 /** XML tag for root element. */
3577 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3578 /** XML tag for individual url */
3579 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003580 /** XML attribute for mcc */
3581 private static final String ATTR_MCC = "mcc";
3582 /** XML attribute for mnc */
3583 private static final String ATTR_MNC = "mnc";
3584
Paul Jensen434dde82015-06-11 09:43:30 -04003585 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003586 FileReader fileReader = null;
3587 XmlPullParser parser = null;
3588 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003589
3590 try {
3591 fileReader = new FileReader(mProvisioningUrlFile);
3592 parser = Xml.newPullParser();
3593 parser.setInput(fileReader);
3594 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3595
3596 while (true) {
3597 XmlUtils.nextElement(parser);
3598
3599 String element = parser.getName();
3600 if (element == null) break;
3601
Paul Jensen434dde82015-06-11 09:43:30 -04003602 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003603 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3604 try {
3605 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3606 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3607 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3608 parser.next();
3609 if (parser.getEventType() == XmlPullParser.TEXT) {
3610 return parser.getText();
3611 }
3612 }
3613 }
3614 } catch (NumberFormatException e) {
3615 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3616 }
3617 }
3618 }
3619 return null;
3620 } catch (FileNotFoundException e) {
3621 loge("Carrier Provisioning Urls file not found");
3622 } catch (XmlPullParserException e) {
3623 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3624 } catch (IOException e) {
3625 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3626 } finally {
3627 if (fileReader != null) {
3628 try {
3629 fileReader.close();
3630 } catch (IOException e) {}
3631 }
3632 }
3633 return null;
3634 }
3635
Wink Saville42d4f082013-07-20 20:31:59 -07003636 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003637 public String getMobileProvisioningUrl() {
3638 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003639 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003640 if (TextUtils.isEmpty(url)) {
3641 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003642 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003643 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003644 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003645 }
Wink Saville8cf35602013-07-10 23:00:07 -07003646 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003647 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003648 String phoneNumber = mTelephonyManager.getLine1Number();
3649 if (TextUtils.isEmpty(phoneNumber)) {
3650 phoneNumber = "0000000000";
3651 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003652 url = String.format(url,
3653 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3654 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003655 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003656 }
3657
Wink Savilleab9321d2013-06-29 21:10:57 -07003658 return url;
3659 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003660
Wink Saville948282b2013-08-29 08:55:16 -07003661 @Override
3662 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003663 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003664 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003665 final long ident = Binder.clearCallingIdentity();
3666 try {
3667 setProvNotificationVisible(visible, networkType, action);
3668 } finally {
3669 Binder.restoreCallingIdentity(ident);
3670 }
Wink Saville948282b2013-08-29 08:55:16 -07003671 }
Wink Saville7788c612013-08-29 14:57:08 -07003672
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003673 @Override
3674 public void setAirplaneMode(boolean enable) {
3675 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003676 final long ident = Binder.clearCallingIdentity();
3677 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003678 final ContentResolver cr = mContext.getContentResolver();
3679 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3680 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3681 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003682 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003683 } finally {
3684 Binder.restoreCallingIdentity(ident);
3685 }
3686 }
3687
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003688 private void onUserStart(int userId) {
3689 synchronized(mVpns) {
3690 Vpn userVpn = mVpns.get(userId);
3691 if (userVpn != null) {
3692 loge("Starting user already has a VPN");
3693 return;
3694 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003695 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003696 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003697 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003698 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3699 updateLockdownVpn();
3700 } else {
3701 updateAlwaysOnVpn(userId);
3702 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003703 }
3704
3705 private void onUserStop(int userId) {
3706 synchronized(mVpns) {
3707 Vpn userVpn = mVpns.get(userId);
3708 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003709 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003710 return;
3711 }
3712 mVpns.delete(userId);
3713 }
3714 }
3715
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003716 private void onUserAdded(int userId) {
3717 synchronized(mVpns) {
3718 final int vpnsSize = mVpns.size();
3719 for (int i = 0; i < vpnsSize; i++) {
3720 Vpn vpn = mVpns.valueAt(i);
3721 vpn.onUserAdded(userId);
3722 }
3723 }
3724 }
3725
3726 private void onUserRemoved(int userId) {
3727 synchronized(mVpns) {
3728 final int vpnsSize = mVpns.size();
3729 for (int i = 0; i < vpnsSize; i++) {
3730 Vpn vpn = mVpns.valueAt(i);
3731 vpn.onUserRemoved(userId);
3732 }
3733 }
3734 }
3735
Robin Lee89e7a692016-02-29 14:38:17 +00003736 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003737 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3738 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3739 updateLockdownVpn();
3740 } else {
3741 updateAlwaysOnVpn(userId);
3742 }
3743 }
3744
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003745 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3746 @Override
3747 public void onReceive(Context context, Intent intent) {
3748 final String action = intent.getAction();
3749 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3750 if (userId == UserHandle.USER_NULL) return;
3751
Robin Lee323f29d2016-05-04 16:38:06 +01003752 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003753 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003754 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003755 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003756 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3757 onUserAdded(userId);
3758 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3759 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003760 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3761 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003762 }
3763 }
3764 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003765
Robert Greenwalta67be032014-05-16 15:49:14 -07003766 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3767 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003768 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3769 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003770
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003771 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3772 // Map from UID to number of NetworkRequests that UID has filed.
3773 @GuardedBy("mUidToNetworkRequestCount")
3774 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3775
Robert Greenwalta67be032014-05-16 15:49:14 -07003776 private static class NetworkFactoryInfo {
3777 public final String name;
3778 public final Messenger messenger;
3779 public final AsyncChannel asyncChannel;
3780
3781 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3782 this.name = name;
3783 this.messenger = messenger;
3784 this.asyncChannel = asyncChannel;
3785 }
3786 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003787
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003788 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003789 * A NetworkRequest as registered by an application can be one of three
3790 * types:
3791 *
3792 * - "listen", for which the framework will issue callbacks about any
3793 * and all networks that match the specified NetworkCapabilities,
3794 *
3795 * - "request", capable of causing a specific network to be created
3796 * first (e.g. a telephony DUN request), the framework will issue
3797 * callbacks about the single, highest scoring current network
3798 * (if any) that matches the specified NetworkCapabilities, or
3799 *
3800 * - "track the default network", a hybrid of the two designed such
3801 * that the framework will issue callbacks for the single, highest
3802 * scoring current network (if any) that matches the capabilities of
3803 * the default Internet request (mDefaultRequest), but which cannot
3804 * cause the framework to either create or retain the existence of
3805 * any specific network.
3806 *
3807 */
3808 private static enum NetworkRequestType {
3809 LISTEN,
3810 TRACK_DEFAULT,
3811 REQUEST
3812 };
3813
3814 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003815 * Tracks info about the requester.
3816 * Also used to notice when the calling process dies so we can self-expire
3817 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003818 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003819 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003820 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003821 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003822 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003823 final int mPid;
3824 final int mUid;
3825 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003826 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003827
Erik Kline371c7b72016-03-22 17:04:20 +09003828 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003829 request = r;
3830 mPendingIntent = pi;
3831 messenger = null;
3832 mBinder = null;
3833 mPid = getCallingPid();
3834 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003835 mType = type;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003836 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003837 }
3838
Erik Kline371c7b72016-03-22 17:04:20 +09003839 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003840 super();
3841 messenger = m;
3842 request = r;
3843 mBinder = binder;
3844 mPid = getCallingPid();
3845 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003846 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003847 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003848 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003849
3850 try {
3851 mBinder.linkToDeath(this, 0);
3852 } catch (RemoteException e) {
3853 binderDied();
3854 }
3855 }
3856
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003857 private void enforceRequestCountLimit() {
3858 synchronized (mUidToNetworkRequestCount) {
3859 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3860 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3861 throw new IllegalArgumentException("Too many NetworkRequests filed");
3862 }
3863 mUidToNetworkRequestCount.put(mUid, networkRequests);
3864 }
3865 }
3866
Erik Kline371c7b72016-03-22 17:04:20 +09003867 private String typeString() {
3868 switch (mType) {
3869 case LISTEN: return "Listen";
3870 case REQUEST: return "Request";
3871 case TRACK_DEFAULT: return "Track default";
3872 default:
3873 return "unknown type";
3874 }
3875 }
3876
Robert Greenwalt9258c642014-03-26 16:47:06 -07003877 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003878 if (mBinder != null) {
3879 mBinder.unlinkToDeath(this, 0);
3880 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003881 }
3882
3883 public void binderDied() {
3884 log("ConnectivityService NetworkRequestInfo binderDied(" +
3885 request + ", " + mBinder + ")");
3886 releaseNetworkRequest(request);
3887 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003888
Erik Kline371c7b72016-03-22 17:04:20 +09003889 /**
3890 * Returns true iff. the contained NetworkRequest is one that:
3891 *
3892 * - should be associated with at most one satisfying network
3893 * at a time;
3894 *
3895 * - should cause a network to be kept up if it is the only network
3896 * which can satisfy the NetworkReqeust.
3897 *
3898 * For full detail of how isRequest() is used for pairing Networks with
3899 * NetworkRequests read rematchNetworkAndRequests().
3900 *
3901 * TODO: Rename to something more properly descriptive.
3902 */
3903 public boolean isRequest() {
3904 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3905 (mType == NetworkRequestType.REQUEST);
3906 }
3907
Robert Greenwalta67be032014-05-16 15:49:14 -07003908 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003909 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003910 " from uid/pid:" + mUid + "/" + mPid +
3911 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003912 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003913 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003914 }
3915
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003916 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3917 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3918 if (badCapability != null) {
3919 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003920 }
3921 }
3922
Erik Kline9d598e12015-07-13 16:37:51 +09003923 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003924 final SortedSet<Integer> thresholds = new TreeSet();
3925 synchronized (nai) {
3926 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3927 if (nri.request.networkCapabilities.hasSignalStrength() &&
3928 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3929 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3930 }
3931 }
3932 }
Erik Kline9d598e12015-07-13 16:37:51 +09003933 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003934 }
3935
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003936 private void updateSignalStrengthThresholds(
3937 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3938 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003939 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003940 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3941
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003942 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003943 String detail;
3944 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3945 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3946 } else {
3947 detail = reason;
3948 }
3949 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3950 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3951 }
3952
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003953 nai.asyncChannel.sendMessage(
3954 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003955 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003956 }
3957
Robert Greenwalt9258c642014-03-26 16:47:06 -07003958 @Override
3959 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003960 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003961 final NetworkRequestType type = (networkCapabilities == null)
3962 ? NetworkRequestType.TRACK_DEFAULT
3963 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003964 // If the requested networkCapabilities is null, take them instead from
3965 // the default network request. This allows callers to keep track of
3966 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09003967 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003968 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3969 enforceAccessPermission();
3970 } else {
3971 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3972 enforceNetworkRequestPermissions(networkCapabilities);
3973 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003974 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003975 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003976
Robert Greenwalt6078b502014-06-11 16:05:07 -07003977 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003978 throw new IllegalArgumentException("Bad timeout specified");
3979 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003980
Etan Cohenddb9ef02015-11-18 10:56:15 -08003981 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3982 .equals(networkCapabilities.getNetworkSpecifier())) {
3983 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3984 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3985 }
3986
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003987 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3988 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09003989 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09003990 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003991
3992 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003993 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003994 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003995 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003996 }
3997 return networkRequest;
3998 }
3999
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004000 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004001 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004002 enforceConnectivityInternalPermission();
4003 } else {
4004 enforceChangePermission();
4005 }
4006 }
4007
fenglub15e72b2015-03-20 11:29:56 -07004008 @Override
fengludb571472015-04-21 17:12:05 -07004009 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004010 enforceAccessPermission();
4011 NetworkAgentInfo nai = null;
4012 if (network == null) {
4013 return false;
4014 }
4015 synchronized (mNetworkForNetId) {
4016 nai = mNetworkForNetId.get(network.netId);
4017 }
4018 if (nai != null) {
4019 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4020 return true;
4021 }
4022 return false;
4023 }
4024
4025
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004026 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
4027 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004028 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004029 final int uidRules;
4030 final int uid = Binder.getCallingUid();
4031 synchronized(mRulesLock) {
4032 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4033 }
Felipe Lemed31a97f2016-05-06 14:53:50 -07004034 if ((uidRules & RULE_ALLOW_ALL) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004035 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004036 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004037 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004038 }
4039 }
4040 }
4041
Robert Greenwalt9258c642014-03-26 16:47:06 -07004042 @Override
4043 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4044 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004045 checkNotNull(operation, "PendingIntent cannot be null.");
4046 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4047 enforceNetworkRequestPermissions(networkCapabilities);
4048 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004049 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004050
4051 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
4052 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004053 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004054 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09004055 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004056 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4057 nri));
4058 return networkRequest;
4059 }
4060
Jeremy Joslin79294842014-12-03 17:15:28 -08004061 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4062 mHandler.sendMessageDelayed(
4063 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4064 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4065 }
4066
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004067 @Override
4068 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004069 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004070 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4071 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004072 }
4073
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004074 // In order to implement the compatibility measure for pre-M apps that call
4075 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4076 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4077 // This ensures it has permission to do so.
4078 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4079 if (nc == null) {
4080 return false;
4081 }
4082 int[] transportTypes = nc.getTransportTypes();
4083 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4084 return false;
4085 }
4086 try {
4087 mContext.enforceCallingOrSelfPermission(
4088 android.Manifest.permission.ACCESS_WIFI_STATE,
4089 "ConnectivityService");
4090 } catch (SecurityException e) {
4091 return false;
4092 }
4093 return true;
4094 }
4095
Robert Greenwalt9258c642014-03-26 16:47:06 -07004096 @Override
4097 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4098 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004099 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4100 enforceAccessPermission();
4101 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004102
Erik Kline7523eb32015-07-09 18:24:03 +09004103 NetworkRequest networkRequest = new NetworkRequest(
4104 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004105 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09004106 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004107 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004108
4109 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4110 return networkRequest;
4111 }
4112
4113 @Override
4114 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4115 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004116 checkNotNull(operation, "PendingIntent cannot be null.");
4117 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4118 enforceAccessPermission();
4119 }
4120
Erik Kline7523eb32015-07-09 18:24:03 +09004121 NetworkRequest networkRequest = new NetworkRequest(
4122 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004123 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004124 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004125 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004126
4127 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004128 }
4129
4130 @Override
4131 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004132 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4133 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004134 }
4135
4136 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004137 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004138 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004139 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4140 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004141 }
4142
Robert Greenwalta67be032014-05-16 15:49:14 -07004143 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004144 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004145 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4146 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4147 }
4148
4149 @Override
4150 public void unregisterNetworkFactory(Messenger messenger) {
4151 enforceConnectivityInternalPermission();
4152 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4153 }
4154
4155 private void handleUnregisterNetworkFactory(Messenger messenger) {
4156 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4157 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004158 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004159 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004160 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004161 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004162 }
4163
Robert Greenwalt7b816022014-04-18 15:25:25 -07004164 /**
4165 * NetworkAgentInfo supporting a request by requestId.
4166 * These have already been vetted (their Capabilities satisfy the request)
4167 * and the are the highest scored network available.
4168 * the are keyed off the Requests requestId.
4169 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004170 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004171 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4172 new SparseArray<NetworkAgentInfo>();
4173
Paul Jensen31a94f42015-02-13 14:18:39 -05004174 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4175 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004176 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4177 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004178 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4179 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4180 // there may not be a strict 1:1 correlation between the two.
4181 @GuardedBy("mNetworkForNetId")
4182 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004183
Robert Greenwalt7b816022014-04-18 15:25:25 -07004184 // NetworkAgentInfo keyed off its connecting messenger
4185 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004186 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004187 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4188 new HashMap<Messenger, NetworkAgentInfo>();
4189
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004190 @GuardedBy("mBlockedAppUids")
4191 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4192
Paul Jensen2c311d62014-11-17 12:34:51 -05004193 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004194 private final NetworkRequest mDefaultRequest;
4195
Erik Klineda4bfa82015-04-30 12:58:40 +09004196 // Request used to optionally keep mobile data active even when higher
4197 // priority networks like Wi-Fi are active.
4198 private final NetworkRequest mDefaultMobileDataRequest;
4199
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004200 private NetworkAgentInfo getDefaultNetwork() {
4201 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4202 }
4203
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004204 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004205 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004206 }
4207
Paul Jensen31a94f42015-02-13 14:18:39 -05004208 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004209 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004210 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004211 enforceConnectivityInternalPermission();
4212
Paul Jensen2c311d62014-11-17 12:34:51 -05004213 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4214 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004215 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004216 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4217 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004218 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004219 synchronized (this) {
4220 nai.networkMonitor.systemReady = mSystemReady;
4221 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004222 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004223 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004224 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004225 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004226 }
4227
4228 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4229 if (VDBG) log("Got NetworkAgent Messenger");
4230 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004231 synchronized (mNetworkForNetId) {
4232 mNetworkForNetId.put(na.network.netId, na);
4233 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004234 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4235 NetworkInfo networkInfo = na.networkInfo;
4236 na.networkInfo = null;
4237 updateNetworkInfo(na, networkInfo);
4238 }
4239
4240 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4241 LinkProperties newLp = networkAgent.linkProperties;
4242 int netId = networkAgent.network.netId;
4243
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004244 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4245 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004246 if (networkAgent.clatd != null) {
4247 networkAgent.clatd.fixupLinkProperties(oldLp);
4248 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004249
Paul Jensen992f2522014-04-28 10:33:11 -04004250 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004251 updateMtu(newLp, oldLp);
4252 // TODO - figure out what to do for clat
4253// for (LinkProperties lp : newLp.getStackedLinks()) {
4254// updateMtu(lp, null);
4255// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004256 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004257
Erik Kline94887872016-04-05 13:30:49 +09004258 updateRoutes(newLp, oldLp, netId);
4259 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004260
Paul Jensen3b759822014-05-13 11:44:01 -04004261 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004262 if (isDefaultNetwork(networkAgent)) {
4263 handleApplyDefaultProxy(newLp.getHttpProxy());
4264 } else {
4265 updateProxy(newLp, oldLp, networkAgent);
4266 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004267 // TODO - move this check to cover the whole function
4268 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004269 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004270 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4271 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004272
4273 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004274 }
4275
Lorenzo Colitti95439462014-10-09 13:44:48 +09004276 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4277 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4278 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004279
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004280 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004281 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4282 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004283 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004284 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004285 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004286 }
Paul Jensen992f2522014-04-28 10:33:11 -04004287
4288 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4289 CompareResult<String> interfaceDiff = new CompareResult<String>();
4290 if (oldLp != null) {
4291 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4292 } else if (newLp != null) {
4293 interfaceDiff.added = newLp.getAllInterfaceNames();
4294 }
4295 for (String iface : interfaceDiff.added) {
4296 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004297 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004298 mNetd.addInterfaceToNetwork(iface, netId);
4299 } catch (Exception e) {
4300 loge("Exception adding interface: " + e);
4301 }
4302 }
4303 for (String iface : interfaceDiff.removed) {
4304 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004305 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004306 mNetd.removeInterfaceFromNetwork(iface, netId);
4307 } catch (Exception e) {
4308 loge("Exception removing interface: " + e);
4309 }
4310 }
4311 }
4312
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004313 /**
4314 * Have netd update routes from oldLp to newLp.
4315 * @return true if routes changed between oldLp and newLp
4316 */
4317 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004318 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4319 if (oldLp != null) {
4320 routeDiff = oldLp.compareAllRoutes(newLp);
4321 } else if (newLp != null) {
4322 routeDiff.added = newLp.getAllRoutes();
4323 }
4324
4325 // add routes before removing old in case it helps with continuous connectivity
4326
4327 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4328 for (RouteInfo route : routeDiff.added) {
4329 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004330 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004331 try {
4332 mNetd.addRoute(netId, route);
4333 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004334 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4335 loge("Exception in addRoute for non-gateway: " + e);
4336 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004337 }
4338 }
4339 for (RouteInfo route : routeDiff.added) {
4340 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004341 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004342 try {
4343 mNetd.addRoute(netId, route);
4344 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004345 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4346 loge("Exception in addRoute for gateway: " + e);
4347 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004348 }
4349 }
4350
4351 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004352 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004353 try {
4354 mNetd.removeRoute(netId, route);
4355 } catch (Exception e) {
4356 loge("Exception in removeRoute: " + e);
4357 }
4358 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004359 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004360 }
Erik Kline41368502015-06-17 13:19:54 +09004361
Erik Kline94887872016-04-05 13:30:49 +09004362 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4363 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4364 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004365 }
Erik Kline94887872016-04-05 13:30:49 +09004366
4367 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004368 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004369 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004370 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004371 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4372 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004373 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004374 }
4375 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4376 if (defaultNai != null && defaultNai.network.netId == netId) {
4377 setDefaultDnsSystemProperties(dnses);
4378 }
4379 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004380 }
4381
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004382 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4383 int last = 0;
4384 for (InetAddress dns : dnses) {
4385 ++last;
4386 String key = "net.dns" + last;
4387 String value = dns.getHostAddress();
4388 SystemProperties.set(key, value);
4389 }
4390 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4391 String key = "net.dns" + i;
4392 SystemProperties.set(key, "");
4393 }
4394 mNumDnsEntries = last;
4395 }
4396
Paul Jensen3d194ea2015-06-16 14:27:36 -04004397 /**
4398 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4399 * augmented with any stateful capabilities implied from {@code networkAgent}
4400 * (e.g., validated status and captive portal status).
4401 *
Paul Jensene0988542015-06-25 15:30:08 -04004402 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004403 * @param networkCapabilities the new network capabilities.
4404 */
Paul Jensene0988542015-06-25 15:30:08 -04004405 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004406 // Don't modify caller's NetworkCapabilities.
4407 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004408 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004409 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4410 } else {
4411 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4412 }
Paul Jensene0988542015-06-25 15:30:08 -04004413 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004414 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4415 } else {
4416 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4417 }
Paul Jensene0988542015-06-25 15:30:08 -04004418 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4419 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004420 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4421 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4422 try {
4423 mNetd.setNetworkPermission(nai.network.netId,
4424 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4425 null : NetworkManagementService.PERMISSION_SYSTEM);
4426 } catch (RemoteException e) {
4427 loge("Exception in setNetworkPermission: " + e);
4428 }
4429 }
Paul Jensene0988542015-06-25 15:30:08 -04004430 synchronized (nai) {
4431 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004432 }
Paul Jensene0988542015-06-25 15:30:08 -04004433 rematchAllNetworksAndRequests(nai, oldScore);
4434 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004435 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004436 }
4437
Paul Jensenc8b9a742014-09-30 15:37:41 -04004438 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4439 for (int i = 0; i < nai.networkRequests.size(); i++) {
4440 NetworkRequest nr = nai.networkRequests.valueAt(i);
4441 // Don't send listening requests to factories. b/17393458
4442 if (!isRequest(nr)) continue;
4443 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4444 }
4445 }
4446
Robert Greenwalt7b816022014-04-18 15:25:25 -07004447 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4448 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004449 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004450 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4451 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004452 }
4453 }
4454
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004455 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4456 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004457 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004458 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004459 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4460 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004461 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004462 sendIntent(nri.mPendingIntent, intent);
4463 }
4464 // else not handled
4465 }
4466
4467 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4468 mPendingIntentWakeLock.acquire();
4469 try {
4470 if (DBG) log("Sending " + pendingIntent);
4471 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4472 } catch (PendingIntent.CanceledException e) {
4473 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4474 mPendingIntentWakeLock.release();
4475 releasePendingNetworkRequest(pendingIntent);
4476 }
4477 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4478 }
4479
4480 @Override
4481 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4482 String resultData, Bundle resultExtras) {
4483 if (DBG) log("Finished sending " + pendingIntent);
4484 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004485 // Release with a delay so the receiving client has an opportunity to put in its
4486 // own request.
4487 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004488 }
4489
Robert Greenwalt9258c642014-03-26 16:47:06 -07004490 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004491 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004492 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004493 Bundle bundle = new Bundle();
4494 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4495 new NetworkRequest(nri.request));
4496 Message msg = Message.obtain();
4497 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4498 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4499 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4500 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004501 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004502 case ConnectivityManager.CALLBACK_LOSING: {
4503 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4504 break;
4505 }
4506 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4507 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4508 new NetworkCapabilities(networkAgent.networkCapabilities));
4509 break;
4510 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004511 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004512 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4513 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004514 break;
4515 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004516 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004517 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004518 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004519 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004520 if (VDBG) {
4521 log("sending notification " + notifyTypeToName(notificationType) +
4522 " for " + nri.request);
4523 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004524 nri.messenger.send(msg);
4525 } catch (RemoteException e) {
4526 // may occur naturally in the race of binder death.
4527 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4528 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004529 }
4530
Paul Jensenc8b9a742014-09-30 15:37:41 -04004531 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4532 for (int i = 0; i < nai.networkRequests.size(); i++) {
4533 NetworkRequest nr = nai.networkRequests.valueAt(i);
4534 // Ignore listening requests.
4535 if (!isRequest(nr)) continue;
4536 loge("Dead network still had at least " + nr);
4537 break;
4538 }
4539 nai.asyncChannel.disconnect();
4540 }
4541
Robert Greenwalt7b816022014-04-18 15:25:25 -07004542 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4543 if (oldNetwork == null) {
4544 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4545 return;
4546 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004547 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4548 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004549 }
4550
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004551 private void makeDefault(NetworkAgentInfo newNetwork, NetworkAgentInfo prevNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004552 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004553 setupDataActivityTracking(newNetwork);
4554 try {
4555 mNetd.setDefaultNetId(newNetwork.network.netId);
4556 } catch (Exception e) {
4557 loge("Exception setting default network :" + e);
4558 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004559 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004560 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004561 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004562 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Hugo Benichi5f16f762016-04-20 12:09:33 +09004563 logDefaultNetworkEvent(newNetwork, prevNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004564 }
4565
Paul Jensen2161a8e2014-09-11 11:00:39 -04004566 // Handles a network appearing or improving its score.
4567 //
4568 // - Evaluates all current NetworkRequests that can be
4569 // satisfied by newNetwork, and reassigns to newNetwork
4570 // any such requests for which newNetwork is the best.
4571 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004572 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004573 // needed. A network is needed if it is the best network for
4574 // one or more NetworkRequests, or if it is a VPN.
4575 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004576 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004577 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004578 //
4579 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4580 // networks that have no chance (i.e. even if validated)
4581 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004582 //
4583 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4584 // it does not remove NetworkRequests that other Networks could better satisfy.
4585 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4586 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4587 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004588 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004589 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004590 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4591 // performed to tear down unvalidated networks that have no chance (i.e. even if
4592 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004593 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004594 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Robin Lee585e2482016-05-01 23:00:00 +01004595 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004596 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004597 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004598 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004599 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004600 // Find and migrate to this Network any NetworkRequests for
4601 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004602 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004603 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004604 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004605 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004606 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4607 final boolean satisfies = newNetwork.satisfies(nri.request);
4608 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004609 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004610 log("Network " + newNetwork.name() + " was already satisfying" +
4611 " request " + nri.request.requestId + ". No change.");
4612 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004613 keep = true;
4614 continue;
4615 }
4616
4617 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004618 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004619 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004620 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004621 // This is not a request, it's a callback listener.
4622 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004623 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004624 continue;
4625 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004626
Robert Greenwalt7b816022014-04-18 15:25:25 -07004627 // next check if it's better than any current network we're using for
4628 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004629 if (VDBG) {
4630 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004631 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4632 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004633 }
4634 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004635 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004636 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004637 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004638 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004639 currentNetwork.networkRequests.remove(nri.request.requestId);
4640 currentNetwork.networkLingered.add(nri.request);
4641 affectedNetworks.add(currentNetwork);
4642 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004643 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004644 }
Paul Jensen573a0352015-01-08 10:49:34 -05004645 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004646 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004647 if (!newNetwork.addRequest(nri.request)) {
4648 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4649 }
4650 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004651 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004652 // Tell NetworkFactories about the new score, so they can stop
4653 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004654 // TODO - this could get expensive if we have alot of requests for this
4655 // network. Think about if there is a way to reduce this. Push
4656 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004657 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004658 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004659 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004660 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004661 }
4662 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004663 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4664 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4665 // mark it as no longer satisfying "nri". Because networks are processed by
4666 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4667 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4668 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4669 // This means this code doesn't have to handle the case where "currentNetwork" no
4670 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4671 if (DBG) {
4672 log("Network " + newNetwork.name() + " stopped satisfying" +
4673 " request " + nri.request.requestId);
4674 }
4675 newNetwork.networkRequests.remove(nri.request.requestId);
4676 if (currentNetwork == newNetwork) {
4677 mNetworkForRequestId.remove(nri.request.requestId);
4678 sendUpdatedScoreToFactories(nri.request, 0);
4679 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004680 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004681 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4682 newNetwork.name() +
4683 " without updating mNetworkForRequestId or factories!");
4684 }
4685 }
4686 // TODO: technically, sending CALLBACK_LOST here is
4687 // incorrect if nri is a request (not a listen) and there
4688 // is a replacement network currently connected that can
4689 // satisfy it. However, the only capability that can both
4690 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4691 // so this code is only incorrect for a network that loses
4692 // the TRUSTED capability, which is a rare case.
4693 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004694 }
4695 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004696 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004697 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004698 if (nai.lingering) {
4699 // Already lingered. Nothing to do. This can only happen if "nai" is in
4700 // "affectedNetworks" twice. The reasoning being that to get added to
4701 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4702 // (i.e. not lingered) so it could have only been lingered by this loop.
4703 // unneeded(nai) will be false and we'll call unlinger() below which would
4704 // be bad, so handle it here.
4705 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004706 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004707 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004708 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004709 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004710 }
4711 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004712 if (isNewDefault) {
4713 // Notify system services that this network is up.
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004714 makeDefault(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004715 synchronized (ConnectivityService.this) {
4716 // have a new default network, release the transition wakelock in
4717 // a second if it's held. The second pause is to allow apps
4718 // to reconnect over the new network
4719 if (mNetTransitionWakeLock.isHeld()) {
4720 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4721 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4722 mNetTransitionWakeLockSerialNumber, 0),
4723 1000);
4724 }
4725 }
4726 }
4727
4728 // do this after the default net is switched, but
4729 // before LegacyTypeTracker sends legacy broadcasts
4730 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4731
4732 if (isNewDefault) {
4733 // Maintain the illusion: since the legacy API only
4734 // understands one network at a time, we must pretend
4735 // that the current default network disconnected before
4736 // the new one connected.
4737 if (oldDefaultNetwork != null) {
4738 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4739 oldDefaultNetwork, true);
4740 }
4741 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4742 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4743 notifyLockdownVpn(newNetwork);
4744 }
4745
Robert Greenwalt7b816022014-04-18 15:25:25 -07004746 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004747 // Notify battery stats service about this network, both the normal
4748 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004749 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004750 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004751 final IBatteryStats bs = BatteryStatsService.getService();
4752 final int type = newNetwork.networkInfo.getType();
4753
4754 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4755 bs.noteNetworkInterfaceType(baseIface, type);
4756 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4757 final String stackedIface = stacked.getInterfaceName();
4758 bs.noteNetworkInterfaceType(stackedIface, type);
4759 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4760 }
4761 } catch (RemoteException ignored) {
4762 }
4763
Robert Greenwalt152ed372014-12-17 17:19:53 -08004764 // This has to happen after the notifyNetworkCallbacks as that tickles each
4765 // ConnectivityManager instance so that legacy requests correctly bind dns
4766 // requests to this network. The legacy users are listening for this bcast
4767 // and will generally do a dns request so they can ensureRouteToHost and if
4768 // they do that before the callbacks happen they'll use the default network.
4769 //
4770 // TODO: Is there still a race here? We send the broadcast
4771 // after sending the callback, but if the app can receive the
4772 // broadcast before the callback, it might still break.
4773 //
4774 // This *does* introduce a race where if the user uses the new api
4775 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4776 // they may get old info. Reverse this after the old startUsing api is removed.
4777 // This is on top of the multiple intent sequencing referenced in the todo above.
4778 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4779 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4780 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4781 // legacy type tracker filters out repeat adds
4782 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4783 }
4784 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004785
4786 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4787 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4788 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4789 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4790 if (newNetwork.isVPN()) {
4791 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4792 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004793 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004794 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4795 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004796 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004797 if (DBG) log("Reaping " + nai.name());
4798 teardownUnneededNetwork(nai);
4799 }
4800 }
4801 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004802 }
4803
Paul Jensen1c7ba022015-06-16 14:27:36 -04004804 /**
4805 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4806 * being disconnected.
4807 * @param changed If only one Network's score or capabilities have been modified since the last
4808 * time this function was called, pass this Network in this argument, otherwise pass
4809 * null.
4810 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4811 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4812 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4813 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4814 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004815 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004816 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004817 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4818 // to avoid the slowness. It is not simply enough to process just "changed", for
4819 // example in the case where "changed"'s score decreases and another network should begin
4820 // satifying a NetworkRequest that "changed" currently satisfies.
4821
4822 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4823 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4824 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004825 if (changed != null && oldScore < changed.getCurrentScore()) {
4826 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004827 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004828 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4829 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4830 // Rematch higher scoring networks first to prevent requests first matching a lower
4831 // scoring network and then a higher scoring network, which could produce multiple
4832 // callbacks and inadvertently unlinger networks.
4833 Arrays.sort(nais);
4834 for (NetworkAgentInfo nai : nais) {
4835 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004836 // Only reap the last time through the loop. Reaping before all rematching
4837 // is complete could incorrectly teardown a network that hasn't yet been
4838 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004839 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004840 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004841 }
4842 }
4843 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004844
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004845 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004846 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004847 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004848 // For now only update icons for default connection.
4849 // TODO: Update WiFi and cellular icons separately. b/17237507
4850 if (!isDefaultNetwork(nai)) return;
4851
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004852 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004853 // Don't repeat publish.
4854 if (newInetCondition == mDefaultInetConditionPublished) return;
4855
4856 mDefaultInetConditionPublished = newInetCondition;
4857 sendInetConditionBroadcast(nai.networkInfo);
4858 }
4859
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004860 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4861 if (mLockdownTracker != null) {
4862 if (nai != null && nai.isVPN()) {
4863 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4864 } else {
4865 mLockdownTracker.onNetworkInfoChanged();
4866 }
4867 }
4868 }
4869
Robert Greenwalt7b816022014-04-18 15:25:25 -07004870 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4871 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004872 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004873 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004874 synchronized (networkAgent) {
4875 oldInfo = networkAgent.networkInfo;
4876 networkAgent.networkInfo = newInfo;
4877 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004878 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004879
4880 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004881 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4882 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4883 notifyIfacesChangedForNetworkStats();
4884 } else if (VDBG) log("ignoring duplicate network state non-change");
4885 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004886 return;
4887 }
4888 if (DBG) {
4889 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4890 (oldInfo == null ? "null" : oldInfo.getState()) +
4891 " to " + state);
4892 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004893
Robin Lee585e2482016-05-01 23:00:00 +01004894 if (!networkAgent.created
4895 && (state == NetworkInfo.State.CONNECTED
4896 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004897 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004898 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004899 if (networkAgent.isVPN()) {
4900 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004901 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4902 (networkAgent.networkMisc == null ||
4903 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004904 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004905 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4906 networkAgent.networkCapabilities.hasCapability(
4907 NET_CAPABILITY_NOT_RESTRICTED) ?
4908 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004909 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004910 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004911 loge("Error creating network " + networkAgent.network.netId + ": "
4912 + e.getMessage());
4913 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004914 }
Paul Jenseneec75412014-08-04 12:21:19 -04004915 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004916 }
4917
4918 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4919 networkAgent.everConnected = true;
4920
Robert Greenwalt7b816022014-04-18 15:25:25 -07004921 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004922 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004923
Paul Jensenca8f16a2014-05-09 12:47:55 -04004924 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004925 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004926
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004927 if (networkAgent.isVPN()) {
4928 // Temporarily disable the default proxy (not global).
4929 synchronized (mProxyLock) {
4930 if (!mDefaultProxyDisabled) {
4931 mDefaultProxyDisabled = true;
4932 if (mGlobalProxy == null && mDefaultProxy != null) {
4933 sendProxyBroadcast(null);
4934 }
4935 }
4936 }
4937 // TODO: support proxy per network.
4938 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004939
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004940 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4941 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4942 // capabilities, so it only needs to be done once on initial connect, not every time the
4943 // network's capabilities change. Note that we do this before rematching the network,
4944 // so we could decide to tear it down immediately afterwards. That's fine though - on
4945 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4946 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004947 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004948
Paul Jensen2161a8e2014-09-11 11:00:39 -04004949 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004950 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004951
4952 // This has to happen after matching the requests, because callbacks are just requests.
4953 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004954 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004955 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004956 if (networkAgent.isVPN()) {
4957 synchronized (mProxyLock) {
4958 if (mDefaultProxyDisabled) {
4959 mDefaultProxyDisabled = false;
4960 if (mGlobalProxy == null && mDefaultProxy != null) {
4961 sendProxyBroadcast(mDefaultProxy);
4962 }
4963 }
4964 }
4965 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004966 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4967 state == NetworkInfo.State.SUSPENDED) {
4968 // going into or coming out of SUSPEND: rescore and notify
4969 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004970 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004971 }
4972 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4973 ConnectivityManager.CALLBACK_SUSPENDED :
4974 ConnectivityManager.CALLBACK_RESUMED));
4975 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004976 }
4977 }
4978
Robert Greenwaltac96c522014-06-03 16:43:57 -07004979 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004980 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004981 if (score < 0) {
4982 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4983 "). Bumping score to min of 0");
4984 score = 0;
4985 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004986
Paul Jensen2161a8e2014-09-11 11:00:39 -04004987 final int oldScore = nai.getCurrentScore();
4988 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004989
Paul Jensen85cf78e2015-06-25 13:25:07 -04004990 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004991
Paul Jensenc8b9a742014-09-30 15:37:41 -04004992 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004993 }
4994
Robert Greenwalt9258c642014-03-26 16:47:06 -07004995 // notify only this one new request of the current state
4996 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4997 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4998 // TODO - read state from monitor to decide what to send.
4999// if (nai.networkMonitor.isLingering()) {
5000// notifyType = NetworkCallbacks.LOSING;
5001// } else if (nai.networkMonitor.isEvaluating()) {
5002// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5003// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005004 if (nri.mPendingIntent == null) {
5005 callCallbackForRequest(nri, nai, notifyType);
5006 } else {
5007 sendPendingIntentForRequest(nri, nai, notifyType);
5008 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005009 }
5010
Robert Greenwalt8d482522015-06-24 13:23:42 -07005011 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005012 // The NetworkInfo we actually send out has no bearing on the real
5013 // state of affairs. For example, if the default connection is mobile,
5014 // and a request for HIPRI has just gone away, we need to pretend that
5015 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5016 // the state to DISCONNECTED, even though the network is of type MOBILE
5017 // and is still connected.
5018 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5019 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005020 if (state != DetailedState.DISCONNECTED) {
5021 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005022 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005023 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005024 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005025 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5026 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5027 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5028 if (info.isFailover()) {
5029 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5030 nai.networkInfo.setFailover(false);
5031 }
5032 if (info.getReason() != null) {
5033 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5034 }
5035 if (info.getExtraInfo() != null) {
5036 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5037 }
5038 NetworkAgentInfo newDefaultAgent = null;
5039 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005040 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005041 if (newDefaultAgent != null) {
5042 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5043 newDefaultAgent.networkInfo);
5044 } else {
5045 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5046 }
5047 }
5048 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5049 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005050 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005051 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005052 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005053 }
5054 }
5055 }
5056
Robert Greenwalt7b816022014-04-18 15:25:25 -07005057 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005058 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005059 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005060 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
5061 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5062 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005063 if (nri.mPendingIntent == null) {
5064 callCallbackForRequest(nri, networkAgent, notifyType);
5065 } else {
5066 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5067 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005068 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005069 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005070
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005071 private String notifyTypeToName(int notifyType) {
5072 switch (notifyType) {
5073 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5074 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5075 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5076 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5077 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5078 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5079 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5080 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5081 }
5082 return "UNKNOWN";
5083 }
5084
Jeff Sharkey69736342014-12-08 14:50:12 -08005085 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005086 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5087 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005088 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005089 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005090 try {
5091 mStatsService.forceUpdateIfaces();
5092 } catch (Exception ignored) {
5093 }
5094 }
5095
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005096 @Override
5097 public boolean addVpnAddress(String address, int prefixLength) {
5098 throwIfLockdownEnabled();
5099 int user = UserHandle.getUserId(Binder.getCallingUid());
5100 synchronized (mVpns) {
5101 return mVpns.get(user).addAddress(address, prefixLength);
5102 }
5103 }
5104
5105 @Override
5106 public boolean removeVpnAddress(String address, int prefixLength) {
5107 throwIfLockdownEnabled();
5108 int user = UserHandle.getUserId(Binder.getCallingUid());
5109 synchronized (mVpns) {
5110 return mVpns.get(user).removeAddress(address, prefixLength);
5111 }
5112 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005113
5114 @Override
5115 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5116 throwIfLockdownEnabled();
5117 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005118 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005119 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005120 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005121 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005122 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005123 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005124 }
5125 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005126 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005127
5128 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005129 public String getCaptivePortalServerUrl() {
5130 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5131 }
5132
5133 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005134 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5135 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5136 enforceKeepalivePermission();
5137 mKeepaliveTracker.startNattKeepalive(
5138 getNetworkAgentInfoForNetwork(network),
5139 intervalSeconds, messenger, binder,
5140 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5141 }
5142
5143 @Override
5144 public void stopKeepalive(Network network, int slot) {
5145 mHandler.sendMessage(mHandler.obtainMessage(
5146 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5147 }
5148
5149 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005150 public void factoryReset() {
5151 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005152
5153 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5154 return;
5155 }
5156
Robin Lee3b3dd942015-05-12 18:14:58 +01005157 final int userId = UserHandle.getCallingUserId();
5158
Stuart Scottf1fb3972015-04-02 18:00:02 -07005159 // Turn airplane mode off
5160 setAirplaneMode(false);
5161
Stuart Scotte3e314d2015-04-20 14:07:45 -07005162 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5163 // Untether
5164 for (String tether : getTetheredIfaces()) {
5165 untether(tether);
5166 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005167 }
5168
Stuart Scotte3e314d2015-04-20 14:07:45 -07005169 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5170 // Turn VPN off
5171 VpnConfig vpnConfig = getVpnConfig(userId);
5172 if (vpnConfig != null) {
5173 if (vpnConfig.legacy) {
5174 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5175 } else {
5176 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5177 // in the future without user intervention.
5178 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005179
Stuart Scotte3e314d2015-04-20 14:07:45 -07005180 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5181 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005182 }
5183 }
5184 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005185
5186 @VisibleForTesting
5187 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5188 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5189 return new NetworkMonitor(context, handler, nai, defaultRequest);
5190 }
Erik Kline48f12f22016-04-14 17:30:59 +09005191
Hugo Benichi5f16f762016-04-20 12:09:33 +09005192 private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5193 int newNetid = NETID_UNSET;
5194 int prevNetid = NETID_UNSET;
5195 int[] transports = new int[0];
5196 boolean hadIPv4 = false;
5197 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005198
Hugo Benichi5f16f762016-04-20 12:09:33 +09005199 if (newNai != null) {
5200 newNetid = newNai.network.netId;
5201 transports = newNai.networkCapabilities.getTransportTypes();
5202 }
5203 if (prevNai != null) {
5204 prevNetid = prevNai.network.netId;
5205 final LinkProperties lp = prevNai.linkProperties;
5206 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5207 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5208 }
5209
5210 DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
Erik Kline48f12f22016-04-14 17:30:59 +09005211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005212}