blob: 707b142404312261da39400ced19fe5e405a6cb7 [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
Robin Lee17e61832016-05-09 13:46:28 +0100921 synchronized (mVpns) {
922 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
923 if (vpn != null && vpn.isBlockingUid(uid)) {
924 return true;
925 }
926 }
927
Robert Greenwalt12e67352014-05-13 21:41:06 -0700928 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700929 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600930 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -0700931 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700932 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700933
Felipe Lemed31a97f2016-05-06 14:53:50 -0700934 boolean allowed = true;
935 // Check Data Saver Mode first...
936 if (networkMetered) {
937 if ((uidRules & RULE_REJECT_METERED) != 0) {
938 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
939 // Explicitly blacklisted.
940 allowed = false;
941 } else {
942 allowed = !mRestrictBackground
943 || (uidRules & RULE_ALLOW_METERED) != 0
944 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
945 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
946 + " mRestrictBackground=" + mRestrictBackground
947 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
948 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
949 + ": " + allowed);
950 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700951 }
Felipe Lemed31a97f2016-05-06 14:53:50 -0700952 // ...then Battery Saver Mode.
953 if (allowed && mRestrictPower) {
954 allowed = (uidRules & RULE_ALLOW_ALL) != 0;
955 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
956 + " mRestrictPower=" + mRestrictPower
957 + ", whitelisted=" + ((uidRules & RULE_ALLOW_ALL) != 0)
958 + ": " + allowed);
959 }
960 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700961 }
962
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900963 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
964 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
965 boolean removed = false;
966 boolean added = false;
967 synchronized (mBlockedAppUids) {
968 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
969 added = true;
970 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
971 removed = true;
972 }
973 }
974 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
975 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
976 }
977
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700978 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600979 * Apply any relevant filters to {@link NetworkState} for the given UID. For
980 * example, this may mark the network as {@link DetailedState#BLOCKED} based
981 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
982 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700983 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600984 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600985 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
986
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600987 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600988 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700989 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600990 if (mLockdownTracker != null) {
991 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700992 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600993
994 // TODO: apply metered state closer to NetworkAgentInfo
995 final long token = Binder.clearCallingIdentity();
996 try {
997 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
998 } catch (RemoteException e) {
999 } finally {
1000 Binder.restoreCallingIdentity(token);
1001 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001002 }
1003
1004 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 * Return NetworkInfo for the active (i.e., connected) network interface.
1006 * It is assumed that at most one network is active at a time. If more
1007 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001008 * @return the info for the active network, or {@code null} if none is
1009 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001011 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001013 enforceAccessPermission();
1014 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001015 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001016 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001017 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1018 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 }
1020
Paul Jensen31a94f42015-02-13 14:18:39 -05001021 @Override
1022 public Network getActiveNetwork() {
1023 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001024 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001025 }
1026
1027 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001028 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001029 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001030 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001031 }
1032
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001033 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001034 final int user = UserHandle.getUserId(uid);
1035 int vpnNetId = NETID_UNSET;
1036 synchronized (mVpns) {
1037 final Vpn vpn = mVpns.get(user);
1038 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1039 }
1040 NetworkAgentInfo nai;
1041 if (vpnNetId != NETID_UNSET) {
1042 synchronized (mNetworkForNetId) {
1043 nai = mNetworkForNetId.get(vpnNetId);
1044 }
1045 if (nai != null) return nai.network;
1046 }
1047 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001048 if (nai != null
1049 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1050 nai = null;
1051 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001052 return nai != null ? nai.network : null;
1053 }
1054
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001055 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1056 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001057 final int uid = Binder.getCallingUid();
1058 NetworkState state = getUnfilteredActiveNetworkState(uid);
1059 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001060 }
1061
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001062 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001063 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001064 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001065 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001066 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001067 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001068 }
1069
1070 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 public NetworkInfo getNetworkInfo(int networkType) {
1072 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001073 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001074 if (getVpnUnderlyingNetworks(uid) != null) {
1075 // A VPN is active, so we may need to return one of its underlying networks. This
1076 // information is not available in LegacyTypeTracker, so we have to get it from
1077 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001078 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001079 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001080 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001081 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001082 }
1083 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001084 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001085 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 }
1087
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001088 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001089 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001090 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001091 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001092 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001093 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001094 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001095 return state.networkInfo;
1096 } else {
1097 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001098 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001099 }
1100
1101 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 public NetworkInfo[] getAllNetworkInfo() {
1103 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001104 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001105 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1106 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001107 NetworkInfo info = getNetworkInfo(networkType);
1108 if (info != null) {
1109 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001112 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 }
1114
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001115 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001116 public Network getNetworkForType(int networkType) {
1117 enforceAccessPermission();
1118 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001119 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1120 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001121 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001122 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001123 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001124 }
1125
1126 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001127 public Network[] getAllNetworks() {
1128 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001129 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001130 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001131 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001132 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001133 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001134 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001135 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001136 }
1137
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001138 @Override
1139 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1140 // The basic principle is: if an app's traffic could possibly go over a
1141 // network, without the app doing anything multinetwork-specific,
1142 // (hence, by "default"), then include that network's capabilities in
1143 // the array.
1144 //
1145 // In the normal case, app traffic only goes over the system's default
1146 // network connection, so that's the only network returned.
1147 //
1148 // With a VPN in force, some app traffic may go into the VPN, and thus
1149 // over whatever underlying networks the VPN specifies, while other app
1150 // traffic may go over the system default network (e.g.: a split-tunnel
1151 // VPN, or an app disallowed by the VPN), so the set of networks
1152 // returned includes the VPN's underlying networks and the system
1153 // default.
1154 enforceAccessPermission();
1155
1156 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1157
1158 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001159 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001160 if (nc != null) {
1161 result.put(nai.network, nc);
1162 }
1163
1164 if (!mLockdownEnabled) {
1165 synchronized (mVpns) {
1166 Vpn vpn = mVpns.get(userId);
1167 if (vpn != null) {
1168 Network[] networks = vpn.getUnderlyingNetworks();
1169 if (networks != null) {
1170 for (Network network : networks) {
1171 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001172 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001173 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001174 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001175 }
1176 }
1177 }
1178 }
1179 }
1180 }
1181
1182 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1183 out = result.values().toArray(out);
1184 return out;
1185 }
1186
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001187 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001188 public boolean isNetworkSupported(int networkType) {
1189 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001190 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001191 }
1192
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001193 /**
1194 * Return LinkProperties for the active (i.e., connected) default
1195 * network interface. It is assumed that at most one default network
1196 * is active at a time. If more than one is active, it is indeterminate
1197 * which will be returned.
1198 * @return the ip properties for the active network, or {@code null} if
1199 * none is active
1200 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001201 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001202 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001203 enforceAccessPermission();
1204 final int uid = Binder.getCallingUid();
1205 NetworkState state = getUnfilteredActiveNetworkState(uid);
1206 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001207 }
1208
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001209 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001210 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001211 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001212 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1213 if (nai != null) {
1214 synchronized (nai) {
1215 return new LinkProperties(nai.linkProperties);
1216 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001217 }
1218 return null;
1219 }
1220
Robert Greenwalt12e67352014-05-13 21:41:06 -07001221 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001222 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001223 public LinkProperties getLinkProperties(Network network) {
1224 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001225 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001226 if (nai != null) {
1227 synchronized (nai) {
1228 return new LinkProperties(nai.linkProperties);
1229 }
1230 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001231 return null;
1232 }
1233
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001234 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001235 if (nai != null) {
1236 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001237 if (nai.networkCapabilities != null) {
1238 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001239 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001240 }
1241 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001242 return null;
1243 }
1244
1245 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001246 public NetworkCapabilities getNetworkCapabilities(Network network) {
1247 enforceAccessPermission();
1248 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1249 }
1250
1251 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001252 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001253 // Require internal since we're handing out IMSI details
1254 enforceConnectivityInternalPermission();
1255
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001256 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001257 for (Network network : getAllNetworks()) {
1258 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1259 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001260 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001261 }
1262 }
1263 return result.toArray(new NetworkState[result.size()]);
1264 }
1265
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001266 @Override
1267 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1268 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001269 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001270 final long token = Binder.clearCallingIdentity();
1271 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001272 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1273 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001274 try {
1275 return mPolicyManager.getNetworkQuotaInfo(state);
1276 } catch (RemoteException e) {
1277 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001278 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001279 return null;
1280 } finally {
1281 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001282 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001283 }
1284
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001285 @Override
1286 public boolean isActiveNetworkMetered() {
1287 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001288
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001289 final NetworkInfo info = getActiveNetworkInfo();
1290 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001291 }
1292
Jeff Sharkey216c1812012-08-05 14:29:23 -07001293 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1294 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001295 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001296 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001297 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001298 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001299 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001300
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001301 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 * Ensure that a network route exists to deliver traffic to the specified
1303 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001304 * @param networkType the type of the network over which traffic to the
1305 * specified host is to be routed
1306 * @param hostAddress the IP address of the host to which the route is
1307 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 * @return {@code true} on success, {@code false} on failure
1309 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001310 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001312 if (mProtectedNetworks.contains(networkType)) {
1313 enforceConnectivityInternalPermission();
1314 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001315
Chad Brubakerc0234532014-02-14 13:24:29 -08001316 InetAddress addr;
1317 try {
1318 addr = InetAddress.getByAddress(hostAddress);
1319 } catch (UnknownHostException e) {
1320 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1321 return false;
1322 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001325 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 return false;
1327 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001328
1329 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1330 if (nai == null) {
1331 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1332 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1333 } else {
1334 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1335 }
1336 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001337 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001338
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001339 DetailedState netState;
1340 synchronized (nai) {
1341 netState = nai.networkInfo.getDetailedState();
1342 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001343
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001344 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001345 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001346 log("requestRouteToHostAddress on down network "
1347 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001348 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001349 }
1350 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001352
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001353 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001354 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001355 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001356 LinkProperties lp;
1357 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001358 synchronized (nai) {
1359 lp = nai.linkProperties;
1360 netId = nai.network.netId;
1361 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001362 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001363 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1364 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001365 } finally {
1366 Binder.restoreCallingIdentity(token);
1367 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001368 }
1369
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001370 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001371 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001372 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001373 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001374 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001375 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001376 if (bestRoute.getGateway().equals(addr)) {
1377 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001378 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001379 } else {
1380 // if we will connect to this through another route, add a direct route
1381 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001382 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001383 }
1384 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001385 if (DBG) log("Adding legacy route " + bestRoute +
1386 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001387 try {
1388 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1389 } catch (Exception e) {
1390 // never crash - catch them all
1391 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001392 return false;
1393 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001394 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
1396
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001397 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1398 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001399 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001400 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001401 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001402 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001403 }
1404
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001405 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001406 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001407 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001408 if (oldRules == uidRules) return;
1409
1410 mUidRules.put(uid, uidRules);
1411 }
1412
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001413 // TODO: notify UID when it has requested targeted updates
1414 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001415
1416 @Override
1417 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001418 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001419 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001420 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001421 }
1422
1423 synchronized (mRulesLock) {
1424 mMeteredIfaces.clear();
1425 for (String iface : meteredIfaces) {
1426 mMeteredIfaces.add(iface);
1427 }
1428 }
1429 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001430
1431 @Override
1432 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1433 // caller is NPMS, since we only register with them
1434 if (LOGD_RULES) {
1435 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1436 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001437
1438 synchronized (mRulesLock) {
1439 mRestrictBackground = restrictBackground;
1440 }
1441
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001442 if (restrictBackground) {
1443 log("onRestrictBackgroundChanged(true): disabling tethering");
1444 mTethering.untetherAll();
1445 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001446 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001447
1448 @Override
Felipe Lemed31a97f2016-05-06 14:53:50 -07001449 public void onRestrictPowerChanged(boolean restrictPower) {
1450 // caller is NPMS, since we only register with them
1451 if (LOGD_RULES) {
1452 log("onRestrictPowerChanged(restrictPower=" + restrictPower + ")");
1453 }
1454
1455 synchronized (mRulesLock) {
1456 mRestrictPower = restrictPower;
1457 }
1458 }
1459
1460 @Override
Felipe Leme019fcd22016-04-19 10:24:39 -07001461 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1462 if (LOGD_RULES) {
1463 // caller is NPMS, since we only register with them
1464 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1465 + whitelisted + ")");
1466 }
1467 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001468 };
1469
Robin Lee3b3dd942015-05-12 18:14:58 +01001470 /**
1471 * Require that the caller is either in the same user or has appropriate permission to interact
1472 * across users.
1473 *
1474 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1475 */
1476 private void enforceCrossUserPermission(int userId) {
1477 if (userId == UserHandle.getCallingUserId()) {
1478 // Not a cross-user call.
1479 return;
1480 }
1481 mContext.enforceCallingOrSelfPermission(
1482 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1483 "ConnectivityService");
1484 }
1485
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001486 private void enforceInternetPermission() {
1487 mContext.enforceCallingOrSelfPermission(
1488 android.Manifest.permission.INTERNET,
1489 "ConnectivityService");
1490 }
1491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001493 mContext.enforceCallingOrSelfPermission(
1494 android.Manifest.permission.ACCESS_NETWORK_STATE,
1495 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
1497
1498 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001499 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 }
1501
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001502 private void enforceTetherAccessPermission() {
1503 mContext.enforceCallingOrSelfPermission(
1504 android.Manifest.permission.ACCESS_NETWORK_STATE,
1505 "ConnectivityService");
1506 }
1507
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001508 private void enforceConnectivityInternalPermission() {
1509 mContext.enforceCallingOrSelfPermission(
1510 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1511 "ConnectivityService");
1512 }
1513
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001514 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001515 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001516 }
1517
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001518 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001519 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001520 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001521 }
1522
1523 private void sendInetConditionBroadcast(NetworkInfo info) {
1524 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1525 }
1526
Wink Saville628b0852011-08-04 15:01:58 -07001527 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001528 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001529 info = new NetworkInfo(info);
1530 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001531 }
1532
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001533 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001534 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001535 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 if (info.isFailover()) {
1537 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1538 info.setFailover(false);
1539 }
1540 if (info.getReason() != null) {
1541 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1542 }
1543 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001544 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1545 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001547 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001548 return intent;
1549 }
1550
1551 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1552 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1553 }
1554
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001555 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001556 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1557 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1558 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001559 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001560 final long ident = Binder.clearCallingIdentity();
1561 try {
1562 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1563 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1564 } finally {
1565 Binder.restoreCallingIdentity(ident);
1566 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001567 }
1568
Mike Lockwood0f79b542009-08-14 14:18:49 -04001569 private void sendStickyBroadcast(Intent intent) {
1570 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001571 if (!mSystemReady) {
1572 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001573 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001574 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001575 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001576 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001577 }
1578
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001579 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001580 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001581 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001582 final NetworkInfo ni = intent.getParcelableExtra(
1583 ConnectivityManager.EXTRA_NETWORK_INFO);
1584 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1585 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1586 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001587 } else {
1588 BroadcastOptions opts = BroadcastOptions.makeBasic();
1589 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1590 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001591 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001592 final IBatteryStats bs = BatteryStatsService.getService();
1593 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001594 bs.noteConnectivityChanged(intent.getIntExtra(
1595 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1596 ni != null ? ni.getState().toString() : "?");
1597 } catch (RemoteException e) {
1598 }
1599 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001600 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001601 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001602 } finally {
1603 Binder.restoreCallingIdentity(ident);
1604 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001605 }
1606 }
1607
1608 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001609 loadGlobalProxy();
1610
Mike Lockwood0f79b542009-08-14 14:18:49 -04001611 synchronized(this) {
1612 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001613 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001614 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001615 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001616 }
1617 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001618 // load the global proxy at startup
1619 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001620
Robin Lee244ce8e2016-01-05 18:03:46 +00001621 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1622 // for user to unlock device too.
1623 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001624
Erik Klineda4bfa82015-04-30 12:58:40 +09001625 // Configure whether mobile data is always on.
1626 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1627
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001628 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001629
1630 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 }
1632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001634 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001635 *
1636 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001637 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001638 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001639 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1640 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001641
1642 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001643 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001644
Robert Greenwalt7b816022014-04-18 15:25:25 -07001645 if (networkAgent.networkCapabilities.hasTransport(
1646 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001647 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1648 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001649 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001650 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001651 } else if (networkAgent.networkCapabilities.hasTransport(
1652 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001653 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1654 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001655 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001656 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001657 } else {
1658 // do not track any other networks
1659 timeout = 0;
1660 }
1661
Robert Greenwalt7b816022014-04-18 15:25:25 -07001662 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001663 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001664 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001665 } catch (Exception e) {
1666 // You shall not crash!
1667 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001668 }
1669 }
1670 }
1671
1672 /**
1673 * Remove data activity tracking when network disconnects.
1674 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001675 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1676 final String iface = networkAgent.linkProperties.getInterfaceName();
1677 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001678
Robert Greenwalt7b816022014-04-18 15:25:25 -07001679 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1680 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001681 try {
1682 // the call fails silently if no idletimer setup for this interface
1683 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001684 } catch (Exception e) {
1685 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001686 }
1687 }
1688 }
1689
1690 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001691 * Reads the network specific MTU size from reources.
1692 * and set it on it's iface.
1693 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001694 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1695 final String iface = newLp.getInterfaceName();
1696 final int mtu = newLp.getMtu();
1697 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1698 if (VDBG) log("identical MTU - not setting");
1699 return;
1700 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001701
Robert Greenwalt43074032014-08-15 17:53:05 -07001702 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001703 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001704 return;
1705 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001706
w1997615afd812014-08-05 15:18:11 -07001707 // Cannot set MTU without interface name
1708 if (TextUtils.isEmpty(iface)) {
1709 loge("Setting MTU size with null iface.");
1710 return;
1711 }
1712
Robert Greenwalt7b816022014-04-18 15:25:25 -07001713 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001714 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001715 mNetd.setMtu(iface, mtu);
1716 } catch (Exception e) {
1717 Slog.e(TAG, "exception in setMtu()" + e);
1718 }
1719 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001720
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001721 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001722 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1723
1724 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001725 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001726 protected int getDefaultTcpRwnd() {
1727 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1728 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001729
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001730 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1731 if (isDefaultNetwork(nai) == false) {
1732 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001733 }
1734
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001735 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1736 String[] values = null;
1737 if (tcpBufferSizes != null) {
1738 values = tcpBufferSizes.split(",");
1739 }
1740
1741 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001742 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001743 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1744 values = tcpBufferSizes.split(",");
1745 }
1746
1747 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1748
1749 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001750 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001751
1752 final String prefix = "/sys/kernel/ipv4/tcp_";
1753 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1754 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1755 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1756 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1757 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1758 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1759 mCurrentTcpBufferSizes = tcpBufferSizes;
1760 } catch (IOException e) {
1761 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001762 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001763
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001764 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001765 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001766 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1767 if (rwndValue != 0) {
1768 SystemProperties.set(sysctlKey, rwndValue.toString());
1769 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001770 }
1771
Mattias Falk8b47b362011-08-23 14:15:13 +02001772 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001773 /*
1774 * Tell the VMs to toss their DNS caches
1775 */
1776 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1777 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001778 /*
1779 * Connectivity events can happen before boot has completed ...
1780 */
1781 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001782 final long ident = Binder.clearCallingIdentity();
1783 try {
1784 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1785 } finally {
1786 Binder.restoreCallingIdentity(ident);
1787 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001788 }
1789
Robert Greenwalt562cc542014-05-15 18:07:26 -07001790 @Override
1791 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001792 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1793 NETWORK_RESTORE_DELAY_PROP_NAME);
1794 if(restoreDefaultNetworkDelayStr != null &&
1795 restoreDefaultNetworkDelayStr.length() != 0) {
1796 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001797 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001798 } catch (NumberFormatException e) {
1799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001801 // if the system property isn't set, use the value for the apn type
1802 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1803
1804 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1805 (mNetConfigs[networkType] != null)) {
1806 ret = mNetConfigs[networkType].restoreTime;
1807 }
1808 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001811 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001812 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001813 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001814 }
1815 return false;
1816 }
1817
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001818 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1819 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1820 final long DIAG_TIME_MS = 5000;
1821 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1822 // Start gathering diagnostic information.
1823 netDiags.add(new NetworkDiagnostics(
1824 nai.network,
1825 new LinkProperties(nai.linkProperties), // Must be a copy.
1826 DIAG_TIME_MS));
1827 }
1828
1829 for (NetworkDiagnostics netDiag : netDiags) {
1830 pw.println();
1831 netDiag.waitForMeasurements();
1832 netDiag.dump(pw);
1833 }
1834 }
1835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001837 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1838 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001839 if (mContext.checkCallingOrSelfPermission(
1840 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001842 pw.println("Permission Denial: can't dump ConnectivityService " +
1843 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1844 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 return;
1846 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001847
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001848 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001849 dumpNetworkDiagnostics(pw);
1850 return;
1851 }
Erik Kline379747a2015-06-05 17:47:34 +09001852
Lorenzo Colittie3805462015-06-03 11:18:24 +09001853 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001854 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001855 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001856 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001857 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001858 pw.println();
1859
Paul Jensen85cf78e2015-06-25 13:25:07 -04001860 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001861 pw.print("Active default network: ");
1862 if (defaultNai == null) {
1863 pw.println("none");
1864 } else {
1865 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001867 pw.println();
1868
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001869 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001870 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001871 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1872 pw.println(nai.toString());
1873 pw.increaseIndent();
1874 pw.println("Requests:");
1875 pw.increaseIndent();
1876 for (int i = 0; i < nai.networkRequests.size(); i++) {
1877 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001878 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001879 pw.decreaseIndent();
1880 pw.println("Lingered:");
1881 pw.increaseIndent();
1882 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1883 pw.decreaseIndent();
1884 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001885 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001886 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001887 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001888
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001889 pw.println("Metered Interfaces:");
1890 pw.increaseIndent();
1891 for (String value : mMeteredIfaces) {
1892 pw.println(value);
1893 }
1894 pw.decreaseIndent();
1895 pw.println();
1896
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001897 pw.print("Restrict background: ");
1898 pw.println(mRestrictBackground);
1899 pw.println();
1900
Felipe Lemed31a97f2016-05-06 14:53:50 -07001901 pw.print("Restrict power: ");
1902 pw.println(mRestrictPower);
1903 pw.println();
1904
Felipe Leme46c4fc32016-05-04 09:21:43 -07001905 pw.println("Status for known UIDs:");
1906 pw.increaseIndent();
1907 final int size = mUidRules.size();
1908 for (int i = 0; i < size; i++) {
1909 final int uid = mUidRules.keyAt(i);
1910 pw.print("UID=");
1911 pw.print(uid);
1912 final int uidRules = mUidRules.get(uid, RULE_NONE);
1913 pw.print(" rules=");
1914 pw.print(uidRulesToString(uidRules));
1915 pw.println();
1916 }
1917 pw.println();
1918 pw.decreaseIndent();
1919
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001920 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001921 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001922 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1923 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001924 }
1925 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001926 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001927
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001928 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001929
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001930 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001931 pw.print("mNetTransitionWakeLock: currently " +
1932 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1933 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1934 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1935 } else {
1936 pw.println(", last requested never");
1937 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001938 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001939
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001940 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001941 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001942
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001943 pw.println();
1944 mKeepaliveTracker.dump(pw);
1945
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001946 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001947
Lorenzo Colittie3805462015-06-03 11:18:24 +09001948 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001949 pw.println();
1950 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001951 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001952 for(int i = 0; i < mInetLog.size(); i++) {
1953 pw.println(mInetLog.get(i));
1954 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001955 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001956 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001957
1958 if (argsContain(args, "--short") == false) {
1959 pw.println();
1960 synchronized (mValidationLogs) {
1961 pw.println("mValidationLogs (most recent first):");
1962 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1963 pw.println(p.first);
1964 pw.increaseIndent();
1965 p.second.dump(fd, pw, args);
1966 pw.decreaseIndent();
1967 }
1968 }
Erik Kline7523eb32015-07-09 18:24:03 +09001969
1970 pw.println();
1971 pw.println("mNetworkRequestInfoLogs (most recent first):");
1972 pw.increaseIndent();
1973 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1974 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
1977
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001978 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001979 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001980 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001981 if (officialNai != null && officialNai.equals(nai)) return true;
1982 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001983 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001984 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001985 " - " + nai);
1986 }
1987 return false;
1988 }
1989
Paul Jensenc8b9a742014-09-30 15:37:41 -04001990 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001991 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001992 }
1993
Robert Greenwalt42acef32009-08-12 16:08:25 -07001994 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001995 private class NetworkStateTrackerHandler extends Handler {
1996 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001997 super(looper);
1998 }
1999
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002000 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002002 default:
2003 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002004 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002005 handleAsyncChannelHalfConnect(msg);
2006 break;
2007 }
2008 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2009 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2010 if (nai != null) nai.asyncChannel.disconnect();
2011 break;
2012 }
2013 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2014 handleAsyncChannelDisconnected(msg);
2015 break;
2016 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002017 }
2018 return true;
2019 }
2020
2021 private void maybeHandleNetworkAgentMessage(Message msg) {
2022 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2023 if (nai == null) {
2024 if (VDBG) {
2025 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2026 log(String.format("%s from unknown NetworkAgent", what));
2027 }
2028 return;
2029 }
2030
2031 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002032 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002033 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2034 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2035 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2036 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002037 }
Robin Lee585e2482016-05-01 23:00:00 +01002038 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002039 networkCapabilities)) {
2040 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2041 + nai.networkCapabilities + " -> " + networkCapabilities);
2042 }
2043 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002044 break;
2045 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002046 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002047 if (VDBG) {
2048 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002049 "; created=" + nai.created +
2050 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002051 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002052 LinkProperties oldLp = nai.linkProperties;
2053 synchronized (nai) {
2054 nai.linkProperties = (LinkProperties)msg.obj;
2055 }
Robin Lee585e2482016-05-01 23:00:00 +01002056 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002057 break;
2058 }
2059 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002060 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002061 updateNetworkInfo(nai, info);
2062 break;
2063 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002064 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002065 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002066 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002067 break;
2068 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002069 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002070 try {
2071 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002072 } catch (Exception e) {
2073 // Never crash!
2074 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002075 }
2076 break;
2077 }
2078 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002079 try {
2080 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002081 } catch (Exception e) {
2082 // Never crash!
2083 loge("Exception in removeVpnUidRanges: " + e);
2084 }
2085 break;
2086 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002087 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002088 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2089 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002090 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002091 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002092 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002093 break;
2094 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002095 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002096 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2097 break;
2098 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002099 }
2100 }
2101
2102 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2103 switch (msg.what) {
2104 default:
2105 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002106 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002107 final NetworkAgentInfo nai;
2108 synchronized (mNetworkForNetId) {
2109 nai = mNetworkForNetId.get(msg.arg2);
2110 }
2111 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002112 final boolean valid =
2113 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002114 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2115 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002116 if (valid != nai.lastValidated) {
2117 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002118 nai.lastValidated = valid;
2119 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002120 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002121 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2122 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002123 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002124 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002125 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002126 Bundle redirectUrlBundle = new Bundle();
2127 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002128 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002129 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002130 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002131 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002132 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 break;
2134 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002135 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002136 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002137 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002138 handleLingerComplete(nai);
2139 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002140 break;
2141 }
Paul Jensen869868be2014-05-15 10:33:05 -04002142 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002143 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002144 final boolean visible = (msg.arg1 != 0);
2145 final NetworkAgentInfo nai;
2146 synchronized (mNetworkForNetId) {
2147 nai = mNetworkForNetId.get(netId);
2148 }
2149 // If captive portal status has changed, update capabilities.
2150 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2151 nai.lastCaptivePortalDetected = visible;
2152 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002153 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002154 }
2155 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002156 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002157 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002158 if (nai == null) {
2159 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2160 break;
2161 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002162 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002163 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2164 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002165 }
Paul Jensen869868be2014-05-15 10:33:05 -04002166 break;
2167 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002168 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002169 return true;
2170 }
2171
2172 @Override
2173 public void handleMessage(Message msg) {
2174 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2175 maybeHandleNetworkAgentMessage(msg);
2176 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002177 }
2178 }
2179
Paul Jensen85cf78e2015-06-25 13:25:07 -04002180 private void linger(NetworkAgentInfo nai) {
2181 nai.lingering = true;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002182 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002183 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2184 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2185 }
2186
Paul Jensen0cc17322014-11-25 15:26:53 -05002187 // Cancel any lingering so the linger timeout doesn't teardown a network.
2188 // This should be called when a network begins satisfying a NetworkRequest.
2189 // Note: depending on what state the NetworkMonitor is in (e.g.,
2190 // if it's awaiting captive portal login, or if validation failed), this
2191 // may trigger a re-evaluation of the network.
2192 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002193 nai.networkLingered.clear();
2194 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002195 nai.lingering = false;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002196 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
Paul Jensen0cc17322014-11-25 15:26:53 -05002197 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002198 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2199 }
2200
Robert Greenwalt7b816022014-04-18 15:25:25 -07002201 private void handleAsyncChannelHalfConnect(Message msg) {
2202 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002203 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002204 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2205 if (VDBG) log("NetworkFactory connected");
2206 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002207 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002208 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002209 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002210 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002211 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002212 }
2213 } else {
2214 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002215 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002216 }
2217 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2218 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2219 if (VDBG) log("NetworkAgent connected");
2220 // A network agent has requested a connection. Establish the connection.
2221 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2222 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2223 } else {
2224 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002225 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002226 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002227 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002228 synchronized (mNetworkForNetId) {
2229 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002230 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002231 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002232 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002233 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002234 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002235 }
2236 }
2237 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002238
Robert Greenwalt7b816022014-04-18 15:25:25 -07002239 private void handleAsyncChannelDisconnected(Message msg) {
2240 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2241 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002242 if (DBG) {
2243 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2244 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002245 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002246 // TODO - if we move the logic to the network agent (have them disconnect
2247 // because they lost all their requests or because their score isn't good)
2248 // then they would disconnect organically, report their new state and then
2249 // disconnect the channel.
2250 if (nai.networkInfo.isConnected()) {
2251 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2252 null, null);
2253 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002254 final boolean wasDefault = isDefaultNetwork(nai);
2255 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002256 mDefaultInetConditionPublished = 0;
2257 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002258 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002259 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2260 // by other networks that are already connected. Perhaps that can be done by
2261 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2262 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002263 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002264 mKeepaliveTracker.handleStopAllKeepalives(nai,
2265 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002266 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002267 mNetworkAgentInfos.remove(msg.replyTo);
2268 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002269 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002270 // Remove the NetworkAgent, but don't mark the netId as
2271 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002272 mNetworkForNetId.remove(nai.network.netId);
2273 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002274 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002275 for (int i = 0; i < nai.networkRequests.size(); i++) {
2276 NetworkRequest request = nai.networkRequests.valueAt(i);
2277 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2278 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2279 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002280 sendUpdatedScoreToFactories(request, 0);
2281 }
2282 }
2283 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2284 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002285 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002286 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002287 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002288 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002289 rematchAllNetworksAndRequests(null, 0);
Pierre Imai04e222252016-04-12 18:02:58 +09002290 if (wasDefault && getDefaultNetwork() == null) {
2291 // Log that we lost the default network and there is no replacement.
Hugo Benichi5f16f762016-04-20 12:09:33 +09002292 logDefaultNetworkEvent(null, nai);
Pierre Imai04e222252016-04-12 18:02:58 +09002293 }
Paul Jensen62d30802015-06-17 14:42:30 -04002294 if (nai.created) {
2295 // Tell netd to clean up the configuration for this network
2296 // (routing rules, DNS, etc).
2297 // This may be slow as it requires a lot of netd shelling out to ip and
2298 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2299 // after we've rematched networks with requests which should make a potential
2300 // fallback network the default or requested a new network from the
2301 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2302 // long time.
2303 try {
2304 mNetd.removeNetwork(nai.network.netId);
2305 } catch (Exception e) {
2306 loge("Exception removing network: " + e);
2307 }
2308 }
2309 synchronized (mNetworkForNetId) {
2310 mNetIdInUse.delete(nai.network.netId);
2311 }
2312 } else {
2313 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2314 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002315 }
2316 }
2317
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002318 // If this method proves to be too slow then we can maintain a separate
2319 // pendingIntent => NetworkRequestInfo map.
2320 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2321 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2322 Intent intent = pendingIntent.getIntent();
2323 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2324 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2325 if (existingPendingIntent != null &&
2326 existingPendingIntent.getIntent().filterEquals(intent)) {
2327 return entry.getValue();
2328 }
2329 }
2330 return null;
2331 }
2332
2333 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2334 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2335
2336 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2337 if (existingRequest != null) { // remove the existing request.
2338 if (DBG) log("Replacing " + existingRequest.request + " with "
2339 + nri.request + " because their intents matched.");
2340 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2341 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002342 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002343 }
2344
Erik Klineda4bfa82015-04-30 12:58:40 +09002345 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002346 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002347 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002348 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002349 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002350 if (nri.request.networkCapabilities.hasSignalStrength() &&
2351 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2352 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002353 }
2354 }
2355 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002356 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002357 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002358 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002359 }
2360 }
2361
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002362 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2363 int callingUid) {
2364 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2365 if (nri != null) {
2366 handleReleaseNetworkRequest(nri.request, callingUid);
2367 }
2368 }
2369
Paul Jensen99364842014-12-09 11:43:45 -05002370 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002371 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2372 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002373 private boolean unneeded(NetworkAgentInfo nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002374 if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002375 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2376 // If this Network is already the highest scoring Network for a request, or if
2377 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002378 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002379 (nai.networkRequests.get(nri.request.requestId) != null ||
2380 // Note that this catches two important cases:
2381 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2382 // is currently satisfying the request. This is desirable when
2383 // cellular ends up validating but WiFi does not.
2384 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002385 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002386 // WiFi ends up validating and out scoring cellular.
2387 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2388 nai.getCurrentScoreAsValidated())) {
2389 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002390 }
2391 }
Paul Jensene0988542015-06-25 15:30:08 -04002392 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002393 }
2394
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002395 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2396 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002397 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002398 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002399 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2400 return;
2401 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002402 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002403 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002404 mNetworkRequests.remove(request);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002405 synchronized (mUidToNetworkRequestCount) {
2406 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2407 if (requests < 1) {
2408 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2409 nri.mUid);
2410 } else if (requests == 1) {
2411 mUidToNetworkRequestCount.removeAt(
2412 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2413 } else {
2414 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2415 }
2416 }
Erik Kline7523eb32015-07-09 18:24:03 +09002417 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002418 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002419 // Find all networks that are satisfying this request and remove the request
2420 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002421 // TODO - it's my understanding that for a request there is only a single
2422 // network satisfying it, so this loop is wasteful
2423 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002424 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2425 if (nai.networkRequests.get(nri.request.requestId) != null) {
2426 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002427 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002428 log(" Removing from current network " + nai.name() +
2429 ", leaving " + nai.networkRequests.size() +
2430 " requests.");
2431 }
Paul Jensen99364842014-12-09 11:43:45 -05002432 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002433 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002434 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002435 } else {
2436 // suspect there should only be one pass through here
2437 // but if any were kept do the check below
2438 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002439 }
2440 }
2441 }
2442
Robert Greenwalt51481852015-01-08 14:43:31 -08002443 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2444 if (nai != null) {
2445 mNetworkForRequestId.remove(nri.request.requestId);
2446 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002447 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002448 // that a network connected to serve it, even though the network was already
2449 // connected. Now that this request has gone away, we might have to pretend
2450 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002451 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002452 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2453 boolean doRemove = true;
2454 if (wasKept) {
2455 // check if any of the remaining requests for this network are for the
2456 // same legacy type - if so, don't remove the nai
2457 for (int i = 0; i < nai.networkRequests.size(); i++) {
2458 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2459 if (otherRequest.legacyType == nri.request.legacyType &&
2460 isRequest(otherRequest)) {
2461 if (DBG) log(" still have other legacy request - leaving");
2462 doRemove = false;
2463 }
2464 }
2465 }
2466
2467 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002468 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002469 }
2470 }
2471
Robert Greenwalta67be032014-05-16 15:49:14 -07002472 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002473 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2474 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002475 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002476 } else {
2477 // listens don't have a singular affectedNetwork. Check all networks to see
2478 // if this listen request applies and remove it.
2479 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2480 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002481 if (nri.request.networkCapabilities.hasSignalStrength() &&
2482 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2483 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002484 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002485 }
2486 }
2487 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2488 }
2489 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002490
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002491 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2492 enforceConnectivityInternalPermission();
2493 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2494 accept ? 1 : 0, always ? 1: 0, network));
2495 }
2496
2497 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2498 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2499 " accept=" + accept + " always=" + always);
2500
2501 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2502 if (nai == null) {
2503 // Nothing to do.
2504 return;
2505 }
2506
2507 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002508 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002509 return;
2510 }
2511
2512 if (!nai.networkMisc.explicitlySelected) {
2513 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2514 }
2515
2516 if (accept != nai.networkMisc.acceptUnvalidated) {
2517 int oldScore = nai.getCurrentScore();
2518 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002519 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002520 sendUpdatedScoreToFactories(nai);
2521 }
2522
2523 if (always) {
2524 nai.asyncChannel.sendMessage(
2525 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2526 }
2527
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002528 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002529 // Tell the NetworkAgent to not automatically reconnect to the network.
2530 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2531 // Teardown the nework.
2532 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002533 }
2534
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002535 }
2536
2537 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002538 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002539 mHandler.sendMessageDelayed(
2540 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2541 PROMPT_UNVALIDATED_DELAY_MS);
2542 }
2543
2544 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002545 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002546 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2547
2548 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2549 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002550 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002551 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002552 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2553 return;
2554 }
2555
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002556 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002557 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002558 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2559 intent.setClassName("com.android.settings",
2560 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002561
2562 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2563 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2564 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002565 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002566 }
2567
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002568 private class InternalHandler extends Handler {
2569 public InternalHandler(Looper looper) {
2570 super(looper);
2571 }
2572
2573 @Override
2574 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002575 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002576 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002577 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002578 String causedBy = null;
2579 synchronized (ConnectivityService.this) {
2580 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2581 mNetTransitionWakeLock.isHeld()) {
2582 mNetTransitionWakeLock.release();
2583 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002584 } else {
2585 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002586 }
2587 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002588 if (VDBG) {
2589 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2590 log("Failed to find a new network - expiring NetTransition Wakelock");
2591 } else {
2592 log("NetTransition Wakelock (" +
2593 (causedBy == null ? "unknown" : causedBy) +
2594 " cleared because we found a replacement network");
2595 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002596 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002597 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002598 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002599 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002600 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002601 break;
2602 }
Jason Monkdecd2952013-10-10 14:02:51 -04002603 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002604 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002605 break;
2606 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002607 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002608 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2609 break;
2610 }
2611 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2612 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002613 break;
2614 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002615 case EVENT_REGISTER_NETWORK_AGENT: {
2616 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2617 break;
2618 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002619 case EVENT_REGISTER_NETWORK_REQUEST:
2620 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002621 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002622 break;
2623 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002624 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2625 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002626 handleRegisterNetworkRequestWithIntent(msg);
2627 break;
2628 }
2629 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2630 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2631 break;
2632 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002633 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002634 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002635 break;
2636 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002637 case EVENT_SET_ACCEPT_UNVALIDATED: {
2638 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2639 break;
2640 }
2641 case EVENT_PROMPT_UNVALIDATED: {
2642 handlePromptUnvalidated((Network) msg.obj);
2643 break;
2644 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002645 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2646 handleMobileDataAlwaysOn();
2647 break;
2648 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002649 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2650 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2651 mKeepaliveTracker.handleStartKeepalive(msg);
2652 break;
2653 }
2654 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2655 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2656 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2657 int slot = msg.arg1;
2658 int reason = msg.arg2;
2659 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2660 break;
2661 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002662 case EVENT_SYSTEM_READY: {
2663 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2664 nai.networkMonitor.systemReady = true;
2665 }
2666 break;
2667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 }
2669 }
2670 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002671
2672 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002673 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002674 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002675 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002676 final int status = mTethering.tether(iface);
2677 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2678 try {
2679 mPolicyManager.onTetheringChanged(iface, true);
2680 } catch (RemoteException e) {
2681 }
2682 }
2683 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002684 } else {
2685 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2686 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002687 }
2688
2689 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002690 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002691 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002692
2693 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002694 final int status = mTethering.untether(iface);
2695 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2696 try {
2697 mPolicyManager.onTetheringChanged(iface, false);
2698 } catch (RemoteException e) {
2699 }
2700 }
2701 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002702 } else {
2703 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2704 }
2705 }
2706
2707 // javadoc from interface
2708 public int getLastTetherError(String iface) {
2709 enforceTetherAccessPermission();
2710
2711 if (isTetheringSupported()) {
2712 return mTethering.getLastTetherError(iface);
2713 } else {
2714 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2715 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002716 }
2717
2718 // TODO - proper iface API for selection by property, inspection, etc
2719 public String[] getTetherableUsbRegexs() {
2720 enforceTetherAccessPermission();
2721 if (isTetheringSupported()) {
2722 return mTethering.getTetherableUsbRegexs();
2723 } else {
2724 return new String[0];
2725 }
2726 }
2727
2728 public String[] getTetherableWifiRegexs() {
2729 enforceTetherAccessPermission();
2730 if (isTetheringSupported()) {
2731 return mTethering.getTetherableWifiRegexs();
2732 } else {
2733 return new String[0];
2734 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002735 }
2736
Danica Chang6fdd0c62010-08-11 14:54:43 -07002737 public String[] getTetherableBluetoothRegexs() {
2738 enforceTetherAccessPermission();
2739 if (isTetheringSupported()) {
2740 return mTethering.getTetherableBluetoothRegexs();
2741 } else {
2742 return new String[0];
2743 }
2744 }
2745
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002746 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002747 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002748 if (isTetheringSupported()) {
2749 return mTethering.setUsbTethering(enable);
2750 } else {
2751 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2752 }
2753 }
2754
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002755 // TODO - move iface listing, queries, etc to new module
2756 // javadoc from interface
2757 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002758 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002759 return mTethering.getTetherableIfaces();
2760 }
2761
2762 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002763 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002764 return mTethering.getTetheredIfaces();
2765 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002766
Robert Greenwalt5a735062010-03-02 17:25:02 -08002767 public String[] getTetheringErroredIfaces() {
2768 enforceTetherAccessPermission();
2769 return mTethering.getErroredIfaces();
2770 }
2771
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002772 public String[] getTetheredDhcpRanges() {
2773 enforceConnectivityInternalPermission();
2774 return mTethering.getTetheredDhcpRanges();
2775 }
2776
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002777 // if ro.tether.denied = true we default to no tethering
2778 // gservices could set the secure setting to 1 though to enable it on a build where it
2779 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002780 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002781 public boolean isTetheringSupported() {
2782 enforceTetherAccessPermission();
2783 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002784 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002785 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2786 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002787 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2788 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002789 mTethering.getTetherableWifiRegexs().length != 0 ||
2790 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2791 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002792 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002793
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002794 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002795 public void startTethering(int type, ResultReceiver receiver,
2796 boolean showProvisioningUi) {
2797 ConnectivityManager.enforceTetherChangePermission(mContext);
2798 if (!isTetheringSupported()) {
2799 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2800 return;
2801 }
2802 mTethering.startTethering(type, receiver, showProvisioningUi);
2803 }
2804
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002805 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002806 public void stopTethering(int type) {
2807 ConnectivityManager.enforceTetherChangePermission(mContext);
2808 mTethering.stopTethering(type);
2809 }
2810
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002811 // Called when we lose the default network and have no replacement yet.
2812 // This will automatically be cleared after X seconds or a new default network
2813 // becomes CONNECTED, whichever happens first. The timer is started by the
2814 // first caller and not restarted by subsequent callers.
2815 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002816 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002817 synchronized (this) {
2818 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002819 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002820 mNetTransitionWakeLock.acquire();
2821 mNetTransitionWakeLockCausedBy = forWhom;
2822 }
2823 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002824 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002825 mNetTransitionWakeLockTimeout);
2826 return;
2827 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002828
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002829 // 100 percent is full good, 0 is full bad.
2830 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002831 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002832 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002833 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002834 }
2835
Paul Jensenbfd17b72015-04-07 12:43:13 -04002836 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002837 enforceAccessPermission();
2838 enforceInternetPermission();
2839
Paul Jensenbfd17b72015-04-07 12:43:13 -04002840 NetworkAgentInfo nai;
2841 if (network == null) {
2842 nai = getDefaultNetwork();
2843 } else {
2844 nai = getNetworkAgentInfoForNetwork(network);
2845 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002846 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2847 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2848 return;
2849 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002850 // Revalidate if the app report does not match our current validated state.
2851 if (hasConnectivity == nai.lastValidated) return;
2852 final int uid = Binder.getCallingUid();
2853 if (DBG) {
2854 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2855 ") by " + uid);
2856 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002857 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002858 // Validating a network that has not yet connected could result in a call to
2859 // rematchNetworkAndRequests() which is not meant to work on such networks.
2860 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04002861
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002862 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002863
2864 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2865 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002866 }
2867
Paul Jensencee9b512015-05-06 07:32:40 -04002868 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002869 // this information is already available as a world read/writable jvm property
2870 // so this API change wouldn't have a benifit. It also breaks the passing
2871 // of proxy info to all the JVMs.
2872 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002873 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002874 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002875 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2876 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002877 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002878 }
2879
Paul Jensencee9b512015-05-06 07:32:40 -04002880 public ProxyInfo getProxyForNetwork(Network network) {
2881 if (network == null) return getDefaultProxy();
2882 final ProxyInfo globalProxy = getGlobalProxy();
2883 if (globalProxy != null) return globalProxy;
2884 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2885 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2886 // caller may not have.
2887 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2888 if (nai == null) return null;
2889 synchronized (nai) {
2890 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2891 if (proxyInfo == null) return null;
2892 return new ProxyInfo(proxyInfo);
2893 }
2894 }
2895
Paul Jensene0bef712014-12-10 15:12:18 -05002896 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2897 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2898 // proxy is null then there is no proxy in place).
2899 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2900 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2901 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2902 proxy = null;
2903 }
2904 return proxy;
2905 }
2906
2907 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2908 // better for determining if a new proxy broadcast is necessary:
2909 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2910 // avoid unnecessary broadcasts.
2911 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2912 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2913 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2914 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2915 // all set.
2916 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2917 a = canonicalizeProxyInfo(a);
2918 b = canonicalizeProxyInfo(b);
2919 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2920 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2921 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2922 }
2923
Jason Monk207900c2014-04-25 15:00:09 -04002924 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002925 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002926
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002927 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002928 if (proxyProperties == mGlobalProxy) return;
2929 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2930 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2931
2932 String host = "";
2933 int port = 0;
2934 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002935 String pacFileUrl = "";
2936 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002937 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002938 if (!proxyProperties.isValid()) {
2939 if (DBG)
2940 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2941 return;
2942 }
Jason Monk207900c2014-04-25 15:00:09 -04002943 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002944 host = mGlobalProxy.getHost();
2945 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002946 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002947 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002948 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002949 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002950 } else {
2951 mGlobalProxy = null;
2952 }
2953 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002954 final long token = Binder.clearCallingIdentity();
2955 try {
2956 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2957 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2958 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2959 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002960 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002961 } finally {
2962 Binder.restoreCallingIdentity(token);
2963 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002964
Jason Monkcf0f97a2014-10-02 15:39:38 -04002965 if (mGlobalProxy == null) {
2966 proxyProperties = mDefaultProxy;
2967 }
2968 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002969 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002970 }
2971
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002972 private void loadGlobalProxy() {
2973 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002974 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2975 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2976 String exclList = Settings.Global.getString(res,
2977 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002978 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2979 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002980 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002981 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002982 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002983 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002984 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002985 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002986 if (!proxyProperties.isValid()) {
2987 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2988 return;
2989 }
2990
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002991 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002992 mGlobalProxy = proxyProperties;
2993 }
2994 }
2995 }
2996
Jason Monk207900c2014-04-25 15:00:09 -04002997 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002998 // this information is already available as a world read/writable jvm property
2999 // so this API change wouldn't have a benifit. It also breaks the passing
3000 // of proxy info to all the JVMs.
3001 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003002 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003003 return mGlobalProxy;
3004 }
3005 }
3006
Jason Monk207900c2014-04-25 15:00:09 -04003007 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003008 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003009 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003010 proxy = null;
3011 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003012 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003013 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003014 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003015 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003016 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3017 return;
3018 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003019
3020 // This call could be coming from the PacManager, containing the port of the local
3021 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3022 // global (to get the correct local port), and send a broadcast.
3023 // TODO: Switch PacManager to have its own message to send back rather than
3024 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003025 if ((mGlobalProxy != null) && (proxy != null)
3026 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003027 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3028 mGlobalProxy = proxy;
3029 sendProxyBroadcast(mGlobalProxy);
3030 return;
3031 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003032 mDefaultProxy = proxy;
3033
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003034 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003035 if (!mDefaultProxyDisabled) {
3036 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003037 }
3038 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003039 }
3040
Paul Jensene0bef712014-12-10 15:12:18 -05003041 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3042 // This method gets called when any network changes proxy, but the broadcast only ever contains
3043 // the default proxy (even if it hasn't changed).
3044 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3045 // world where an app might be bound to a non-default network.
3046 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3047 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3048 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3049
3050 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3051 sendProxyBroadcast(getDefaultProxy());
3052 }
3053 }
3054
Robert Greenwalt434203a2010-10-11 16:00:27 -07003055 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003056 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3057 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003058 if (!TextUtils.isEmpty(proxy)) {
3059 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003060 if (data.length == 0) {
3061 return;
3062 }
3063
Robert Greenwalt434203a2010-10-11 16:00:27 -07003064 String proxyHost = data[0];
3065 int proxyPort = 8080;
3066 if (data.length > 1) {
3067 try {
3068 proxyPort = Integer.parseInt(data[1]);
3069 } catch (NumberFormatException e) {
3070 return;
3071 }
3072 }
Jason Monk207900c2014-04-25 15:00:09 -04003073 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003074 setGlobalProxy(p);
3075 }
3076 }
3077
Jason Monk207900c2014-04-25 15:00:09 -04003078 private void sendProxyBroadcast(ProxyInfo proxy) {
3079 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003080 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003081 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003082 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003083 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3084 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003085 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003086 final long ident = Binder.clearCallingIdentity();
3087 try {
3088 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3089 } finally {
3090 Binder.restoreCallingIdentity(ident);
3091 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003092 }
3093
3094 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003095 final private HashMap<Uri, Integer> mUriEventMap;
3096 final private Context mContext;
3097 final private Handler mHandler;
3098
3099 SettingsObserver(Context context, Handler handler) {
3100 super(null);
3101 mUriEventMap = new HashMap<Uri, Integer>();
3102 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003103 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003104 }
3105
Erik Klineda4bfa82015-04-30 12:58:40 +09003106 void observe(Uri uri, int what) {
3107 mUriEventMap.put(uri, what);
3108 final ContentResolver resolver = mContext.getContentResolver();
3109 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003110 }
3111
3112 @Override
3113 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003114 Slog.wtf(TAG, "Should never be reached.");
3115 }
3116
3117 @Override
3118 public void onChange(boolean selfChange, Uri uri) {
3119 final Integer what = mUriEventMap.get(uri);
3120 if (what != null) {
3121 mHandler.obtainMessage(what.intValue()).sendToTarget();
3122 } else {
3123 loge("No matching event to send for URI=" + uri);
3124 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003125 }
3126 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003127
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003128 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003129 Slog.d(TAG, s);
3130 }
3131
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003132 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003133 Slog.e(TAG, s);
3134 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003135
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003136 private static <T> T checkNotNull(T value, String message) {
3137 if (value == null) {
3138 throw new NullPointerException(message);
3139 }
3140 return value;
3141 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003142
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003143 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003144 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003145 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3146 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3147 *
3148 * @param oldPackage Package name of the application which currently controls VPN, which will
3149 * be replaced. If there is no such application, this should should either be
3150 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3151 * @param newPackage Package name of the application which should gain control of VPN, or
3152 * {@code null} to disable.
3153 * @param userId User for whom to prepare the new VPN.
3154 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003155 * @hide
3156 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003157 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003158 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3159 int userId) {
3160 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003161 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003162
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003163 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003164 Vpn vpn = mVpns.get(userId);
3165 if (vpn != null) {
3166 return vpn.prepare(oldPackage, newPackage);
3167 } else {
3168 return false;
3169 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003170 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003171 }
3172
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003173 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003174 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3175 * This method is used by system-privileged apps.
3176 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3177 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3178 *
3179 * @param packageName The package for which authorization state should change.
3180 * @param userId User for whom {@code packageName} is installed.
3181 * @param authorized {@code true} if this app should be able to start a VPN connection without
3182 * explicit user approval, {@code false} if not.
3183 *
Jeff Davidson05542602014-08-11 14:07:27 -07003184 * @hide
3185 */
3186 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003187 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3188 enforceCrossUserPermission(userId);
3189
Jeff Davidson05542602014-08-11 14:07:27 -07003190 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003191 Vpn vpn = mVpns.get(userId);
3192 if (vpn != null) {
3193 vpn.setPackageAuthorization(packageName, authorized);
3194 }
Jeff Davidson05542602014-08-11 14:07:27 -07003195 }
3196 }
3197
3198 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003199 * Configure a TUN interface and return its file descriptor. Parameters
3200 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003201 * and not available in ConnectivityManager. Permissions are checked in
3202 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003203 * @hide
3204 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003205 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003206 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003207 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003208 int user = UserHandle.getUserId(Binder.getCallingUid());
3209 synchronized(mVpns) {
3210 return mVpns.get(user).establish(config);
3211 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003212 }
3213
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003214 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003215 * Start legacy VPN, controlling native daemons as needed. Creates a
3216 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003217 */
3218 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003219 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003220 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003221 final LinkProperties egress = getActiveLinkProperties();
3222 if (egress == null) {
3223 throw new IllegalStateException("Missing active network connection");
3224 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003225 int user = UserHandle.getUserId(Binder.getCallingUid());
3226 synchronized(mVpns) {
3227 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3228 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003229 }
3230
3231 /**
3232 * Return the information of the ongoing legacy VPN. This method is used
3233 * by VpnSettings and not available in ConnectivityManager. Permissions
3234 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003235 */
3236 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003237 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3238 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003239 if (mLockdownEnabled) {
3240 return null;
3241 }
3242
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003243 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003244 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003245 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003246 }
3247
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003248 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003249 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3250 * and not available in ConnectivityManager.
3251 */
3252 @Override
3253 public VpnInfo[] getAllVpnInfo() {
3254 enforceConnectivityInternalPermission();
3255 if (mLockdownEnabled) {
3256 return new VpnInfo[0];
3257 }
3258
3259 synchronized(mVpns) {
3260 List<VpnInfo> infoList = new ArrayList<>();
3261 for (int i = 0; i < mVpns.size(); i++) {
3262 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3263 if (info != null) {
3264 infoList.add(info);
3265 }
3266 }
3267 return infoList.toArray(new VpnInfo[infoList.size()]);
3268 }
3269 }
3270
3271 /**
3272 * @return VPN information for accounting, or null if we can't retrieve all required
3273 * information, e.g primary underlying iface.
3274 */
3275 @Nullable
3276 private VpnInfo createVpnInfo(Vpn vpn) {
3277 VpnInfo info = vpn.getVpnInfo();
3278 if (info == null) {
3279 return null;
3280 }
3281 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3282 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3283 // the underlyingNetworks list.
3284 if (underlyingNetworks == null) {
3285 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3286 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3287 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3288 }
3289 } else if (underlyingNetworks.length > 0) {
3290 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3291 if (linkProperties != null) {
3292 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3293 }
3294 }
3295 return info.primaryUnderlyingIface == null ? null : info;
3296 }
3297
3298 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003299 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3300 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003301 * Permissions are checked in Vpn class.
3302 * @hide
3303 */
3304 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003305 public VpnConfig getVpnConfig(int userId) {
3306 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003307 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003308 Vpn vpn = mVpns.get(userId);
3309 if (vpn != null) {
3310 return vpn.getVpnConfig();
3311 } else {
3312 return null;
3313 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003314 }
3315 }
3316
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003317 @Override
3318 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003319 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3320 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3321 return false;
3322 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003323
3324 // Tear down existing lockdown if profile was removed
3325 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3326 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003327 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3328 final VpnProfile profile = VpnProfile.decode(
3329 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003330 if (profile == null) {
3331 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3332 setLockdownTracker(null);
3333 return true;
3334 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003335 int user = UserHandle.getUserId(Binder.getCallingUid());
3336 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003337 Vpn vpn = mVpns.get(user);
3338 if (vpn == null) {
3339 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3340 return false;
3341 }
3342 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003343 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003344 } else {
3345 setLockdownTracker(null);
3346 }
3347
3348 return true;
3349 }
3350
3351 /**
3352 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3353 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3354 */
3355 private void setLockdownTracker(LockdownVpnTracker tracker) {
3356 // Shutdown any existing tracker
3357 final LockdownVpnTracker existing = mLockdownTracker;
3358 mLockdownTracker = null;
3359 if (existing != null) {
3360 existing.shutdown();
3361 }
3362
3363 try {
3364 if (tracker != null) {
3365 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003366 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003367 mLockdownTracker = tracker;
3368 mLockdownTracker.init();
3369 } else {
3370 mNetd.setFirewallEnabled(false);
3371 }
3372 } catch (RemoteException e) {
3373 // ignored; NMS lives inside system_server
3374 }
3375 }
3376
3377 private void throwIfLockdownEnabled() {
3378 if (mLockdownEnabled) {
3379 throw new IllegalStateException("Unavailable in lockdown mode");
3380 }
3381 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003382
Robin Lee244ce8e2016-01-05 18:03:46 +00003383 /**
Robin Lee17e61832016-05-09 13:46:28 +01003384 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3385 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003386 *
Robin Lee17e61832016-05-09 13:46:28 +01003387 * @return {@code true} if the service was started, the service was already connected, or there
3388 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003389 */
Robin Lee17e61832016-05-09 13:46:28 +01003390 private boolean startAlwaysOnVpn(int userId) {
3391 final String alwaysOnPackage;
3392 synchronized (mVpns) {
3393 Vpn vpn = mVpns.get(userId);
3394 if (vpn == null) {
3395 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3396 // exists already.
3397 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3398 return false;
3399 }
3400 alwaysOnPackage = vpn.getAlwaysOnPackage();
3401 // Skip if there is no service to start.
3402 if (alwaysOnPackage == null) {
3403 return true;
3404 }
3405 // Skip if the service is already established. This isn't bulletproof: it's not bound
3406 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
3407 // which may restart the connection.
3408 if (vpn.getNetworkInfo().isConnected()) {
3409 return true;
3410 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003411 }
3412
Robin Lee17e61832016-05-09 13:46:28 +01003413 // Start the VPN service declared in the app's manifest.
Robin Lee244ce8e2016-01-05 18:03:46 +00003414 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
Robin Lee17e61832016-05-09 13:46:28 +01003415 serviceIntent.setPackage(alwaysOnPackage);
Robin Lee244ce8e2016-01-05 18:03:46 +00003416 try {
Robin Lee17e61832016-05-09 13:46:28 +01003417 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(userId)) != null;
Robin Lee244ce8e2016-01-05 18:03:46 +00003418 } catch (RuntimeException e) {
Robin Lee17e61832016-05-09 13:46:28 +01003419 Slog.w(TAG, "VpnService " + serviceIntent + " failed to start", e);
Robin Lee244ce8e2016-01-05 18:03:46 +00003420 return false;
3421 }
3422 }
3423
3424 @Override
Robin Leedc679712016-05-03 13:23:03 +01003425 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003426 enforceConnectivityInternalPermission();
3427 enforceCrossUserPermission(userId);
3428
3429 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3430 if (LockdownVpnTracker.isEnabled()) {
3431 return false;
3432 }
3433
Robin Lee244ce8e2016-01-05 18:03:46 +00003434 synchronized (mVpns) {
3435 Vpn vpn = mVpns.get(userId);
3436 if (vpn == null) {
3437 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3438 return false;
3439 }
Robin Lee17e61832016-05-09 13:46:28 +01003440 // If the current VPN package is the same as the new one, this is a no-op
3441 if (TextUtils.equals(packageName, vpn.getAlwaysOnPackage())) {
3442 return true;
3443 }
3444 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003445 return false;
3446 }
Robin Lee17e61832016-05-09 13:46:28 +01003447 if (!startAlwaysOnVpn(userId)) {
3448 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003449 return false;
3450 }
Robin Lee17e61832016-05-09 13:46:28 +01003451
3452 // Save the configuration
3453 final long token = Binder.clearCallingIdentity();
3454 try {
3455 final ContentResolver cr = mContext.getContentResolver();
3456 Settings.Secure.putStringForUser(cr, Settings.Secure.ALWAYS_ON_VPN_APP,
3457 packageName, userId);
3458 Settings.Secure.putIntForUser(cr, Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
3459 (lockdown ? 1 : 0), userId);
3460 } finally {
3461 Binder.restoreCallingIdentity(token);
3462 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003463 }
3464 return true;
3465 }
3466
3467 @Override
3468 public String getAlwaysOnVpnPackage(int userId) {
3469 enforceConnectivityInternalPermission();
3470 enforceCrossUserPermission(userId);
3471
3472 synchronized (mVpns) {
3473 Vpn vpn = mVpns.get(userId);
3474 if (vpn == null) {
3475 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3476 return null;
3477 }
3478 return vpn.getAlwaysOnPackage();
3479 }
3480 }
3481
Wink Savilleab9321d2013-06-29 21:10:57 -07003482 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003483 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003484 // TODO: Remove? Any reason to trigger a provisioning check?
3485 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003486 }
3487
3488 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003489 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003490
Paul Jensen89e0f092014-09-15 15:59:36 -04003491 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003492 Intent intent = new Intent(action);
3493 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003494 // Concatenate the range of types onto the range of NetIDs.
3495 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003496 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003497 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003498 }
3499
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003500 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003501 * Show or hide network provisioning notifications.
3502 *
3503 * We use notifications for two purposes: to notify that a network requires sign in
3504 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3505 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3506 * particular network we can display the notification type that was most recently requested.
3507 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3508 * might first display NO_INTERNET, and then when the captive portal check completes, display
3509 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003510 *
3511 * @param id an identifier that uniquely identifies this notification. This must match
3512 * between show and hide calls. We use the NetID value but for legacy callers
3513 * we concatenate the range of types with the range of NetIDs.
3514 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003515 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003516 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3517 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003518 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003519 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3520 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003521 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003522 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003523
3524 Resources r = Resources.getSystem();
3525 NotificationManager notificationManager = (NotificationManager) mContext
3526 .getSystemService(Context.NOTIFICATION_SERVICE);
3527
3528 if (visible) {
3529 CharSequence title;
3530 CharSequence details;
3531 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003532 if (notifyType == NotificationType.NO_INTERNET &&
3533 networkType == ConnectivityManager.TYPE_WIFI) {
3534 title = r.getString(R.string.wifi_no_internet, 0);
3535 details = r.getString(R.string.wifi_no_internet_detailed);
3536 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3537 } else if (notifyType == NotificationType.SIGN_IN) {
3538 switch (networkType) {
3539 case ConnectivityManager.TYPE_WIFI:
3540 title = r.getString(R.string.wifi_available_sign_in, 0);
3541 details = r.getString(R.string.network_available_sign_in_detailed,
3542 extraInfo);
3543 icon = R.drawable.stat_notify_wifi_in_range;
3544 break;
3545 case ConnectivityManager.TYPE_MOBILE:
3546 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3547 title = r.getString(R.string.network_available_sign_in, 0);
3548 // TODO: Change this to pull from NetworkInfo once a printable
3549 // name has been added to it
3550 details = mTelephonyManager.getNetworkOperatorName();
3551 icon = R.drawable.stat_notify_rssi_in_range;
3552 break;
3553 default:
3554 title = r.getString(R.string.network_available_sign_in, 0);
3555 details = r.getString(R.string.network_available_sign_in_detailed,
3556 extraInfo);
3557 icon = R.drawable.stat_notify_rssi_in_range;
3558 break;
3559 }
3560 } else {
3561 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3562 + getNetworkTypeName(networkType));
3563 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003564 }
3565
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003566 Notification notification = new Notification.Builder(mContext)
3567 .setWhen(0)
3568 .setSmallIcon(icon)
3569 .setAutoCancel(true)
3570 .setTicker(title)
3571 .setColor(mContext.getColor(
3572 com.android.internal.R.color.system_notification_accent_color))
3573 .setContentTitle(title)
3574 .setContentText(details)
3575 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003576 .setLocalOnly(true)
3577 .setPriority(highPriority ?
3578 Notification.PRIORITY_HIGH :
3579 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003580 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003581 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003582 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003583
Wink Saville948282b2013-08-29 08:55:16 -07003584 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003585 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003586 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003587 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003588 npe.printStackTrace();
3589 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003590 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003591 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003592 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003593 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003594 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003595 npe.printStackTrace();
3596 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003597 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003598 }
3599
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003600 /** Location to an updatable file listing carrier provisioning urls.
3601 * An example:
3602 *
3603 * <?xml version="1.0" encoding="utf-8"?>
3604 * <provisioningUrls>
3605 * <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 -07003606 * </provisioningUrls>
3607 */
3608 private static final String PROVISIONING_URL_PATH =
3609 "/data/misc/radio/provisioning_urls.xml";
3610 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003611
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003612 /** XML tag for root element. */
3613 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3614 /** XML tag for individual url */
3615 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003616 /** XML attribute for mcc */
3617 private static final String ATTR_MCC = "mcc";
3618 /** XML attribute for mnc */
3619 private static final String ATTR_MNC = "mnc";
3620
Paul Jensen434dde82015-06-11 09:43:30 -04003621 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003622 FileReader fileReader = null;
3623 XmlPullParser parser = null;
3624 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003625
3626 try {
3627 fileReader = new FileReader(mProvisioningUrlFile);
3628 parser = Xml.newPullParser();
3629 parser.setInput(fileReader);
3630 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3631
3632 while (true) {
3633 XmlUtils.nextElement(parser);
3634
3635 String element = parser.getName();
3636 if (element == null) break;
3637
Paul Jensen434dde82015-06-11 09:43:30 -04003638 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003639 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3640 try {
3641 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3642 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3643 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3644 parser.next();
3645 if (parser.getEventType() == XmlPullParser.TEXT) {
3646 return parser.getText();
3647 }
3648 }
3649 }
3650 } catch (NumberFormatException e) {
3651 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3652 }
3653 }
3654 }
3655 return null;
3656 } catch (FileNotFoundException e) {
3657 loge("Carrier Provisioning Urls file not found");
3658 } catch (XmlPullParserException e) {
3659 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3660 } catch (IOException e) {
3661 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3662 } finally {
3663 if (fileReader != null) {
3664 try {
3665 fileReader.close();
3666 } catch (IOException e) {}
3667 }
3668 }
3669 return null;
3670 }
3671
Wink Saville42d4f082013-07-20 20:31:59 -07003672 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003673 public String getMobileProvisioningUrl() {
3674 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003675 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003676 if (TextUtils.isEmpty(url)) {
3677 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003678 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003679 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003680 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003681 }
Wink Saville8cf35602013-07-10 23:00:07 -07003682 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003683 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003684 String phoneNumber = mTelephonyManager.getLine1Number();
3685 if (TextUtils.isEmpty(phoneNumber)) {
3686 phoneNumber = "0000000000";
3687 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003688 url = String.format(url,
3689 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3690 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003691 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003692 }
3693
Wink Savilleab9321d2013-06-29 21:10:57 -07003694 return url;
3695 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003696
Wink Saville948282b2013-08-29 08:55:16 -07003697 @Override
3698 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003699 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003700 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003701 final long ident = Binder.clearCallingIdentity();
3702 try {
3703 setProvNotificationVisible(visible, networkType, action);
3704 } finally {
3705 Binder.restoreCallingIdentity(ident);
3706 }
Wink Saville948282b2013-08-29 08:55:16 -07003707 }
Wink Saville7788c612013-08-29 14:57:08 -07003708
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003709 @Override
3710 public void setAirplaneMode(boolean enable) {
3711 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003712 final long ident = Binder.clearCallingIdentity();
3713 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003714 final ContentResolver cr = mContext.getContentResolver();
3715 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3716 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3717 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003718 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003719 } finally {
3720 Binder.restoreCallingIdentity(ident);
3721 }
3722 }
3723
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003724 private void onUserStart(int userId) {
3725 synchronized(mVpns) {
3726 Vpn userVpn = mVpns.get(userId);
3727 if (userVpn != null) {
3728 loge("Starting user already has a VPN");
3729 return;
3730 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003731 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003732 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003733
3734 final ContentResolver cr = mContext.getContentResolver();
3735 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3736 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3737 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3738 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3739 if (alwaysOnPackage != null) {
3740 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3741 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003742 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003743 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3744 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003745 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003746 }
3747
3748 private void onUserStop(int userId) {
3749 synchronized(mVpns) {
3750 Vpn userVpn = mVpns.get(userId);
3751 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003752 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003753 return;
3754 }
Robin Lee17e61832016-05-09 13:46:28 +01003755 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003756 mVpns.delete(userId);
3757 }
3758 }
3759
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003760 private void onUserAdded(int userId) {
3761 synchronized(mVpns) {
3762 final int vpnsSize = mVpns.size();
3763 for (int i = 0; i < vpnsSize; i++) {
3764 Vpn vpn = mVpns.valueAt(i);
3765 vpn.onUserAdded(userId);
3766 }
3767 }
3768 }
3769
3770 private void onUserRemoved(int userId) {
3771 synchronized(mVpns) {
3772 final int vpnsSize = mVpns.size();
3773 for (int i = 0; i < vpnsSize; i++) {
3774 Vpn vpn = mVpns.valueAt(i);
3775 vpn.onUserRemoved(userId);
3776 }
3777 }
3778 }
3779
Robin Lee89e7a692016-02-29 14:38:17 +00003780 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003781 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3782 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3783 updateLockdownVpn();
3784 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003785 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003786 }
3787 }
3788
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003789 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3790 @Override
3791 public void onReceive(Context context, Intent intent) {
3792 final String action = intent.getAction();
3793 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3794 if (userId == UserHandle.USER_NULL) return;
3795
Robin Lee323f29d2016-05-04 16:38:06 +01003796 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003797 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003798 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003799 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003800 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3801 onUserAdded(userId);
3802 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3803 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003804 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3805 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003806 }
3807 }
3808 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003809
Robert Greenwalta67be032014-05-16 15:49:14 -07003810 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3811 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003812 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3813 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003814
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003815 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3816 // Map from UID to number of NetworkRequests that UID has filed.
3817 @GuardedBy("mUidToNetworkRequestCount")
3818 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3819
Robert Greenwalta67be032014-05-16 15:49:14 -07003820 private static class NetworkFactoryInfo {
3821 public final String name;
3822 public final Messenger messenger;
3823 public final AsyncChannel asyncChannel;
3824
3825 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3826 this.name = name;
3827 this.messenger = messenger;
3828 this.asyncChannel = asyncChannel;
3829 }
3830 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003831
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003832 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003833 * A NetworkRequest as registered by an application can be one of three
3834 * types:
3835 *
3836 * - "listen", for which the framework will issue callbacks about any
3837 * and all networks that match the specified NetworkCapabilities,
3838 *
3839 * - "request", capable of causing a specific network to be created
3840 * first (e.g. a telephony DUN request), the framework will issue
3841 * callbacks about the single, highest scoring current network
3842 * (if any) that matches the specified NetworkCapabilities, or
3843 *
3844 * - "track the default network", a hybrid of the two designed such
3845 * that the framework will issue callbacks for the single, highest
3846 * scoring current network (if any) that matches the capabilities of
3847 * the default Internet request (mDefaultRequest), but which cannot
3848 * cause the framework to either create or retain the existence of
3849 * any specific network.
3850 *
3851 */
3852 private static enum NetworkRequestType {
3853 LISTEN,
3854 TRACK_DEFAULT,
3855 REQUEST
3856 };
3857
3858 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003859 * Tracks info about the requester.
3860 * Also used to notice when the calling process dies so we can self-expire
3861 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003862 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003863 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003864 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003865 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003866 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003867 final int mPid;
3868 final int mUid;
3869 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003870 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003871
Erik Kline371c7b72016-03-22 17:04:20 +09003872 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003873 request = r;
3874 mPendingIntent = pi;
3875 messenger = null;
3876 mBinder = null;
3877 mPid = getCallingPid();
3878 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003879 mType = type;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003880 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003881 }
3882
Erik Kline371c7b72016-03-22 17:04:20 +09003883 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003884 super();
3885 messenger = m;
3886 request = r;
3887 mBinder = binder;
3888 mPid = getCallingPid();
3889 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003890 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003891 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003892 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003893
3894 try {
3895 mBinder.linkToDeath(this, 0);
3896 } catch (RemoteException e) {
3897 binderDied();
3898 }
3899 }
3900
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003901 private void enforceRequestCountLimit() {
3902 synchronized (mUidToNetworkRequestCount) {
3903 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3904 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3905 throw new IllegalArgumentException("Too many NetworkRequests filed");
3906 }
3907 mUidToNetworkRequestCount.put(mUid, networkRequests);
3908 }
3909 }
3910
Erik Kline371c7b72016-03-22 17:04:20 +09003911 private String typeString() {
3912 switch (mType) {
3913 case LISTEN: return "Listen";
3914 case REQUEST: return "Request";
3915 case TRACK_DEFAULT: return "Track default";
3916 default:
3917 return "unknown type";
3918 }
3919 }
3920
Robert Greenwalt9258c642014-03-26 16:47:06 -07003921 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003922 if (mBinder != null) {
3923 mBinder.unlinkToDeath(this, 0);
3924 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003925 }
3926
3927 public void binderDied() {
3928 log("ConnectivityService NetworkRequestInfo binderDied(" +
3929 request + ", " + mBinder + ")");
3930 releaseNetworkRequest(request);
3931 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003932
Erik Kline371c7b72016-03-22 17:04:20 +09003933 /**
3934 * Returns true iff. the contained NetworkRequest is one that:
3935 *
3936 * - should be associated with at most one satisfying network
3937 * at a time;
3938 *
3939 * - should cause a network to be kept up if it is the only network
3940 * which can satisfy the NetworkReqeust.
3941 *
3942 * For full detail of how isRequest() is used for pairing Networks with
3943 * NetworkRequests read rematchNetworkAndRequests().
3944 *
3945 * TODO: Rename to something more properly descriptive.
3946 */
3947 public boolean isRequest() {
3948 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3949 (mType == NetworkRequestType.REQUEST);
3950 }
3951
Robert Greenwalta67be032014-05-16 15:49:14 -07003952 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003953 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003954 " from uid/pid:" + mUid + "/" + mPid +
3955 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003956 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003957 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003958 }
3959
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003960 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3961 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3962 if (badCapability != null) {
3963 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003964 }
3965 }
3966
Erik Kline9d598e12015-07-13 16:37:51 +09003967 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003968 final SortedSet<Integer> thresholds = new TreeSet();
3969 synchronized (nai) {
3970 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3971 if (nri.request.networkCapabilities.hasSignalStrength() &&
3972 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3973 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3974 }
3975 }
3976 }
Erik Kline9d598e12015-07-13 16:37:51 +09003977 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003978 }
3979
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003980 private void updateSignalStrengthThresholds(
3981 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3982 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003983 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003984 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3985
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003986 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003987 String detail;
3988 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3989 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3990 } else {
3991 detail = reason;
3992 }
3993 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3994 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3995 }
3996
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003997 nai.asyncChannel.sendMessage(
3998 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003999 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004000 }
4001
Robert Greenwalt9258c642014-03-26 16:47:06 -07004002 @Override
4003 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004004 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09004005 final NetworkRequestType type = (networkCapabilities == null)
4006 ? NetworkRequestType.TRACK_DEFAULT
4007 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004008 // If the requested networkCapabilities is null, take them instead from
4009 // the default network request. This allows callers to keep track of
4010 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09004011 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004012 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4013 enforceAccessPermission();
4014 } else {
4015 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4016 enforceNetworkRequestPermissions(networkCapabilities);
4017 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004018 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004019 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004020
Robert Greenwalt6078b502014-06-11 16:05:07 -07004021 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004022 throw new IllegalArgumentException("Bad timeout specified");
4023 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004024
Etan Cohenddb9ef02015-11-18 10:56:15 -08004025 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4026 .equals(networkCapabilities.getNetworkSpecifier())) {
4027 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4028 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4029 }
4030
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004031 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
4032 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09004033 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09004034 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004035
4036 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004037 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004038 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004039 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004040 }
4041 return networkRequest;
4042 }
4043
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004044 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004045 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004046 enforceConnectivityInternalPermission();
4047 } else {
4048 enforceChangePermission();
4049 }
4050 }
4051
fenglub15e72b2015-03-20 11:29:56 -07004052 @Override
fengludb571472015-04-21 17:12:05 -07004053 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004054 enforceAccessPermission();
4055 NetworkAgentInfo nai = null;
4056 if (network == null) {
4057 return false;
4058 }
4059 synchronized (mNetworkForNetId) {
4060 nai = mNetworkForNetId.get(network.netId);
4061 }
4062 if (nai != null) {
4063 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4064 return true;
4065 }
4066 return false;
4067 }
4068
4069
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004070 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
4071 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004072 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004073 final int uidRules;
4074 final int uid = Binder.getCallingUid();
4075 synchronized(mRulesLock) {
4076 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4077 }
Felipe Lemed31a97f2016-05-06 14:53:50 -07004078 if ((uidRules & RULE_ALLOW_ALL) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004079 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004080 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004081 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004082 }
4083 }
4084 }
4085
Robert Greenwalt9258c642014-03-26 16:47:06 -07004086 @Override
4087 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4088 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004089 checkNotNull(operation, "PendingIntent cannot be null.");
4090 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4091 enforceNetworkRequestPermissions(networkCapabilities);
4092 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004093 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004094
4095 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
4096 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004097 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004098 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09004099 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004100 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4101 nri));
4102 return networkRequest;
4103 }
4104
Jeremy Joslin79294842014-12-03 17:15:28 -08004105 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4106 mHandler.sendMessageDelayed(
4107 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4108 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4109 }
4110
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004111 @Override
4112 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004113 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004114 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4115 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004116 }
4117
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004118 // In order to implement the compatibility measure for pre-M apps that call
4119 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4120 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4121 // This ensures it has permission to do so.
4122 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4123 if (nc == null) {
4124 return false;
4125 }
4126 int[] transportTypes = nc.getTransportTypes();
4127 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4128 return false;
4129 }
4130 try {
4131 mContext.enforceCallingOrSelfPermission(
4132 android.Manifest.permission.ACCESS_WIFI_STATE,
4133 "ConnectivityService");
4134 } catch (SecurityException e) {
4135 return false;
4136 }
4137 return true;
4138 }
4139
Robert Greenwalt9258c642014-03-26 16:47:06 -07004140 @Override
4141 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4142 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004143 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4144 enforceAccessPermission();
4145 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004146
Erik Kline7523eb32015-07-09 18:24:03 +09004147 NetworkRequest networkRequest = new NetworkRequest(
4148 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004149 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09004150 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004151 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004152
4153 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4154 return networkRequest;
4155 }
4156
4157 @Override
4158 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4159 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004160 checkNotNull(operation, "PendingIntent cannot be null.");
4161 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4162 enforceAccessPermission();
4163 }
4164
Erik Kline7523eb32015-07-09 18:24:03 +09004165 NetworkRequest networkRequest = new NetworkRequest(
4166 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004167 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004168 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004169 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004170
4171 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004172 }
4173
4174 @Override
4175 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004176 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4177 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004178 }
4179
4180 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004181 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004182 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004183 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4184 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004185 }
4186
Robert Greenwalta67be032014-05-16 15:49:14 -07004187 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004188 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004189 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4190 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4191 }
4192
4193 @Override
4194 public void unregisterNetworkFactory(Messenger messenger) {
4195 enforceConnectivityInternalPermission();
4196 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4197 }
4198
4199 private void handleUnregisterNetworkFactory(Messenger messenger) {
4200 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4201 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004202 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004203 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004204 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004205 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004206 }
4207
Robert Greenwalt7b816022014-04-18 15:25:25 -07004208 /**
4209 * NetworkAgentInfo supporting a request by requestId.
4210 * These have already been vetted (their Capabilities satisfy the request)
4211 * and the are the highest scored network available.
4212 * the are keyed off the Requests requestId.
4213 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004214 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004215 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4216 new SparseArray<NetworkAgentInfo>();
4217
Paul Jensen31a94f42015-02-13 14:18:39 -05004218 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4219 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004220 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4221 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004222 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4223 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4224 // there may not be a strict 1:1 correlation between the two.
4225 @GuardedBy("mNetworkForNetId")
4226 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004227
Robert Greenwalt7b816022014-04-18 15:25:25 -07004228 // NetworkAgentInfo keyed off its connecting messenger
4229 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004230 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004231 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4232 new HashMap<Messenger, NetworkAgentInfo>();
4233
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004234 @GuardedBy("mBlockedAppUids")
4235 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4236
Paul Jensen2c311d62014-11-17 12:34:51 -05004237 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004238 private final NetworkRequest mDefaultRequest;
4239
Erik Klineda4bfa82015-04-30 12:58:40 +09004240 // Request used to optionally keep mobile data active even when higher
4241 // priority networks like Wi-Fi are active.
4242 private final NetworkRequest mDefaultMobileDataRequest;
4243
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004244 private NetworkAgentInfo getDefaultNetwork() {
4245 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4246 }
4247
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004248 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004249 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004250 }
4251
Paul Jensen31a94f42015-02-13 14:18:39 -05004252 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004253 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004254 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004255 enforceConnectivityInternalPermission();
4256
Paul Jensen2c311d62014-11-17 12:34:51 -05004257 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4258 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004259 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004260 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4261 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004262 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004263 synchronized (this) {
4264 nai.networkMonitor.systemReady = mSystemReady;
4265 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004266 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004267 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004268 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004269 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004270 }
4271
4272 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4273 if (VDBG) log("Got NetworkAgent Messenger");
4274 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004275 synchronized (mNetworkForNetId) {
4276 mNetworkForNetId.put(na.network.netId, na);
4277 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004278 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4279 NetworkInfo networkInfo = na.networkInfo;
4280 na.networkInfo = null;
4281 updateNetworkInfo(na, networkInfo);
4282 }
4283
4284 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4285 LinkProperties newLp = networkAgent.linkProperties;
4286 int netId = networkAgent.network.netId;
4287
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004288 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4289 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004290 if (networkAgent.clatd != null) {
4291 networkAgent.clatd.fixupLinkProperties(oldLp);
4292 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004293
Paul Jensen992f2522014-04-28 10:33:11 -04004294 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004295 updateMtu(newLp, oldLp);
4296 // TODO - figure out what to do for clat
4297// for (LinkProperties lp : newLp.getStackedLinks()) {
4298// updateMtu(lp, null);
4299// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004300 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004301
Erik Kline94887872016-04-05 13:30:49 +09004302 updateRoutes(newLp, oldLp, netId);
4303 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004304
Paul Jensen3b759822014-05-13 11:44:01 -04004305 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004306 if (isDefaultNetwork(networkAgent)) {
4307 handleApplyDefaultProxy(newLp.getHttpProxy());
4308 } else {
4309 updateProxy(newLp, oldLp, networkAgent);
4310 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004311 // TODO - move this check to cover the whole function
4312 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004313 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004314 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4315 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004316
4317 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004318 }
4319
Lorenzo Colitti95439462014-10-09 13:44:48 +09004320 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4321 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4322 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004323
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004324 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004325 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4326 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004327 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004328 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004329 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004330 }
Paul Jensen992f2522014-04-28 10:33:11 -04004331
4332 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4333 CompareResult<String> interfaceDiff = new CompareResult<String>();
4334 if (oldLp != null) {
4335 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4336 } else if (newLp != null) {
4337 interfaceDiff.added = newLp.getAllInterfaceNames();
4338 }
4339 for (String iface : interfaceDiff.added) {
4340 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004341 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004342 mNetd.addInterfaceToNetwork(iface, netId);
4343 } catch (Exception e) {
4344 loge("Exception adding interface: " + e);
4345 }
4346 }
4347 for (String iface : interfaceDiff.removed) {
4348 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004349 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004350 mNetd.removeInterfaceFromNetwork(iface, netId);
4351 } catch (Exception e) {
4352 loge("Exception removing interface: " + e);
4353 }
4354 }
4355 }
4356
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004357 /**
4358 * Have netd update routes from oldLp to newLp.
4359 * @return true if routes changed between oldLp and newLp
4360 */
4361 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004362 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4363 if (oldLp != null) {
4364 routeDiff = oldLp.compareAllRoutes(newLp);
4365 } else if (newLp != null) {
4366 routeDiff.added = newLp.getAllRoutes();
4367 }
4368
4369 // add routes before removing old in case it helps with continuous connectivity
4370
4371 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4372 for (RouteInfo route : routeDiff.added) {
4373 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004374 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004375 try {
4376 mNetd.addRoute(netId, route);
4377 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004378 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4379 loge("Exception in addRoute for non-gateway: " + e);
4380 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004381 }
4382 }
4383 for (RouteInfo route : routeDiff.added) {
4384 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004385 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004386 try {
4387 mNetd.addRoute(netId, route);
4388 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004389 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4390 loge("Exception in addRoute for gateway: " + e);
4391 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004392 }
4393 }
4394
4395 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004396 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004397 try {
4398 mNetd.removeRoute(netId, route);
4399 } catch (Exception e) {
4400 loge("Exception in removeRoute: " + e);
4401 }
4402 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004403 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004404 }
Erik Kline41368502015-06-17 13:19:54 +09004405
Erik Kline94887872016-04-05 13:30:49 +09004406 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4407 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4408 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004409 }
Erik Kline94887872016-04-05 13:30:49 +09004410
4411 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004412 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004413 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004414 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004415 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4416 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004417 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004418 }
4419 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4420 if (defaultNai != null && defaultNai.network.netId == netId) {
4421 setDefaultDnsSystemProperties(dnses);
4422 }
4423 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004424 }
4425
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004426 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4427 int last = 0;
4428 for (InetAddress dns : dnses) {
4429 ++last;
4430 String key = "net.dns" + last;
4431 String value = dns.getHostAddress();
4432 SystemProperties.set(key, value);
4433 }
4434 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4435 String key = "net.dns" + i;
4436 SystemProperties.set(key, "");
4437 }
4438 mNumDnsEntries = last;
4439 }
4440
Paul Jensen3d194ea2015-06-16 14:27:36 -04004441 /**
4442 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4443 * augmented with any stateful capabilities implied from {@code networkAgent}
4444 * (e.g., validated status and captive portal status).
4445 *
Paul Jensene0988542015-06-25 15:30:08 -04004446 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004447 * @param networkCapabilities the new network capabilities.
4448 */
Paul Jensene0988542015-06-25 15:30:08 -04004449 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004450 // Don't modify caller's NetworkCapabilities.
4451 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004452 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004453 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4454 } else {
4455 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4456 }
Paul Jensene0988542015-06-25 15:30:08 -04004457 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004458 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4459 } else {
4460 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4461 }
Paul Jensene0988542015-06-25 15:30:08 -04004462 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4463 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004464 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4465 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4466 try {
4467 mNetd.setNetworkPermission(nai.network.netId,
4468 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4469 null : NetworkManagementService.PERMISSION_SYSTEM);
4470 } catch (RemoteException e) {
4471 loge("Exception in setNetworkPermission: " + e);
4472 }
4473 }
Paul Jensene0988542015-06-25 15:30:08 -04004474 synchronized (nai) {
4475 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004476 }
Paul Jensene0988542015-06-25 15:30:08 -04004477 rematchAllNetworksAndRequests(nai, oldScore);
4478 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004479 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004480 }
4481
Paul Jensenc8b9a742014-09-30 15:37:41 -04004482 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4483 for (int i = 0; i < nai.networkRequests.size(); i++) {
4484 NetworkRequest nr = nai.networkRequests.valueAt(i);
4485 // Don't send listening requests to factories. b/17393458
4486 if (!isRequest(nr)) continue;
4487 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4488 }
4489 }
4490
Robert Greenwalt7b816022014-04-18 15:25:25 -07004491 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4492 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004493 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004494 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4495 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004496 }
4497 }
4498
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004499 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4500 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004501 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004502 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004503 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4504 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004505 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004506 sendIntent(nri.mPendingIntent, intent);
4507 }
4508 // else not handled
4509 }
4510
4511 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4512 mPendingIntentWakeLock.acquire();
4513 try {
4514 if (DBG) log("Sending " + pendingIntent);
4515 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4516 } catch (PendingIntent.CanceledException e) {
4517 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4518 mPendingIntentWakeLock.release();
4519 releasePendingNetworkRequest(pendingIntent);
4520 }
4521 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4522 }
4523
4524 @Override
4525 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4526 String resultData, Bundle resultExtras) {
4527 if (DBG) log("Finished sending " + pendingIntent);
4528 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004529 // Release with a delay so the receiving client has an opportunity to put in its
4530 // own request.
4531 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004532 }
4533
Robert Greenwalt9258c642014-03-26 16:47:06 -07004534 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004535 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004536 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004537 Bundle bundle = new Bundle();
4538 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4539 new NetworkRequest(nri.request));
4540 Message msg = Message.obtain();
4541 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4542 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4543 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4544 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004545 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004546 case ConnectivityManager.CALLBACK_LOSING: {
4547 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4548 break;
4549 }
4550 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4551 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4552 new NetworkCapabilities(networkAgent.networkCapabilities));
4553 break;
4554 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004555 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004556 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4557 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004558 break;
4559 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004560 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004561 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004562 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004563 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004564 if (VDBG) {
4565 log("sending notification " + notifyTypeToName(notificationType) +
4566 " for " + nri.request);
4567 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004568 nri.messenger.send(msg);
4569 } catch (RemoteException e) {
4570 // may occur naturally in the race of binder death.
4571 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4572 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004573 }
4574
Paul Jensenc8b9a742014-09-30 15:37:41 -04004575 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4576 for (int i = 0; i < nai.networkRequests.size(); i++) {
4577 NetworkRequest nr = nai.networkRequests.valueAt(i);
4578 // Ignore listening requests.
4579 if (!isRequest(nr)) continue;
4580 loge("Dead network still had at least " + nr);
4581 break;
4582 }
4583 nai.asyncChannel.disconnect();
4584 }
4585
Robert Greenwalt7b816022014-04-18 15:25:25 -07004586 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4587 if (oldNetwork == null) {
4588 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4589 return;
4590 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004591 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4592 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004593 }
4594
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004595 private void makeDefault(NetworkAgentInfo newNetwork, NetworkAgentInfo prevNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004596 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004597 setupDataActivityTracking(newNetwork);
4598 try {
4599 mNetd.setDefaultNetId(newNetwork.network.netId);
4600 } catch (Exception e) {
4601 loge("Exception setting default network :" + e);
4602 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004603 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004604 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004605 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004606 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Hugo Benichi5f16f762016-04-20 12:09:33 +09004607 logDefaultNetworkEvent(newNetwork, prevNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004608 }
4609
Paul Jensen2161a8e2014-09-11 11:00:39 -04004610 // Handles a network appearing or improving its score.
4611 //
4612 // - Evaluates all current NetworkRequests that can be
4613 // satisfied by newNetwork, and reassigns to newNetwork
4614 // any such requests for which newNetwork is the best.
4615 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004616 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004617 // needed. A network is needed if it is the best network for
4618 // one or more NetworkRequests, or if it is a VPN.
4619 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004620 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004621 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004622 //
4623 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4624 // networks that have no chance (i.e. even if validated)
4625 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004626 //
4627 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4628 // it does not remove NetworkRequests that other Networks could better satisfy.
4629 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4630 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4631 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004632 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004633 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004634 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4635 // performed to tear down unvalidated networks that have no chance (i.e. even if
4636 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004637 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004638 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Robin Lee585e2482016-05-01 23:00:00 +01004639 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004640 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004641 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004642 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004643 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004644 // Find and migrate to this Network any NetworkRequests for
4645 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004646 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004647 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004648 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004649 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004650 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4651 final boolean satisfies = newNetwork.satisfies(nri.request);
4652 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004653 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004654 log("Network " + newNetwork.name() + " was already satisfying" +
4655 " request " + nri.request.requestId + ". No change.");
4656 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004657 keep = true;
4658 continue;
4659 }
4660
4661 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004662 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004663 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004664 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004665 // This is not a request, it's a callback listener.
4666 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004667 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004668 continue;
4669 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004670
Robert Greenwalt7b816022014-04-18 15:25:25 -07004671 // next check if it's better than any current network we're using for
4672 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004673 if (VDBG) {
4674 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004675 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4676 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004677 }
4678 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004679 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004680 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004681 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004682 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004683 currentNetwork.networkRequests.remove(nri.request.requestId);
4684 currentNetwork.networkLingered.add(nri.request);
4685 affectedNetworks.add(currentNetwork);
4686 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004687 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004688 }
Paul Jensen573a0352015-01-08 10:49:34 -05004689 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004690 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004691 if (!newNetwork.addRequest(nri.request)) {
4692 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4693 }
4694 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004695 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004696 // Tell NetworkFactories about the new score, so they can stop
4697 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004698 // TODO - this could get expensive if we have alot of requests for this
4699 // network. Think about if there is a way to reduce this. Push
4700 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004701 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004702 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004703 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004704 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004705 }
4706 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004707 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4708 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4709 // mark it as no longer satisfying "nri". Because networks are processed by
4710 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4711 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4712 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4713 // This means this code doesn't have to handle the case where "currentNetwork" no
4714 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4715 if (DBG) {
4716 log("Network " + newNetwork.name() + " stopped satisfying" +
4717 " request " + nri.request.requestId);
4718 }
4719 newNetwork.networkRequests.remove(nri.request.requestId);
4720 if (currentNetwork == newNetwork) {
4721 mNetworkForRequestId.remove(nri.request.requestId);
4722 sendUpdatedScoreToFactories(nri.request, 0);
4723 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004724 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004725 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4726 newNetwork.name() +
4727 " without updating mNetworkForRequestId or factories!");
4728 }
4729 }
4730 // TODO: technically, sending CALLBACK_LOST here is
4731 // incorrect if nri is a request (not a listen) and there
4732 // is a replacement network currently connected that can
4733 // satisfy it. However, the only capability that can both
4734 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4735 // so this code is only incorrect for a network that loses
4736 // the TRUSTED capability, which is a rare case.
4737 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004738 }
4739 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004740 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004741 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004742 if (nai.lingering) {
4743 // Already lingered. Nothing to do. This can only happen if "nai" is in
4744 // "affectedNetworks" twice. The reasoning being that to get added to
4745 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4746 // (i.e. not lingered) so it could have only been lingered by this loop.
4747 // unneeded(nai) will be false and we'll call unlinger() below which would
4748 // be bad, so handle it here.
4749 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004750 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004751 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004752 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004753 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004754 }
4755 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004756 if (isNewDefault) {
4757 // Notify system services that this network is up.
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004758 makeDefault(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004759 synchronized (ConnectivityService.this) {
4760 // have a new default network, release the transition wakelock in
4761 // a second if it's held. The second pause is to allow apps
4762 // to reconnect over the new network
4763 if (mNetTransitionWakeLock.isHeld()) {
4764 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4765 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4766 mNetTransitionWakeLockSerialNumber, 0),
4767 1000);
4768 }
4769 }
4770 }
4771
4772 // do this after the default net is switched, but
4773 // before LegacyTypeTracker sends legacy broadcasts
4774 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4775
4776 if (isNewDefault) {
4777 // Maintain the illusion: since the legacy API only
4778 // understands one network at a time, we must pretend
4779 // that the current default network disconnected before
4780 // the new one connected.
4781 if (oldDefaultNetwork != null) {
4782 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4783 oldDefaultNetwork, true);
4784 }
4785 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4786 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4787 notifyLockdownVpn(newNetwork);
4788 }
4789
Robert Greenwalt7b816022014-04-18 15:25:25 -07004790 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004791 // Notify battery stats service about this network, both the normal
4792 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004793 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004794 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004795 final IBatteryStats bs = BatteryStatsService.getService();
4796 final int type = newNetwork.networkInfo.getType();
4797
4798 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4799 bs.noteNetworkInterfaceType(baseIface, type);
4800 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4801 final String stackedIface = stacked.getInterfaceName();
4802 bs.noteNetworkInterfaceType(stackedIface, type);
4803 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4804 }
4805 } catch (RemoteException ignored) {
4806 }
4807
Robert Greenwalt152ed372014-12-17 17:19:53 -08004808 // This has to happen after the notifyNetworkCallbacks as that tickles each
4809 // ConnectivityManager instance so that legacy requests correctly bind dns
4810 // requests to this network. The legacy users are listening for this bcast
4811 // and will generally do a dns request so they can ensureRouteToHost and if
4812 // they do that before the callbacks happen they'll use the default network.
4813 //
4814 // TODO: Is there still a race here? We send the broadcast
4815 // after sending the callback, but if the app can receive the
4816 // broadcast before the callback, it might still break.
4817 //
4818 // This *does* introduce a race where if the user uses the new api
4819 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4820 // they may get old info. Reverse this after the old startUsing api is removed.
4821 // This is on top of the multiple intent sequencing referenced in the todo above.
4822 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4823 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4824 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4825 // legacy type tracker filters out repeat adds
4826 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4827 }
4828 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004829
4830 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4831 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4832 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4833 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4834 if (newNetwork.isVPN()) {
4835 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4836 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004837 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004838 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4839 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004840 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004841 if (DBG) log("Reaping " + nai.name());
4842 teardownUnneededNetwork(nai);
4843 }
4844 }
4845 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004846 }
4847
Paul Jensen1c7ba022015-06-16 14:27:36 -04004848 /**
4849 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4850 * being disconnected.
4851 * @param changed If only one Network's score or capabilities have been modified since the last
4852 * time this function was called, pass this Network in this argument, otherwise pass
4853 * null.
4854 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4855 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4856 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4857 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4858 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004859 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004860 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004861 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4862 // to avoid the slowness. It is not simply enough to process just "changed", for
4863 // example in the case where "changed"'s score decreases and another network should begin
4864 // satifying a NetworkRequest that "changed" currently satisfies.
4865
4866 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4867 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4868 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004869 if (changed != null && oldScore < changed.getCurrentScore()) {
4870 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004871 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004872 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4873 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4874 // Rematch higher scoring networks first to prevent requests first matching a lower
4875 // scoring network and then a higher scoring network, which could produce multiple
4876 // callbacks and inadvertently unlinger networks.
4877 Arrays.sort(nais);
4878 for (NetworkAgentInfo nai : nais) {
4879 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004880 // Only reap the last time through the loop. Reaping before all rematching
4881 // is complete could incorrectly teardown a network that hasn't yet been
4882 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004883 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004884 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004885 }
4886 }
4887 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004888
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004889 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004890 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004891 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004892 // For now only update icons for default connection.
4893 // TODO: Update WiFi and cellular icons separately. b/17237507
4894 if (!isDefaultNetwork(nai)) return;
4895
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004896 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004897 // Don't repeat publish.
4898 if (newInetCondition == mDefaultInetConditionPublished) return;
4899
4900 mDefaultInetConditionPublished = newInetCondition;
4901 sendInetConditionBroadcast(nai.networkInfo);
4902 }
4903
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004904 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4905 if (mLockdownTracker != null) {
4906 if (nai != null && nai.isVPN()) {
4907 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4908 } else {
4909 mLockdownTracker.onNetworkInfoChanged();
4910 }
4911 }
4912 }
4913
Robert Greenwalt7b816022014-04-18 15:25:25 -07004914 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4915 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004916 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004917 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004918 synchronized (networkAgent) {
4919 oldInfo = networkAgent.networkInfo;
4920 networkAgent.networkInfo = newInfo;
4921 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004922 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004923
4924 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004925 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4926 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4927 notifyIfacesChangedForNetworkStats();
4928 } else if (VDBG) log("ignoring duplicate network state non-change");
4929 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004930 return;
4931 }
4932 if (DBG) {
4933 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4934 (oldInfo == null ? "null" : oldInfo.getState()) +
4935 " to " + state);
4936 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004937
Robin Lee585e2482016-05-01 23:00:00 +01004938 if (!networkAgent.created
4939 && (state == NetworkInfo.State.CONNECTED
4940 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004941 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004942 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004943 if (networkAgent.isVPN()) {
4944 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004945 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4946 (networkAgent.networkMisc == null ||
4947 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004948 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004949 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4950 networkAgent.networkCapabilities.hasCapability(
4951 NET_CAPABILITY_NOT_RESTRICTED) ?
4952 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004953 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004954 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004955 loge("Error creating network " + networkAgent.network.netId + ": "
4956 + e.getMessage());
4957 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004958 }
Paul Jenseneec75412014-08-04 12:21:19 -04004959 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004960 }
4961
4962 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4963 networkAgent.everConnected = true;
4964
Robert Greenwalt7b816022014-04-18 15:25:25 -07004965 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004966 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004967
Paul Jensenca8f16a2014-05-09 12:47:55 -04004968 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004969 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004970
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004971 if (networkAgent.isVPN()) {
4972 // Temporarily disable the default proxy (not global).
4973 synchronized (mProxyLock) {
4974 if (!mDefaultProxyDisabled) {
4975 mDefaultProxyDisabled = true;
4976 if (mGlobalProxy == null && mDefaultProxy != null) {
4977 sendProxyBroadcast(null);
4978 }
4979 }
4980 }
4981 // TODO: support proxy per network.
4982 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004983
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004984 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4985 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4986 // capabilities, so it only needs to be done once on initial connect, not every time the
4987 // network's capabilities change. Note that we do this before rematching the network,
4988 // so we could decide to tear it down immediately afterwards. That's fine though - on
4989 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4990 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004991 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004992
Paul Jensen2161a8e2014-09-11 11:00:39 -04004993 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004994 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004995
4996 // This has to happen after matching the requests, because callbacks are just requests.
4997 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004998 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004999 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005000 if (networkAgent.isVPN()) {
5001 synchronized (mProxyLock) {
5002 if (mDefaultProxyDisabled) {
5003 mDefaultProxyDisabled = false;
5004 if (mGlobalProxy == null && mDefaultProxy != null) {
5005 sendProxyBroadcast(mDefaultProxy);
5006 }
5007 }
5008 }
5009 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005010 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5011 state == NetworkInfo.State.SUSPENDED) {
5012 // going into or coming out of SUSPEND: rescore and notify
5013 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005014 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005015 }
5016 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5017 ConnectivityManager.CALLBACK_SUSPENDED :
5018 ConnectivityManager.CALLBACK_RESUMED));
5019 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005020 }
5021 }
5022
Robert Greenwaltac96c522014-06-03 16:43:57 -07005023 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005024 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005025 if (score < 0) {
5026 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5027 "). Bumping score to min of 0");
5028 score = 0;
5029 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005030
Paul Jensen2161a8e2014-09-11 11:00:39 -04005031 final int oldScore = nai.getCurrentScore();
5032 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005033
Paul Jensen85cf78e2015-06-25 13:25:07 -04005034 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005035
Paul Jensenc8b9a742014-09-30 15:37:41 -04005036 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005037 }
5038
Robert Greenwalt9258c642014-03-26 16:47:06 -07005039 // notify only this one new request of the current state
5040 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5041 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
5042 // TODO - read state from monitor to decide what to send.
5043// if (nai.networkMonitor.isLingering()) {
5044// notifyType = NetworkCallbacks.LOSING;
5045// } else if (nai.networkMonitor.isEvaluating()) {
5046// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5047// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005048 if (nri.mPendingIntent == null) {
5049 callCallbackForRequest(nri, nai, notifyType);
5050 } else {
5051 sendPendingIntentForRequest(nri, nai, notifyType);
5052 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005053 }
5054
Robert Greenwalt8d482522015-06-24 13:23:42 -07005055 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005056 // The NetworkInfo we actually send out has no bearing on the real
5057 // state of affairs. For example, if the default connection is mobile,
5058 // and a request for HIPRI has just gone away, we need to pretend that
5059 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5060 // the state to DISCONNECTED, even though the network is of type MOBILE
5061 // and is still connected.
5062 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5063 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005064 if (state != DetailedState.DISCONNECTED) {
5065 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005066 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005067 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005068 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005069 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5070 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5071 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5072 if (info.isFailover()) {
5073 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5074 nai.networkInfo.setFailover(false);
5075 }
5076 if (info.getReason() != null) {
5077 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5078 }
5079 if (info.getExtraInfo() != null) {
5080 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5081 }
5082 NetworkAgentInfo newDefaultAgent = null;
5083 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005084 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005085 if (newDefaultAgent != null) {
5086 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5087 newDefaultAgent.networkInfo);
5088 } else {
5089 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5090 }
5091 }
5092 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5093 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005094 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005095 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005096 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005097 }
5098 }
5099 }
5100
Robert Greenwalt7b816022014-04-18 15:25:25 -07005101 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005102 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005103 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005104 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
5105 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5106 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005107 if (nri.mPendingIntent == null) {
5108 callCallbackForRequest(nri, networkAgent, notifyType);
5109 } else {
5110 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5111 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005112 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005113 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005114
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005115 private String notifyTypeToName(int notifyType) {
5116 switch (notifyType) {
5117 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5118 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5119 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5120 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5121 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5122 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5123 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5124 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5125 }
5126 return "UNKNOWN";
5127 }
5128
Jeff Sharkey69736342014-12-08 14:50:12 -08005129 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005130 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5131 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005132 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005133 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005134 try {
5135 mStatsService.forceUpdateIfaces();
5136 } catch (Exception ignored) {
5137 }
5138 }
5139
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005140 @Override
5141 public boolean addVpnAddress(String address, int prefixLength) {
5142 throwIfLockdownEnabled();
5143 int user = UserHandle.getUserId(Binder.getCallingUid());
5144 synchronized (mVpns) {
5145 return mVpns.get(user).addAddress(address, prefixLength);
5146 }
5147 }
5148
5149 @Override
5150 public boolean removeVpnAddress(String address, int prefixLength) {
5151 throwIfLockdownEnabled();
5152 int user = UserHandle.getUserId(Binder.getCallingUid());
5153 synchronized (mVpns) {
5154 return mVpns.get(user).removeAddress(address, prefixLength);
5155 }
5156 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005157
5158 @Override
5159 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5160 throwIfLockdownEnabled();
5161 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005162 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005163 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005164 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005165 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005166 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005167 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005168 }
5169 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005170 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005171
5172 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005173 public String getCaptivePortalServerUrl() {
5174 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5175 }
5176
5177 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005178 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5179 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5180 enforceKeepalivePermission();
5181 mKeepaliveTracker.startNattKeepalive(
5182 getNetworkAgentInfoForNetwork(network),
5183 intervalSeconds, messenger, binder,
5184 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5185 }
5186
5187 @Override
5188 public void stopKeepalive(Network network, int slot) {
5189 mHandler.sendMessage(mHandler.obtainMessage(
5190 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5191 }
5192
5193 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005194 public void factoryReset() {
5195 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005196
5197 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5198 return;
5199 }
5200
Robin Lee3b3dd942015-05-12 18:14:58 +01005201 final int userId = UserHandle.getCallingUserId();
5202
Stuart Scottf1fb3972015-04-02 18:00:02 -07005203 // Turn airplane mode off
5204 setAirplaneMode(false);
5205
Stuart Scotte3e314d2015-04-20 14:07:45 -07005206 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5207 // Untether
5208 for (String tether : getTetheredIfaces()) {
5209 untether(tether);
5210 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005211 }
5212
Stuart Scotte3e314d2015-04-20 14:07:45 -07005213 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5214 // Turn VPN off
5215 VpnConfig vpnConfig = getVpnConfig(userId);
5216 if (vpnConfig != null) {
5217 if (vpnConfig.legacy) {
5218 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5219 } else {
5220 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5221 // in the future without user intervention.
5222 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005223
Stuart Scotte3e314d2015-04-20 14:07:45 -07005224 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5225 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005226 }
5227 }
5228 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005229
5230 @VisibleForTesting
5231 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5232 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5233 return new NetworkMonitor(context, handler, nai, defaultRequest);
5234 }
Erik Kline48f12f22016-04-14 17:30:59 +09005235
Hugo Benichi5f16f762016-04-20 12:09:33 +09005236 private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5237 int newNetid = NETID_UNSET;
5238 int prevNetid = NETID_UNSET;
5239 int[] transports = new int[0];
5240 boolean hadIPv4 = false;
5241 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005242
Hugo Benichi5f16f762016-04-20 12:09:33 +09005243 if (newNai != null) {
5244 newNetid = newNai.network.netId;
5245 transports = newNai.networkCapabilities.getTransportTypes();
5246 }
5247 if (prevNai != null) {
5248 prevNetid = prevNai.network.netId;
5249 final LinkProperties lp = prevNai.linkProperties;
5250 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5251 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5252 }
5253
5254 DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
Erik Kline48f12f22016-04-14 17:30:59 +09005255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256}