blob: 1e0ebc285bed8f5bb5021828d501717c611cbe52 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060032import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070033import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070034import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060036import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070037import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060038
Wenchao Tongf5ea3402015-03-04 13:26:38 -080039import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080040import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070041import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070042import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.ContentResolver;
44import android.content.Context;
45import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070046import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070048import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090049import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070050import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090052import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070054import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070055import android.net.INetworkPolicyListener;
56import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070057import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080058import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070059import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070060import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070061import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070062import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070063import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070065import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070066import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070067import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070068import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070069import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070070import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070071import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040072import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070073import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040074import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040075import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090076import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090077import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090078import android.net.metrics.NetworkEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080080import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070081import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040082import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070084import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070085import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070086import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Looper;
88import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070089import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070090import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070091import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070092import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070093import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080094import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090095import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070097import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040098import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700100import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700101import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700102import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700103import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600104import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700105import android.util.LocalLog;
106import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600107import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700108import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800109import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700110import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500111import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700112import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700113import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
Wink Savilleab9321d2013-06-29 21:10:57 -0700115import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400116import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400117import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700118import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700119import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700121import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800122import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700123import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700124import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700125import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900126import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900127import com.android.internal.util.WakeupMessage;
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;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900136import com.android.server.connectivity.NetworkNotificationManager;
137import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400138import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700139import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800140import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700141import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700142import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700143import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600144
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700145import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700146
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700147import org.xmlpull.v1.XmlPullParser;
148import org.xmlpull.v1.XmlPullParserException;
149
150import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700152import java.io.FileNotFoundException;
153import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700154import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700156import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700157import java.net.InetAddress;
158import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700159import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700160import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700161import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700162import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700163import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700164import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700165import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700166import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700167import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600168import java.util.SortedSet;
169import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
171/**
172 * @hide
173 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800174public class ConnectivityService extends IConnectivityManager.Stub
175 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900176 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900178 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700179 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Jake Hamby786e71a2014-02-06 14:43:50 -0800181 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900182 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700183
Jeff Sharkey899223b2012-08-04 15:24:58 -0700184 // TODO: create better separation between radio types and network types
185
Robert Greenwalt42acef32009-08-12 16:08:25 -0700186 // how long to wait before switching back to a radio's default network
187 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
188 // system property that can override the above value
189 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
190 "android.telephony.apn-restore";
191
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900192 // How long to wait before putting up a "This network doesn't have an Internet connection,
193 // connect anyway?" dialog after the user selects a network that doesn't validate.
194 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
195
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900196 // Default to 30s linger time-out. Modifiable only for testing.
197 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
198 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
199 @VisibleForTesting
200 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
201
Jeremy Joslin79294842014-12-03 17:15:28 -0800202 // How long to delay to removal of a pending intent based request.
203 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
204 private final int mReleasePendingIntentDelayMs;
205
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800206 private Tethering mTethering;
207
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700208 private final PermissionMonitor mPermissionMonitor;
209
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700210 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700211
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700212 @GuardedBy("mVpns")
213 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700214
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700215 private boolean mLockdownEnabled;
216 private LockdownVpnTracker mLockdownTracker;
217
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700218 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
219 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700220 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600221 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700223 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600224 @GuardedBy("mRulesLock")
225 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
226 /** Flag indicating if background data is restricted. */
227 @GuardedBy("mRulesLock")
228 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700229
Erik Klineda4bfa82015-04-30 12:58:40 +0900230 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700232 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700233 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800235 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
237 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700238 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700240 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800241 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700242 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700243
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700244 private String mCurrentTcpBufferSizes;
245
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700246 private static final int ENABLED = 1;
247 private static final int DISABLED = 0;
248
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900249 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900250 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
251 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900252
Paul Jensenb10e37f2014-11-25 12:33:08 -0500253 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400254 // Tear down networks that have no chance (e.g. even if validated) of becoming
255 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500256 // all networks have been rematched against all NetworkRequests.
257 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400258 // Don't reap networks. This should be passed when some networks have not yet been
259 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500260 DONT_REAP
261 };
262
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700263 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700264 * used internally to change our mobile data enabled flag
265 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700266 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700267
268 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700269 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700270 * from one net to another. Clear happens when we get a new
271 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
272 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700273 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700274 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700275
Robert Greenwalt434203a2010-10-11 16:00:27 -0700276 /**
277 * used internally to reload global proxy settings
278 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700279 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700280
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700281 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400282 * PAC manager has received new port.
283 */
284 private static final int EVENT_PROXY_HAS_CHANGED = 16;
285
Robert Greenwalte049c232014-04-11 15:53:27 -0700286 /**
287 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700288 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700289 */
290 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
291
Robert Greenwalt7b816022014-04-18 15:25:25 -0700292 /**
293 * used internally when registering NetworkAgents
294 * obj = Messenger
295 */
296 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
297
Robert Greenwalt9258c642014-03-26 16:47:06 -0700298 /**
299 * used to add a network request
300 * includes a NetworkRequestInfo
301 */
302 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
303
304 /**
305 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900306 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700307 * cancel it.
308 * includes a NetworkRequestInfo
309 */
310 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
311
312 /**
313 * used to add a network listener - no request
314 * includes a NetworkRequestInfo
315 */
316 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
317
318 /**
319 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400320 * arg1 = UID of caller
321 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700322 */
323 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
324
Robert Greenwalta67be032014-05-16 15:49:14 -0700325 /**
326 * used internally when registering NetworkFactories
327 * obj = Messenger
328 */
329 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
330
Robert Greenwalt27711812014-06-25 16:45:57 -0700331 /**
332 * used internally to expire a wakelock when transitioning
333 * from one net to another. Expire happens when we fail to find
334 * a new network (typically after 1 minute) -
335 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
336 * a replacement network.
337 */
338 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
339
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700340 /**
341 * Used internally to indicate the system is ready.
342 */
343 private static final int EVENT_SYSTEM_READY = 25;
344
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800345 /**
346 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400347 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800348 */
349 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
350
351 /**
352 * used to remove a pending intent and its associated network request.
353 * arg1 = UID of caller
354 * obj = PendingIntent
355 */
356 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
357
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900358 /**
359 * used to specify whether a network should be used even if unvalidated.
360 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
361 * arg2 = whether to remember this choice in the future (1 or 0)
362 * obj = network
363 */
364 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
365
366 /**
367 * used to ask the user to confirm a connection to an unvalidated network.
368 * obj = network
369 */
370 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700371
Erik Klineda4bfa82015-04-30 12:58:40 +0900372 /**
373 * used internally to (re)configure mobile data always-on settings.
374 */
375 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
376
Paul Jensen694f2b82015-06-17 14:15:39 -0400377 /**
378 * used to add a network listener with a pending intent
379 * obj = NetworkRequestInfo
380 */
381 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
382
Erik Klineacdd6392016-07-07 16:50:58 +0900383 /**
384 * Indicates a caller has requested to have its callback invoked with
385 * the latest LinkProperties or NetworkCapabilities.
386 *
387 * arg1 = UID of caller
388 * obj = NetworkRequest
389 */
390 private static final int EVENT_REQUEST_LINKPROPERTIES = 32;
391 private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
392
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900393 /** Handler thread used for both of the handlers below. */
394 @VisibleForTesting
395 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700396 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700397 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700398 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700399 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700400
Mike Lockwood0f79b542009-08-14 14:18:49 -0400401 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800402 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400403
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700404 private PowerManager.WakeLock mNetTransitionWakeLock;
405 private String mNetTransitionWakeLockCausedBy = "";
406 private int mNetTransitionWakeLockSerialNumber;
407 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800408 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700409
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700410 // used in DBG mode to track inet condition reports
411 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
412 private ArrayList mInetLog;
413
Robert Greenwalt434203a2010-10-11 16:00:27 -0700414 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400415 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700416 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700417 private boolean mDefaultProxyDisabled = false;
418
Robert Greenwalt434203a2010-10-11 16:00:27 -0700419 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400420 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700421
Jason Monk602b2322013-07-03 17:04:33 -0400422 private PacManager mPacManager = null;
423
Erik Klineda4bfa82015-04-30 12:58:40 +0900424 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700425
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400426 private UserManager mUserManager;
427
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700428 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700429 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700430
Robert Greenwalt50393202011-06-21 17:26:14 -0700431 // the set of network types that can only be enabled by system/sig apps
432 List mProtectedNetworks;
433
John Spurlockbf991a82013-06-24 14:20:23 -0400434 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700435
Wink Savilleab9321d2013-06-29 21:10:57 -0700436 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400437
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900438 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900439 private NetworkNotificationManager mNotifier;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900440
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700441 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
442 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700443 private final static int MAX_NET_ID = 65535;
444 private int mNextNetId = MIN_NET_ID;
445
Robert Greenwalt34524f02014-05-18 16:22:10 -0700446 // sequence number of NetworkRequests
447 private int mNextNetworkRequestId = 1;
448
Erik Kline7523eb32015-07-09 18:24:03 +0900449 // NetworkRequest activity String log entries.
450 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
451 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
452
Hugo Benichic2ae2872016-07-11 11:05:12 +0900453 // NetworkInfo blocked and unblocked String log entries
454 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
455 private static final int MAX_NETWORK_INFO_LOGS = 100;
456 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
457
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700458 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
459 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400460 private static class ValidationLog {
461 final Network mNetwork;
462 final String mNetworkExtraInfo;
463 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700464
Paul Jensen0808eb82016-06-03 13:51:21 -0400465 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
466 mNetwork = network;
467 mNetworkExtraInfo = networkExtraInfo;
468 mLog = log;
469 }
470 }
471 private final ArrayDeque<ValidationLog> mValidationLogs =
472 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
473
474 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700475 synchronized(mValidationLogs) {
476 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
477 mValidationLogs.removeLast();
478 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400479 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700480 }
481 }
482
Hugo Benichif9fdf872016-07-28 17:53:06 +0900483 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900484
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700485 /**
486 * Implements support for the legacy "one network per network type" model.
487 *
488 * We used to have a static array of NetworkStateTrackers, one for each
489 * network type, but that doesn't work any more now that we can have,
490 * for example, more that one wifi network. This class stores all the
491 * NetworkAgentInfo objects that support a given type, but the legacy
492 * API will only see the first one.
493 *
494 * It serves two main purposes:
495 *
496 * 1. Provide information about "the network for a given type" (since this
497 * API only supports one).
498 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
499 * the first network for a given type changes, or if the default network
500 * changes.
501 */
502 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900503
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900504 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900505 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900506
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700507 /**
508 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
509 * Each list holds references to all NetworkAgentInfos that are used to
510 * satisfy requests for that network type.
511 *
512 * This array is built out at startup such that an unsupported network
513 * doesn't get an ArrayList instance, making this a tristate:
514 * unsupported, supported but not active and active.
515 *
516 * The actual lists are populated when we scan the network types that
517 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900518 *
519 * Threading model:
520 * - addSupportedType() is only called in the constructor
521 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
522 * They are therefore not thread-safe with respect to each other.
523 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
524 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
525 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700526 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900527 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700528
529 public LegacyTypeTracker() {
530 mTypeLists = (ArrayList<NetworkAgentInfo>[])
531 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
532 }
533
534 public void addSupportedType(int type) {
535 if (mTypeLists[type] != null) {
536 throw new IllegalStateException(
537 "legacy list for type " + type + "already initialized");
538 }
539 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
540 }
541
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700542 public boolean isTypeSupported(int type) {
543 return isNetworkTypeValid(type) && mTypeLists[type] != null;
544 }
545
546 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900547 synchronized (mTypeLists) {
548 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
549 return mTypeLists[type].get(0);
550 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700551 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900552 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700553 }
554
Robert Greenwalt8d482522015-06-24 13:23:42 -0700555 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900556 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900557 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700558 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900559 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900560 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900561 }
562 }
563
564 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700565 public void add(int type, NetworkAgentInfo nai) {
566 if (!isTypeSupported(type)) {
567 return; // Invalid network type.
568 }
569 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
570
571 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
572 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700573 return;
574 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900575 synchronized (mTypeLists) {
576 list.add(nai);
577 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900578
579 // 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 +0900580 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900581 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700582 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
583 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700584 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700585 }
586
Lorenzo Colittia793a672014-07-31 23:20:17 +0900587 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900588 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900589 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
590 if (list == null || list.isEmpty()) {
591 return;
592 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900593 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900594
Hugo Benichi78caa2582016-06-21 09:48:07 +0900595 synchronized (mTypeLists) {
596 if (!list.remove(nai)) {
597 return;
598 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900599 }
600
Robert Greenwalt8d482522015-06-24 13:23:42 -0700601 final DetailedState state = DetailedState.DISCONNECTED;
602
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900603 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700604 maybeLogBroadcast(nai, state, type, wasDefault);
605 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606 }
607
608 if (!list.isEmpty() && wasFirstNetwork) {
609 if (DBG) log("Other network available for type " + type +
610 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900611 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700612 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
613 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900614 }
615 }
616
617 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900618 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
619 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700620 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700622 }
623 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700624
Robert Greenwalt8d482522015-06-24 13:23:42 -0700625 // send out another legacy broadcast - currently only used for suspend/unsuspend
626 // toggle
627 public void update(NetworkAgentInfo nai) {
628 final boolean isDefault = isDefaultNetwork(nai);
629 final DetailedState state = nai.networkInfo.getDetailedState();
630 for (int type = 0; type < mTypeLists.length; type++) {
631 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700632 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900633 final boolean isFirst = contains && (nai == list.get(0));
634 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700635 maybeLogBroadcast(nai, state, type, isDefault);
636 sendLegacyNetworkBroadcast(nai, state, type);
637 }
638 }
639 }
640
Lorenzo Colittia793a672014-07-31 23:20:17 +0900641 private String naiToString(NetworkAgentInfo nai) {
642 String name = (nai != null) ? nai.name() : "null";
643 String state = (nai.networkInfo != null) ?
644 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
645 "???/???";
646 return name + " " + state;
647 }
648
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700649 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900650 pw.println("mLegacyTypeTracker:");
651 pw.increaseIndent();
652 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700653 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900654 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700655 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900656 pw.println();
657 pw.println("Current state:");
658 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900659 synchronized (mTypeLists) {
660 for (int type = 0; type < mTypeLists.length; type++) {
661 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
662 for (NetworkAgentInfo nai : mTypeLists[type]) {
663 pw.println(type + " " + naiToString(nai));
664 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900665 }
666 }
667 pw.decreaseIndent();
668 pw.decreaseIndent();
669 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700670 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700671 }
672 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
673
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900674 @VisibleForTesting
675 protected HandlerThread createHandlerThread() {
676 return new HandlerThread("ConnectivityServiceThread");
677 }
678
Jeff Sharkey899223b2012-08-04 15:24:58 -0700679 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700680 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900681 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
682 }
683
684 @VisibleForTesting
685 protected ConnectivityService(Context context, INetworkManagementService netManager,
686 INetworkStatsService statsService, INetworkPolicyManager policyManager,
687 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800688 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800689
Hugo Benichif9fdf872016-07-28 17:53:06 +0900690 mMetricsLog = logger;
Erik Klineda4bfa82015-04-30 12:58:40 +0900691 mDefaultRequest = createInternetRequestForTransport(-1);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900692 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900693 mNetworkRequests.put(mDefaultRequest, defaultNRI);
694 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900695
696 mDefaultMobileDataRequest = createInternetRequestForTransport(
697 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700698
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900699 mHandlerThread = createHandlerThread();
700 mHandlerThread.start();
701 mHandler = new InternalHandler(mHandlerThread.getLooper());
702 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700703
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800704 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800705 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
706 String id = Settings.Secure.getString(context.getContentResolver(),
707 Settings.Secure.ANDROID_ID);
708 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700709 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800710 SystemProperties.set("net.hostname", name);
711 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800712 }
713
Jeremy Joslin79294842014-12-03 17:15:28 -0800714 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
715 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
716
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900717 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
718
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700719 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700720 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800721 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700722 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700723 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700724 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700725
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700726 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600727 mPolicyManager.setConnectivityListener(mPolicyListener);
728 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700729 } catch (RemoteException e) {
730 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700731 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700732 }
733
734 final PowerManager powerManager = (PowerManager) context.getSystemService(
735 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700736 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
737 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
738 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800739 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700740
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700741 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700742
Wink Saville51f456f2013-04-23 14:26:51 -0700743 // TODO: What is the "correct" way to do determine if this is a wifi only device?
744 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
745 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700746 String[] naStrings = context.getResources().getStringArray(
747 com.android.internal.R.array.networkAttributes);
748 for (String naString : naStrings) {
749 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700750 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700751 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700752 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800753 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700754 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700755 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700756 }
Wink Saville51f456f2013-04-23 14:26:51 -0700757 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
758 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
759 n.type);
760 continue;
761 }
Wink Saville975c8482011-04-07 14:23:45 -0700762 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800763 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700764 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700765 continue;
766 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700767 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700768
Wink Saville975c8482011-04-07 14:23:45 -0700769 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700770 mNetworksDefined++;
771 } catch(Exception e) {
772 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700773 }
774 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700775
776 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
777 if (mNetConfigs[TYPE_VPN] == null) {
778 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
779 // don't need to add TYPE_VPN to mNetConfigs.
780 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
781 mNetworksDefined++; // used only in the log() statement below.
782 }
783
Wink Saville5e56bc52013-07-29 15:00:57 -0700784 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700785
Robert Greenwalt50393202011-06-21 17:26:14 -0700786 mProtectedNetworks = new ArrayList<Integer>();
787 int[] protectedNetworks = context.getResources().getIntArray(
788 com.android.internal.R.array.config_protectedNetworks);
789 for (int p : protectedNetworks) {
790 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
791 mProtectedNetworks.add(p);
792 } else {
793 if (DBG) loge("Ignoring protectedNetwork " + p);
794 }
795 }
796
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700797 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
798 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700799
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800800 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800801
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700802 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
803
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700804 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700805 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100806 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700807 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700808 intentFilter.addAction(Intent.ACTION_USER_ADDED);
809 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000810 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700811 mContext.registerReceiverAsUser(
812 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900813
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700814 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700815 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700816 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700817 } catch (RemoteException e) {
818 loge("Error registering observer :" + e);
819 }
820
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700821 if (DBG) {
822 mInetLog = new ArrayList();
823 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700824
Erik Klineda4bfa82015-04-30 12:58:40 +0900825 mSettingsObserver = new SettingsObserver(mContext, mHandler);
826 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800827
John Spurlockbf991a82013-06-24 14:20:23 -0400828 mDataConnectionStats = new DataConnectionStats(mContext);
829 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400830
Jason Monkdecd2952013-10-10 14:02:51 -0400831 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700832
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400833 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900834
835 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900836 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700838
Erik Klineda4bfa82015-04-30 12:58:40 +0900839 private NetworkRequest createInternetRequestForTransport(int transportType) {
840 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900841 netCap.addCapability(NET_CAPABILITY_INTERNET);
842 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900843 if (transportType > -1) {
844 netCap.addTransportType(transportType);
845 }
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900846 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(),
847 NetworkRequest.Type.REQUEST);
Erik Klineda4bfa82015-04-30 12:58:40 +0900848 }
849
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900850 // Used only for testing.
851 // TODO: Delete this and either:
852 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
853 // changing ContentResolver to make registerContentObserver non-final).
854 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
855 // by subclassing SettingsObserver.
856 @VisibleForTesting
857 void updateMobileDataAlwaysOn() {
858 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
859 }
860
Erik Klineda4bfa82015-04-30 12:58:40 +0900861 private void handleMobileDataAlwaysOn() {
862 final boolean enable = (Settings.Global.getInt(
863 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
864 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
865 if (enable == isEnabled) {
866 return; // Nothing to do.
867 }
868
869 if (enable) {
870 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900871 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900872 } else {
873 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
874 }
875 }
876
877 private void registerSettingsCallbacks() {
878 // Watch for global HTTP proxy changes.
879 mSettingsObserver.observe(
880 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
881 EVENT_APPLY_GLOBAL_HTTP_PROXY);
882
883 // Watch for whether or not to keep mobile data always on.
884 mSettingsObserver.observe(
885 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
886 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
887 }
888
Robert Greenwalt34524f02014-05-18 16:22:10 -0700889 private synchronized int nextNetworkRequestId() {
890 return mNextNetworkRequestId++;
891 }
892
Paul Jensen67b0b072015-06-10 11:22:17 -0400893 @VisibleForTesting
894 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400895 synchronized (mNetworkForNetId) {
896 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
897 int netId = mNextNetId;
898 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
899 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500900 if (!mNetIdInUse.get(netId)) {
901 mNetIdInUse.put(netId, true);
902 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400903 }
904 }
905 }
906 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700907 }
908
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600909 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800910 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600911 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
912 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800913 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600914 state = nai.getNetworkState();
915 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800916 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600917 final NetworkInfo info = new NetworkInfo(networkType, 0,
918 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800919 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
920 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600921 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
922 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800923 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600924 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600925 return state;
926 } else {
927 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800928 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400929 }
930
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800931 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
932 if (network == null) {
933 return null;
934 }
935 synchronized (mNetworkForNetId) {
936 return mNetworkForNetId.get(network.netId);
937 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600938 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900940 private Network[] getVpnUnderlyingNetworks(int uid) {
941 if (!mLockdownEnabled) {
942 int user = UserHandle.getUserId(uid);
943 synchronized (mVpns) {
944 Vpn vpn = mVpns.get(user);
945 if (vpn != null && vpn.appliesToUid(uid)) {
946 return vpn.getUnderlyingNetworks();
947 }
948 }
949 }
950 return null;
951 }
952
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800953 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400954 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800955
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900956 final Network[] networks = getVpnUnderlyingNetworks(uid);
957 if (networks != null) {
958 // getUnderlyingNetworks() returns:
959 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
960 // empty array => the VPN explicitly said "no default network".
961 // non-empty array => the VPN specified one or more default networks; we use the
962 // first one.
963 if (networks.length > 0) {
964 nai = getNetworkAgentInfoForNetwork(networks[0]);
965 } else {
966 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800967 }
968 }
969
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800970 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600971 return nai.getNetworkState();
972 } else {
973 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800974 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400975 }
976
977 /**
978 * Check if UID should be blocked from using the network with the given LinkProperties.
979 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600980 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
981 boolean ignoreBlocked) {
982 // Networks aren't blocked when ignoring blocked status
983 if (ignoreBlocked) return false;
984 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -0700985 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600986
987 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700988 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700989
Robin Lee17e61832016-05-09 13:46:28 +0100990 synchronized (mVpns) {
991 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
992 if (vpn != null && vpn.isBlockingUid(uid)) {
993 return true;
994 }
995 }
996
Robert Greenwalt12e67352014-05-13 21:41:06 -0700997 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700998 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600999 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001000 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001001 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001002
Felipe Lemed31a97f2016-05-06 14:53:50 -07001003 boolean allowed = true;
1004 // Check Data Saver Mode first...
1005 if (networkMetered) {
1006 if ((uidRules & RULE_REJECT_METERED) != 0) {
1007 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1008 // Explicitly blacklisted.
1009 allowed = false;
1010 } else {
1011 allowed = !mRestrictBackground
1012 || (uidRules & RULE_ALLOW_METERED) != 0
1013 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1014 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1015 + " mRestrictBackground=" + mRestrictBackground
1016 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1017 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1018 + ": " + allowed);
1019 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001020 }
Felipe Leme781ba142016-05-09 16:24:48 -07001021 // ...then power restrictions.
1022 if (allowed) {
1023 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001024 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001025 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001026 }
1027 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001028 }
1029
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001030 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001031 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1032 return;
1033 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001034 boolean removed = false;
1035 boolean added = false;
1036 synchronized (mBlockedAppUids) {
1037 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1038 added = true;
1039 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1040 removed = true;
1041 }
1042 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001043 if (added) {
1044 log("Returning blocked NetworkInfo to uid=" + uid);
1045 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1046 } else if (removed) {
1047 log("Returning unblocked NetworkInfo to uid=" + uid);
1048 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1049 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001050 }
1051
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001052 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001053 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1054 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1055 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1056 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001057 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001058 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001059 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1060
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001061 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001062 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001063 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001064 if (mLockdownTracker != null) {
1065 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001066 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001067
1068 // TODO: apply metered state closer to NetworkAgentInfo
1069 final long token = Binder.clearCallingIdentity();
1070 try {
1071 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1072 } catch (RemoteException e) {
1073 } finally {
1074 Binder.restoreCallingIdentity(token);
1075 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001076 }
1077
1078 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 * Return NetworkInfo for the active (i.e., connected) network interface.
1080 * It is assumed that at most one network is active at a time. If more
1081 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001082 * @return the info for the active network, or {@code null} if none is
1083 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001085 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001087 enforceAccessPermission();
1088 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001089 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001090 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001091 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1092 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
1094
Paul Jensen31a94f42015-02-13 14:18:39 -05001095 @Override
1096 public Network getActiveNetwork() {
1097 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001098 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001099 }
1100
1101 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001102 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001103 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001104 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001105 }
1106
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001107 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001108 final int user = UserHandle.getUserId(uid);
1109 int vpnNetId = NETID_UNSET;
1110 synchronized (mVpns) {
1111 final Vpn vpn = mVpns.get(user);
1112 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1113 }
1114 NetworkAgentInfo nai;
1115 if (vpnNetId != NETID_UNSET) {
1116 synchronized (mNetworkForNetId) {
1117 nai = mNetworkForNetId.get(vpnNetId);
1118 }
1119 if (nai != null) return nai.network;
1120 }
1121 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 if (nai != null
1123 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1124 nai = null;
1125 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001126 return nai != null ? nai.network : null;
1127 }
1128
Lorenzo Colitti18660282016-07-04 12:55:44 +09001129 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001130 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1131 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001132 final int uid = Binder.getCallingUid();
1133 NetworkState state = getUnfilteredActiveNetworkState(uid);
1134 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001135 }
1136
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001137 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001138 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001139 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001140 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001141 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001142 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001143 }
1144
1145 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 public NetworkInfo getNetworkInfo(int networkType) {
1147 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001148 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001149 if (getVpnUnderlyingNetworks(uid) != null) {
1150 // A VPN is active, so we may need to return one of its underlying networks. This
1151 // information is not available in LegacyTypeTracker, so we have to get it from
1152 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001153 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001154 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001155 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001156 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001157 }
1158 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001159 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001160 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 }
1162
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001163 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001164 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001165 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001166 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001167 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001168 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001169 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001170 return state.networkInfo;
1171 } else {
1172 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001173 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001174 }
1175
1176 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 public NetworkInfo[] getAllNetworkInfo() {
1178 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001179 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001180 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1181 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001182 NetworkInfo info = getNetworkInfo(networkType);
1183 if (info != null) {
1184 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001187 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 }
1189
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001190 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001191 public Network getNetworkForType(int networkType) {
1192 enforceAccessPermission();
1193 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001194 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1195 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001196 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001197 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001198 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001199 }
1200
1201 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001202 public Network[] getAllNetworks() {
1203 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001204 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001205 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001206 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001207 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001208 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001209 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001210 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001211 }
1212
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001213 @Override
1214 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1215 // The basic principle is: if an app's traffic could possibly go over a
1216 // network, without the app doing anything multinetwork-specific,
1217 // (hence, by "default"), then include that network's capabilities in
1218 // the array.
1219 //
1220 // In the normal case, app traffic only goes over the system's default
1221 // network connection, so that's the only network returned.
1222 //
1223 // With a VPN in force, some app traffic may go into the VPN, and thus
1224 // over whatever underlying networks the VPN specifies, while other app
1225 // traffic may go over the system default network (e.g.: a split-tunnel
1226 // VPN, or an app disallowed by the VPN), so the set of networks
1227 // returned includes the VPN's underlying networks and the system
1228 // default.
1229 enforceAccessPermission();
1230
1231 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1232
1233 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001234 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001235 if (nc != null) {
1236 result.put(nai.network, nc);
1237 }
1238
1239 if (!mLockdownEnabled) {
1240 synchronized (mVpns) {
1241 Vpn vpn = mVpns.get(userId);
1242 if (vpn != null) {
1243 Network[] networks = vpn.getUnderlyingNetworks();
1244 if (networks != null) {
1245 for (Network network : networks) {
1246 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001247 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001248 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001249 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001250 }
1251 }
1252 }
1253 }
1254 }
1255 }
1256
1257 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1258 out = result.values().toArray(out);
1259 return out;
1260 }
1261
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001262 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001263 public boolean isNetworkSupported(int networkType) {
1264 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001265 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001266 }
1267
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001268 /**
1269 * Return LinkProperties for the active (i.e., connected) default
1270 * network interface. It is assumed that at most one default network
1271 * is active at a time. If more than one is active, it is indeterminate
1272 * which will be returned.
1273 * @return the ip properties for the active network, or {@code null} if
1274 * none is active
1275 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001276 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001277 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001278 enforceAccessPermission();
1279 final int uid = Binder.getCallingUid();
1280 NetworkState state = getUnfilteredActiveNetworkState(uid);
1281 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001282 }
1283
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001284 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001285 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001286 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001287 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1288 if (nai != null) {
1289 synchronized (nai) {
1290 return new LinkProperties(nai.linkProperties);
1291 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001292 }
1293 return null;
1294 }
1295
Robert Greenwalt12e67352014-05-13 21:41:06 -07001296 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001297 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001298 public LinkProperties getLinkProperties(Network network) {
1299 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001300 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001301 if (nai != null) {
1302 synchronized (nai) {
1303 return new LinkProperties(nai.linkProperties);
1304 }
1305 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001306 return null;
1307 }
1308
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001309 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001310 if (nai != null) {
1311 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001312 if (nai.networkCapabilities != null) {
1313 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001314 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001315 }
1316 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001317 return null;
1318 }
1319
1320 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001321 public NetworkCapabilities getNetworkCapabilities(Network network) {
1322 enforceAccessPermission();
1323 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1324 }
1325
1326 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001327 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001328 // Require internal since we're handing out IMSI details
1329 enforceConnectivityInternalPermission();
1330
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001331 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001332 for (Network network : getAllNetworks()) {
1333 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1334 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001335 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001336 }
1337 }
1338 return result.toArray(new NetworkState[result.size()]);
1339 }
1340
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001341 @Override
1342 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1343 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001344 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001345 final long token = Binder.clearCallingIdentity();
1346 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001347 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1348 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001349 try {
1350 return mPolicyManager.getNetworkQuotaInfo(state);
1351 } catch (RemoteException e) {
1352 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001353 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001354 return null;
1355 } finally {
1356 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001357 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001358 }
1359
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001360 @Override
1361 public boolean isActiveNetworkMetered() {
1362 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001363
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001364 final NetworkInfo info = getActiveNetworkInfo();
1365 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001366 }
1367
Jeff Sharkey216c1812012-08-05 14:29:23 -07001368 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1369 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001370 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001371 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001372 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001373 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001374 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001375
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001376 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 * Ensure that a network route exists to deliver traffic to the specified
1378 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001379 * @param networkType the type of the network over which traffic to the
1380 * specified host is to be routed
1381 * @param hostAddress the IP address of the host to which the route is
1382 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 * @return {@code true} on success, {@code false} on failure
1384 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001385 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001386 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001388 if (mProtectedNetworks.contains(networkType)) {
1389 enforceConnectivityInternalPermission();
1390 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001391
Chad Brubakerc0234532014-02-14 13:24:29 -08001392 InetAddress addr;
1393 try {
1394 addr = InetAddress.getByAddress(hostAddress);
1395 } catch (UnknownHostException e) {
1396 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1397 return false;
1398 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001401 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 return false;
1403 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001404
1405 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1406 if (nai == null) {
1407 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1408 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1409 } else {
1410 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1411 }
1412 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001413 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001414
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001415 DetailedState netState;
1416 synchronized (nai) {
1417 netState = nai.networkInfo.getDetailedState();
1418 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001419
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001420 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001421 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001422 log("requestRouteToHostAddress on down network "
1423 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001424 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001425 }
1426 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001428
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001429 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001430 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001431 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001432 LinkProperties lp;
1433 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001434 synchronized (nai) {
1435 lp = nai.linkProperties;
1436 netId = nai.network.netId;
1437 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001438 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001439 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1440 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001441 } finally {
1442 Binder.restoreCallingIdentity(token);
1443 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001444 }
1445
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001446 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001447 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001448 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001449 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001450 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001451 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001452 if (bestRoute.getGateway().equals(addr)) {
1453 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001454 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001455 } else {
1456 // if we will connect to this through another route, add a direct route
1457 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001458 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001459 }
1460 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001461 if (DBG) log("Adding legacy route " + bestRoute +
1462 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001463 try {
1464 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1465 } catch (Exception e) {
1466 // never crash - catch them all
1467 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001468 return false;
1469 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001470 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 }
1472
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001473 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1474 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001475 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001476 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001477 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001478 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001479 }
1480
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001481 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001482 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001483 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001484 if (oldRules == uidRules) return;
1485
Felipe Leme781ba142016-05-09 16:24:48 -07001486 if (uidRules == RULE_NONE) {
1487 mUidRules.delete(uid);
1488 } else {
1489 mUidRules.put(uid, uidRules);
1490 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001491 }
1492
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001493 // TODO: notify UID when it has requested targeted updates
1494 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001495
1496 @Override
1497 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001498 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001499 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001500 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001501 }
1502
1503 synchronized (mRulesLock) {
1504 mMeteredIfaces.clear();
1505 for (String iface : meteredIfaces) {
1506 mMeteredIfaces.add(iface);
1507 }
1508 }
1509 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001510
1511 @Override
1512 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1513 // caller is NPMS, since we only register with them
1514 if (LOGD_RULES) {
1515 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1516 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001517
1518 synchronized (mRulesLock) {
1519 mRestrictBackground = restrictBackground;
1520 }
1521
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001522 if (restrictBackground) {
1523 log("onRestrictBackgroundChanged(true): disabling tethering");
1524 mTethering.untetherAll();
1525 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001526 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001527
1528 @Override
1529 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1530 if (LOGD_RULES) {
1531 // caller is NPMS, since we only register with them
1532 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1533 + whitelisted + ")");
1534 }
1535 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001536 @Override
1537 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1538 if (LOGD_RULES) {
1539 // caller is NPMS, since we only register with them
1540 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1541 + blacklisted + ")");
1542 }
1543 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001544 };
1545
Robin Lee3b3dd942015-05-12 18:14:58 +01001546 /**
1547 * Require that the caller is either in the same user or has appropriate permission to interact
1548 * across users.
1549 *
1550 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1551 */
1552 private void enforceCrossUserPermission(int userId) {
1553 if (userId == UserHandle.getCallingUserId()) {
1554 // Not a cross-user call.
1555 return;
1556 }
1557 mContext.enforceCallingOrSelfPermission(
1558 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1559 "ConnectivityService");
1560 }
1561
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001562 private void enforceInternetPermission() {
1563 mContext.enforceCallingOrSelfPermission(
1564 android.Manifest.permission.INTERNET,
1565 "ConnectivityService");
1566 }
1567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001569 mContext.enforceCallingOrSelfPermission(
1570 android.Manifest.permission.ACCESS_NETWORK_STATE,
1571 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 }
1573
1574 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001575 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 }
1577
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001578 private void enforceTetherAccessPermission() {
1579 mContext.enforceCallingOrSelfPermission(
1580 android.Manifest.permission.ACCESS_NETWORK_STATE,
1581 "ConnectivityService");
1582 }
1583
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001584 private void enforceConnectivityInternalPermission() {
1585 mContext.enforceCallingOrSelfPermission(
1586 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1587 "ConnectivityService");
1588 }
1589
Hugo Benichi514da602016-07-19 15:59:27 +09001590 private void enforceConnectivityRestrictedNetworksPermission() {
1591 try {
1592 mContext.enforceCallingOrSelfPermission(
1593 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1594 "ConnectivityService");
1595 return;
1596 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1597 enforceConnectivityInternalPermission();
1598 }
1599
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001600 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001601 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001602 }
1603
Lorenzo Colitti18660282016-07-04 12:55:44 +09001604 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001605 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001606 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001607 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001608 }
1609
1610 private void sendInetConditionBroadcast(NetworkInfo info) {
1611 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1612 }
1613
Wink Saville628b0852011-08-04 15:01:58 -07001614 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001615 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001616 info = new NetworkInfo(info);
1617 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001618 }
1619
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001620 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001621 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001622 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 if (info.isFailover()) {
1624 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1625 info.setFailover(false);
1626 }
1627 if (info.getReason() != null) {
1628 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1629 }
1630 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001631 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1632 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001634 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001635 return intent;
1636 }
1637
1638 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1639 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1640 }
1641
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001642 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001643 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1644 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1645 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001646 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001647 final long ident = Binder.clearCallingIdentity();
1648 try {
1649 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1650 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1651 } finally {
1652 Binder.restoreCallingIdentity(ident);
1653 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001654 }
1655
Mike Lockwood0f79b542009-08-14 14:18:49 -04001656 private void sendStickyBroadcast(Intent intent) {
1657 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001658 if (!mSystemReady) {
1659 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001660 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001661 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001662 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001663 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001664 }
1665
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001666 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001667 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001668 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001669 final NetworkInfo ni = intent.getParcelableExtra(
1670 ConnectivityManager.EXTRA_NETWORK_INFO);
1671 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1672 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1673 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001674 } else {
1675 BroadcastOptions opts = BroadcastOptions.makeBasic();
1676 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1677 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001678 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001679 final IBatteryStats bs = BatteryStatsService.getService();
1680 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001681 bs.noteConnectivityChanged(intent.getIntExtra(
1682 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1683 ni != null ? ni.getState().toString() : "?");
1684 } catch (RemoteException e) {
1685 }
1686 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001687 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001688 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001689 } finally {
1690 Binder.restoreCallingIdentity(ident);
1691 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001692 }
1693 }
1694
1695 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001696 loadGlobalProxy();
1697
Mike Lockwood0f79b542009-08-14 14:18:49 -04001698 synchronized(this) {
1699 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001700 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001701 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001702 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001703 }
1704 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001705 // load the global proxy at startup
1706 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001707
Robin Lee244ce8e2016-01-05 18:03:46 +00001708 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1709 // for user to unlock device too.
1710 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001711
Erik Klineda4bfa82015-04-30 12:58:40 +09001712 // Configure whether mobile data is always on.
1713 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1714
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001715 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001716
1717 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 }
1719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001721 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001722 *
1723 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001724 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001725 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001726 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1727 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001728
1729 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001730 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001731
Robert Greenwalt7b816022014-04-18 15:25:25 -07001732 if (networkAgent.networkCapabilities.hasTransport(
1733 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001734 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1735 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001736 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001737 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001738 } else if (networkAgent.networkCapabilities.hasTransport(
1739 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001740 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1741 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001742 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001743 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001744 } else {
1745 // do not track any other networks
1746 timeout = 0;
1747 }
1748
Robert Greenwalt7b816022014-04-18 15:25:25 -07001749 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001750 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001751 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001752 } catch (Exception e) {
1753 // You shall not crash!
1754 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001755 }
1756 }
1757 }
1758
1759 /**
1760 * Remove data activity tracking when network disconnects.
1761 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001762 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1763 final String iface = networkAgent.linkProperties.getInterfaceName();
1764 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001765
Robert Greenwalt7b816022014-04-18 15:25:25 -07001766 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1767 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001768 try {
1769 // the call fails silently if no idletimer setup for this interface
1770 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001771 } catch (Exception e) {
1772 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001773 }
1774 }
1775 }
1776
1777 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001778 * Reads the network specific MTU size from reources.
1779 * and set it on it's iface.
1780 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001781 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1782 final String iface = newLp.getInterfaceName();
1783 final int mtu = newLp.getMtu();
1784 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1785 if (VDBG) log("identical MTU - not setting");
1786 return;
1787 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001788
Robert Greenwalt43074032014-08-15 17:53:05 -07001789 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001790 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001791 return;
1792 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001793
w1997615afd812014-08-05 15:18:11 -07001794 // Cannot set MTU without interface name
1795 if (TextUtils.isEmpty(iface)) {
1796 loge("Setting MTU size with null iface.");
1797 return;
1798 }
1799
Robert Greenwalt7b816022014-04-18 15:25:25 -07001800 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001801 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001802 mNetd.setMtu(iface, mtu);
1803 } catch (Exception e) {
1804 Slog.e(TAG, "exception in setMtu()" + e);
1805 }
1806 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001807
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001808 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001809 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1810
1811 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001812 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001813 protected int getDefaultTcpRwnd() {
1814 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1815 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001816
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001817 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1818 if (isDefaultNetwork(nai) == false) {
1819 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001820 }
1821
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001822 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1823 String[] values = null;
1824 if (tcpBufferSizes != null) {
1825 values = tcpBufferSizes.split(",");
1826 }
1827
1828 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001829 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001830 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1831 values = tcpBufferSizes.split(",");
1832 }
1833
1834 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1835
1836 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001837 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001838
1839 final String prefix = "/sys/kernel/ipv4/tcp_";
1840 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1841 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1842 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1843 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1844 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1845 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1846 mCurrentTcpBufferSizes = tcpBufferSizes;
1847 } catch (IOException e) {
1848 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001849 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001850
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001851 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001852 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001853 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1854 if (rwndValue != 0) {
1855 SystemProperties.set(sysctlKey, rwndValue.toString());
1856 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001857 }
1858
Mattias Falk8b47b362011-08-23 14:15:13 +02001859 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001860 /*
1861 * Tell the VMs to toss their DNS caches
1862 */
1863 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1864 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001865 /*
1866 * Connectivity events can happen before boot has completed ...
1867 */
1868 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001869 final long ident = Binder.clearCallingIdentity();
1870 try {
1871 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1872 } finally {
1873 Binder.restoreCallingIdentity(ident);
1874 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001875 }
1876
Robert Greenwalt562cc542014-05-15 18:07:26 -07001877 @Override
1878 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001879 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1880 NETWORK_RESTORE_DELAY_PROP_NAME);
1881 if(restoreDefaultNetworkDelayStr != null &&
1882 restoreDefaultNetworkDelayStr.length() != 0) {
1883 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001884 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001885 } catch (NumberFormatException e) {
1886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001888 // if the system property isn't set, use the value for the apn type
1889 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1890
1891 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1892 (mNetConfigs[networkType] != null)) {
1893 ret = mNetConfigs[networkType].restoreTime;
1894 }
1895 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 }
1897
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001898 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001899 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001900 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001901 }
1902 return false;
1903 }
1904
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001905 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1906 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1907 final long DIAG_TIME_MS = 5000;
1908 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1909 // Start gathering diagnostic information.
1910 netDiags.add(new NetworkDiagnostics(
1911 nai.network,
1912 new LinkProperties(nai.linkProperties), // Must be a copy.
1913 DIAG_TIME_MS));
1914 }
1915
1916 for (NetworkDiagnostics netDiag : netDiags) {
1917 pw.println();
1918 netDiag.waitForMeasurements();
1919 netDiag.dump(pw);
1920 }
1921 }
1922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001924 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1925 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001926 if (mContext.checkCallingOrSelfPermission(
1927 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001929 pw.println("Permission Denial: can't dump ConnectivityService " +
1930 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1931 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 return;
1933 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001934
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001935 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001936 dumpNetworkDiagnostics(pw);
1937 return;
1938 }
Erik Kline379747a2015-06-05 17:47:34 +09001939
Lorenzo Colittie3805462015-06-03 11:18:24 +09001940 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001941 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001942 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001943 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001944 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001945 pw.println();
1946
Paul Jensen85cf78e2015-06-25 13:25:07 -04001947 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001948 pw.print("Active default network: ");
1949 if (defaultNai == null) {
1950 pw.println("none");
1951 } else {
1952 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001954 pw.println();
1955
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001956 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001957 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001958 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1959 pw.println(nai.toString());
1960 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001961 pw.println(String.format("Requests: %d request/%d total",
1962 nai.numRequestNetworkRequests(), nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001963 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001964 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1965 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001966 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001967 pw.decreaseIndent();
1968 pw.println("Lingered:");
1969 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001970 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001971 pw.decreaseIndent();
1972 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001973 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001974 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001975 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001976
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001977 pw.println("Metered Interfaces:");
1978 pw.increaseIndent();
1979 for (String value : mMeteredIfaces) {
1980 pw.println(value);
1981 }
1982 pw.decreaseIndent();
1983 pw.println();
1984
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001985 pw.print("Restrict background: ");
1986 pw.println(mRestrictBackground);
1987 pw.println();
1988
Felipe Leme46c4fc32016-05-04 09:21:43 -07001989 pw.println("Status for known UIDs:");
1990 pw.increaseIndent();
1991 final int size = mUidRules.size();
1992 for (int i = 0; i < size; i++) {
1993 final int uid = mUidRules.keyAt(i);
1994 pw.print("UID=");
1995 pw.print(uid);
1996 final int uidRules = mUidRules.get(uid, RULE_NONE);
1997 pw.print(" rules=");
1998 pw.print(uidRulesToString(uidRules));
1999 pw.println();
2000 }
2001 pw.println();
2002 pw.decreaseIndent();
2003
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002004 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002005 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002006 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2007 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002008 }
2009 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002010 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002011
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002012 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002013
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002014 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002015 pw.print("mNetTransitionWakeLock: currently " +
2016 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2017 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2018 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2019 } else {
2020 pw.println(", last requested never");
2021 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002022 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002023
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002024 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002025 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002026
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002027 pw.println();
2028 mKeepaliveTracker.dump(pw);
2029
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002030 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002031
Lorenzo Colittie3805462015-06-03 11:18:24 +09002032 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002033 pw.println();
2034 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002035 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002036 for(int i = 0; i < mInetLog.size(); i++) {
2037 pw.println(mInetLog.get(i));
2038 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002039 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002040 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002041
2042 if (argsContain(args, "--short") == false) {
2043 pw.println();
2044 synchronized (mValidationLogs) {
2045 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002046 for (ValidationLog p : mValidationLogs) {
2047 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002048 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002049 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002050 pw.decreaseIndent();
2051 }
2052 }
Erik Kline7523eb32015-07-09 18:24:03 +09002053
2054 pw.println();
2055 pw.println("mNetworkRequestInfoLogs (most recent first):");
2056 pw.increaseIndent();
2057 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2058 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002059
2060 pw.println();
2061 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2062 pw.increaseIndent();
2063 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2064 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 }
2067
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002068 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002069 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002070 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002071 if (officialNai != null && officialNai.equals(nai)) return true;
2072 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002073 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002074 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002075 " - " + nai);
2076 }
2077 return false;
2078 }
2079
Robert Greenwalt42acef32009-08-12 16:08:25 -07002080 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002081 private class NetworkStateTrackerHandler extends Handler {
2082 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002083 super(looper);
2084 }
2085
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002086 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002088 default:
2089 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002090 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002091 handleAsyncChannelHalfConnect(msg);
2092 break;
2093 }
2094 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2095 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2096 if (nai != null) nai.asyncChannel.disconnect();
2097 break;
2098 }
2099 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2100 handleAsyncChannelDisconnected(msg);
2101 break;
2102 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002103 }
2104 return true;
2105 }
2106
2107 private void maybeHandleNetworkAgentMessage(Message msg) {
2108 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2109 if (nai == null) {
2110 if (VDBG) {
2111 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2112 log(String.format("%s from unknown NetworkAgent", what));
2113 }
2114 return;
2115 }
2116
2117 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002118 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002119 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2120 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2121 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2122 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002123 }
Robin Lee585e2482016-05-01 23:00:00 +01002124 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002125 networkCapabilities)) {
2126 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2127 + nai.networkCapabilities + " -> " + networkCapabilities);
2128 }
2129 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002130 break;
2131 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002133 if (VDBG) {
2134 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002135 "; created=" + nai.created +
2136 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002137 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002138 LinkProperties oldLp = nai.linkProperties;
2139 synchronized (nai) {
2140 nai.linkProperties = (LinkProperties)msg.obj;
2141 }
Robin Lee585e2482016-05-01 23:00:00 +01002142 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 break;
2144 }
2145 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002146 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002147 updateNetworkInfo(nai, info);
2148 break;
2149 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002150 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002151 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002152 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002153 break;
2154 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002155 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002156 try {
2157 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002158 } catch (Exception e) {
2159 // Never crash!
2160 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002161 }
2162 break;
2163 }
2164 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002165 try {
2166 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002167 } catch (Exception e) {
2168 // Never crash!
2169 loge("Exception in removeVpnUidRanges: " + e);
2170 }
2171 break;
2172 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002173 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002174 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2175 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002176 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002177 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002178 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002179 break;
2180 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002181 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002182 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2183 break;
2184 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002185 }
2186 }
2187
2188 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2189 switch (msg.what) {
2190 default:
2191 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002192 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002193 final NetworkAgentInfo nai;
2194 synchronized (mNetworkForNetId) {
2195 nai = mNetworkForNetId.get(msg.arg2);
2196 }
2197 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002198 final boolean valid =
2199 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002200 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2201 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002202 if (valid != nai.lastValidated) {
2203 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002204 nai.lastValidated = valid;
2205 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002206 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002207 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2208 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002209 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002210 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002211 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002212 Bundle redirectUrlBundle = new Bundle();
2213 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002214 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002215 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002216 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002217 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002218 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002219 break;
2220 }
Paul Jensen869868be2014-05-15 10:33:05 -04002221 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002222 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002223 final boolean visible = (msg.arg1 != 0);
2224 final NetworkAgentInfo nai;
2225 synchronized (mNetworkForNetId) {
2226 nai = mNetworkForNetId.get(netId);
2227 }
2228 // If captive portal status has changed, update capabilities.
2229 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2230 nai.lastCaptivePortalDetected = visible;
2231 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002232 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002233 }
2234 if (!visible) {
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +09002235 mNotifier.setProvNotificationVisibleIntent(false, netId, null, 0, null,
2236 null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002237 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002238 if (nai == null) {
2239 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2240 break;
2241 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002242 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +09002243 mNotifier.setProvNotificationVisibleIntent(true, netId,
2244 NotificationType.SIGN_IN,
fionaxu1bf6ec22016-05-23 16:33:16 -07002245 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2246 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
2247 }
Paul Jensen869868be2014-05-15 10:33:05 -04002248 }
Paul Jensen869868be2014-05-15 10:33:05 -04002249 break;
2250 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002251 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002252 return true;
2253 }
2254
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002255 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2256 switch (msg.what) {
2257 default:
2258 return false;
2259 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2260 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2261 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2262 handleLingerComplete(nai);
2263 }
2264 break;
2265 }
2266 }
2267 return true;
2268 }
2269
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002270 @Override
2271 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002272 if (!maybeHandleAsyncChannelMessage(msg) &&
2273 !maybeHandleNetworkMonitorMessage(msg) &&
2274 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002275 maybeHandleNetworkAgentMessage(msg);
2276 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002277 }
2278 }
2279
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002280 private void updateLingerState(NetworkAgentInfo nai, long now) {
2281 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2282 // 2. If the network was lingering and there are now requests, unlinger it.
2283 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2284 // one lingered request, start lingering.
2285 nai.updateLingerTimer();
2286 if (nai.isLingering() && nai.numRequestNetworkRequests() > 0) {
2287 if (DBG) log("Unlingering " + nai.name());
2288 nai.unlinger();
2289 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
2290 } else if (unneeded(nai) && nai.getLingerExpiry() > 0) { // unneeded() calls isLingering()
2291 int lingerTime = (int) (nai.getLingerExpiry() - now);
2292 if (DBG) {
2293 Log.d(TAG, "Lingering " + nai.name() + " for " + lingerTime + "ms");
2294 }
2295 nai.linger();
2296 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2297 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2298 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002299 }
2300
Robert Greenwalt7b816022014-04-18 15:25:25 -07002301 private void handleAsyncChannelHalfConnect(Message msg) {
2302 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002303 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002304 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2305 if (VDBG) log("NetworkFactory connected");
2306 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002307 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002308 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002309 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002310 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002311 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002312 }
2313 } else {
2314 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002315 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002316 }
2317 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2318 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2319 if (VDBG) log("NetworkAgent connected");
2320 // A network agent has requested a connection. Establish the connection.
2321 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2322 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2323 } else {
2324 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002325 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002326 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002327 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002328 synchronized (mNetworkForNetId) {
2329 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002330 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002331 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002332 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002333 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002334 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002335 }
2336 }
2337 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002338
Robert Greenwalt7b816022014-04-18 15:25:25 -07002339 private void handleAsyncChannelDisconnected(Message msg) {
2340 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2341 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002342 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002343 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002344 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002345 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002346 // TODO - if we move the logic to the network agent (have them disconnect
2347 // because they lost all their requests or because their score isn't good)
2348 // then they would disconnect organically, report their new state and then
2349 // disconnect the channel.
2350 if (nai.networkInfo.isConnected()) {
2351 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2352 null, null);
2353 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002354 final boolean wasDefault = isDefaultNetwork(nai);
2355 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002356 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002357 // Log default network disconnection before required book-keeping.
2358 // Let rematchAllNetworksAndRequests() below record a new default network event
2359 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2360 // whose timestamps tell how long it takes to recover a default network.
2361 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002362 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002363 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002364 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2365 // by other networks that are already connected. Perhaps that can be done by
2366 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2367 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002368 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002369 mKeepaliveTracker.handleStopAllKeepalives(nai,
2370 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002371 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002372 mNetworkAgentInfos.remove(msg.replyTo);
2373 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002374 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002375 // Remove the NetworkAgent, but don't mark the netId as
2376 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002377 mNetworkForNetId.remove(nai.network.netId);
2378 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002379 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002380 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2381 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002382 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2383 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2384 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002385 sendUpdatedScoreToFactories(request, 0);
2386 }
2387 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002388 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002389 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002390 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002391 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002392 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002393 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002394 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002395 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002396 if (nai.created) {
2397 // Tell netd to clean up the configuration for this network
2398 // (routing rules, DNS, etc).
2399 // This may be slow as it requires a lot of netd shelling out to ip and
2400 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2401 // after we've rematched networks with requests which should make a potential
2402 // fallback network the default or requested a new network from the
2403 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2404 // long time.
2405 try {
2406 mNetd.removeNetwork(nai.network.netId);
2407 } catch (Exception e) {
2408 loge("Exception removing network: " + e);
2409 }
2410 }
2411 synchronized (mNetworkForNetId) {
2412 mNetIdInUse.delete(nai.network.netId);
2413 }
2414 } else {
2415 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2416 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002417 }
2418 }
2419
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002420 // If this method proves to be too slow then we can maintain a separate
2421 // pendingIntent => NetworkRequestInfo map.
2422 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2423 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2424 Intent intent = pendingIntent.getIntent();
2425 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2426 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2427 if (existingPendingIntent != null &&
2428 existingPendingIntent.getIntent().filterEquals(intent)) {
2429 return entry.getValue();
2430 }
2431 }
2432 return null;
2433 }
2434
2435 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2436 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2437
2438 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2439 if (existingRequest != null) { // remove the existing request.
2440 if (DBG) log("Replacing " + existingRequest.request + " with "
2441 + nri.request + " because their intents matched.");
2442 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2443 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002444 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002445 }
2446
Erik Klineda4bfa82015-04-30 12:58:40 +09002447 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002448 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002449 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002450 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002451 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002452 if (nri.request.networkCapabilities.hasSignalStrength() &&
2453 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2454 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002455 }
2456 }
2457 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002458 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002459 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002460 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002461 }
2462 }
2463
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002464 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2465 int callingUid) {
2466 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2467 if (nri != null) {
2468 handleReleaseNetworkRequest(nri.request, callingUid);
2469 }
2470 }
2471
Paul Jensen99364842014-12-09 11:43:45 -05002472 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002473 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2474 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002475 private boolean unneeded(NetworkAgentInfo nai) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002476 if (!nai.everConnected || nai.isVPN() ||
2477 nai.isLingering() || nai.numRequestNetworkRequests() > 0) {
2478 return false;
2479 }
Paul Jensene0988542015-06-25 15:30:08 -04002480 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2481 // If this Network is already the highest scoring Network for a request, or if
2482 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002483 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002484 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002485 // Note that this catches two important cases:
2486 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2487 // is currently satisfying the request. This is desirable when
2488 // cellular ends up validating but WiFi does not.
2489 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002490 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002491 // WiFi ends up validating and out scoring cellular.
2492 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2493 nai.getCurrentScoreAsValidated())) {
2494 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002495 }
2496 }
Paul Jensene0988542015-06-25 15:30:08 -04002497 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002498 }
2499
Erik Klineacdd6392016-07-07 16:50:58 +09002500 private NetworkRequestInfo getNriForAppRequest(
2501 NetworkRequest request, int callingUid, String requestedOperation) {
2502 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2503
Robert Greenwalt9258c642014-03-26 16:47:06 -07002504 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002505 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002506 log(String.format("UID %d attempted to %s for unowned request %s",
2507 callingUid, requestedOperation, nri));
2508 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002509 }
Erik Klineacdd6392016-07-07 16:50:58 +09002510 }
2511
2512 return nri;
2513 }
2514
2515 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2516 String description, int callbackType) {
2517 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2518 if (nri == null) return;
2519
2520 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2521 // The network that is satisfying this request may have changed since
2522 // the application requested the update.
2523 //
2524 // - If the request is no longer satisfied, don't send any updates.
2525 // - If the request is satisfied by a different network, it is the
2526 // caller's responsibility to check that the Network object in the
2527 // callback matches the network that was returned in the last
2528 // onAvailable() callback for this request.
2529 if (nai == null) return;
2530 callCallbackForRequest(nri, nai, callbackType, 0);
2531 }
2532
2533 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2534 handleRequestCallbackUpdate(request, callingUid,
2535 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2536 }
2537
2538 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2539 handleRequestCallbackUpdate(request, callingUid,
2540 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2541 }
2542
2543 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2544 final NetworkRequestInfo nri = getNriForAppRequest(
2545 request, callingUid, "release NetworkRequest");
2546 if (nri == null) return;
2547
2548 if (VDBG || (DBG && nri.request.isRequest())) log("releasing " + request);
2549 nri.unlinkDeathRecipient();
2550 mNetworkRequests.remove(request);
2551 synchronized (mUidToNetworkRequestCount) {
2552 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2553 if (requests < 1) {
2554 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2555 nri.mUid);
2556 } else if (requests == 1) {
2557 mUidToNetworkRequestCount.removeAt(
2558 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2559 } else {
2560 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2561 }
2562 }
2563 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2564 if (nri.request.isRequest()) {
2565 boolean wasKept = false;
2566 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2567 if (nai != null) {
2568 nai.removeRequest(nri.request.requestId);
2569 if (VDBG) {
2570 log(" Removing from current network " + nai.name() +
2571 ", leaving " + nai.numNetworkRequests() + " requests.");
2572 }
2573 // If there are still lingered requests on this network, don't tear it down,
2574 // but resume lingering instead.
2575 updateLingerState(nai, SystemClock.elapsedRealtime());
2576 if (unneeded(nai)) {
2577 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2578 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002579 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002580 wasKept = true;
2581 }
2582 mNetworkForRequestId.remove(nri.request.requestId);
2583 }
2584
2585 // TODO: remove this code once we know that the Slog.wtf is never hit.
2586 //
2587 // Find all networks that are satisfying this request and remove the request
2588 // from their request lists.
2589 // TODO - it's my understanding that for a request there is only a single
2590 // network satisfying it, so this loop is wasteful
2591 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2592 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2593 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2594 otherNai.name() + ", but mNetworkAgentInfos says " +
2595 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002596 }
2597 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002598
Erik Klineacdd6392016-07-07 16:50:58 +09002599 // Maintain the illusion. When this request arrived, we might have pretended
2600 // that a network connected to serve it, even though the network was already
2601 // connected. Now that this request has gone away, we might have to pretend
2602 // that the network disconnected. LegacyTypeTracker will generate that
2603 // phantom disconnect for this type.
2604 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2605 boolean doRemove = true;
2606 if (wasKept) {
2607 // check if any of the remaining requests for this network are for the
2608 // same legacy type - if so, don't remove the nai
2609 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2610 NetworkRequest otherRequest = nai.requestAt(i);
2611 if (otherRequest.legacyType == nri.request.legacyType &&
2612 otherRequest.isRequest()) {
2613 if (DBG) log(" still have other legacy request - leaving");
2614 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002615 }
2616 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002617 }
2618
Erik Klineacdd6392016-07-07 16:50:58 +09002619 if (doRemove) {
2620 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002621 }
2622 }
Erik Klineacdd6392016-07-07 16:50:58 +09002623
2624 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2625 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2626 nri.request);
2627 }
2628 } else {
2629 // listens don't have a singular affectedNetwork. Check all networks to see
2630 // if this listen request applies and remove it.
2631 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2632 nai.removeRequest(nri.request.requestId);
2633 if (nri.request.networkCapabilities.hasSignalStrength() &&
2634 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2635 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2636 }
2637 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002638 }
Erik Klineacdd6392016-07-07 16:50:58 +09002639 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002640 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002641
Lorenzo Colitti18660282016-07-04 12:55:44 +09002642 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002643 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2644 enforceConnectivityInternalPermission();
2645 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2646 accept ? 1 : 0, always ? 1: 0, network));
2647 }
2648
2649 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2650 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2651 " accept=" + accept + " always=" + always);
2652
2653 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2654 if (nai == null) {
2655 // Nothing to do.
2656 return;
2657 }
2658
2659 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002660 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002661 return;
2662 }
2663
2664 if (!nai.networkMisc.explicitlySelected) {
2665 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2666 }
2667
2668 if (accept != nai.networkMisc.acceptUnvalidated) {
2669 int oldScore = nai.getCurrentScore();
2670 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002671 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002672 sendUpdatedScoreToFactories(nai);
2673 }
2674
2675 if (always) {
2676 nai.asyncChannel.sendMessage(
2677 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2678 }
2679
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002680 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002681 // Tell the NetworkAgent to not automatically reconnect to the network.
2682 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2683 // Teardown the nework.
2684 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002685 }
2686
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002687 }
2688
2689 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002690 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002691 mHandler.sendMessageDelayed(
2692 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2693 PROMPT_UNVALIDATED_DELAY_MS);
2694 }
2695
2696 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002697 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002698 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2699
2700 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2701 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002702 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002703 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002704 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2705 return;
2706 }
2707
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002708 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002709 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002710 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2711 intent.setClassName("com.android.settings",
2712 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002713
2714 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2715 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
fionaxu1bf6ec22016-05-23 16:33:16 -07002716
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +09002717 mNotifier.setProvNotificationVisibleIntent(true, nai.network.netId,
2718 NotificationType.NO_INTERNET, nai.networkInfo.getType(),
2719 nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002720 }
2721
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002722 private class InternalHandler extends Handler {
2723 public InternalHandler(Looper looper) {
2724 super(looper);
2725 }
2726
2727 @Override
2728 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002729 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002730 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002731 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002732 String causedBy = null;
2733 synchronized (ConnectivityService.this) {
2734 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2735 mNetTransitionWakeLock.isHeld()) {
2736 mNetTransitionWakeLock.release();
2737 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002738 } else {
2739 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002740 }
2741 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002742 if (VDBG) {
2743 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2744 log("Failed to find a new network - expiring NetTransition Wakelock");
2745 } else {
2746 log("NetTransition Wakelock (" +
2747 (causedBy == null ? "unknown" : causedBy) +
2748 " cleared because we found a replacement network");
2749 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002750 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002751 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002752 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002753 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002754 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002755 break;
2756 }
Jason Monkdecd2952013-10-10 14:02:51 -04002757 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002758 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002759 break;
2760 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002761 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002762 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2763 break;
2764 }
2765 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2766 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002767 break;
2768 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002769 case EVENT_REGISTER_NETWORK_AGENT: {
2770 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2771 break;
2772 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002773 case EVENT_REGISTER_NETWORK_REQUEST:
2774 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002775 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002776 break;
2777 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002778 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2779 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002780 handleRegisterNetworkRequestWithIntent(msg);
2781 break;
2782 }
2783 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2784 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2785 break;
2786 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002787 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002788 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002789 break;
2790 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002791 case EVENT_SET_ACCEPT_UNVALIDATED: {
2792 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2793 break;
2794 }
2795 case EVENT_PROMPT_UNVALIDATED: {
2796 handlePromptUnvalidated((Network) msg.obj);
2797 break;
2798 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002799 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2800 handleMobileDataAlwaysOn();
2801 break;
2802 }
Erik Klineacdd6392016-07-07 16:50:58 +09002803 case EVENT_REQUEST_LINKPROPERTIES:
2804 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2805 break;
2806 case EVENT_REQUEST_NETCAPABILITIES:
2807 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2808 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002809 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2810 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2811 mKeepaliveTracker.handleStartKeepalive(msg);
2812 break;
2813 }
2814 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2815 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2816 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2817 int slot = msg.arg1;
2818 int reason = msg.arg2;
2819 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2820 break;
2821 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002822 case EVENT_SYSTEM_READY: {
2823 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2824 nai.networkMonitor.systemReady = true;
2825 }
2826 break;
2827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 }
2829 }
2830 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002831
2832 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002833 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002834 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002835 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002836 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002837 final int status = mTethering.tether(iface);
2838 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2839 try {
2840 mPolicyManager.onTetheringChanged(iface, true);
2841 } catch (RemoteException e) {
2842 }
2843 }
2844 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002845 } else {
2846 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2847 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002848 }
2849
2850 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002851 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002852 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002853 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002854
2855 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002856 final int status = mTethering.untether(iface);
2857 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2858 try {
2859 mPolicyManager.onTetheringChanged(iface, false);
2860 } catch (RemoteException e) {
2861 }
2862 }
2863 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002864 } else {
2865 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2866 }
2867 }
2868
2869 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002870 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002871 public int getLastTetherError(String iface) {
2872 enforceTetherAccessPermission();
2873
2874 if (isTetheringSupported()) {
2875 return mTethering.getLastTetherError(iface);
2876 } else {
2877 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2878 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002879 }
2880
2881 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002882 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002883 public String[] getTetherableUsbRegexs() {
2884 enforceTetherAccessPermission();
2885 if (isTetheringSupported()) {
2886 return mTethering.getTetherableUsbRegexs();
2887 } else {
2888 return new String[0];
2889 }
2890 }
2891
Lorenzo Colitti18660282016-07-04 12:55:44 +09002892 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002893 public String[] getTetherableWifiRegexs() {
2894 enforceTetherAccessPermission();
2895 if (isTetheringSupported()) {
2896 return mTethering.getTetherableWifiRegexs();
2897 } else {
2898 return new String[0];
2899 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002900 }
2901
Lorenzo Colitti18660282016-07-04 12:55:44 +09002902 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002903 public String[] getTetherableBluetoothRegexs() {
2904 enforceTetherAccessPermission();
2905 if (isTetheringSupported()) {
2906 return mTethering.getTetherableBluetoothRegexs();
2907 } else {
2908 return new String[0];
2909 }
2910 }
2911
Lorenzo Colitti18660282016-07-04 12:55:44 +09002912 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002913 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002914 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002915 if (isTetheringSupported()) {
2916 return mTethering.setUsbTethering(enable);
2917 } else {
2918 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2919 }
2920 }
2921
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002922 // TODO - move iface listing, queries, etc to new module
2923 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002924 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002925 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002926 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002927 return mTethering.getTetherableIfaces();
2928 }
2929
Lorenzo Colitti18660282016-07-04 12:55:44 +09002930 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002931 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002932 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002933 return mTethering.getTetheredIfaces();
2934 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002935
Lorenzo Colitti18660282016-07-04 12:55:44 +09002936 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002937 public String[] getTetheringErroredIfaces() {
2938 enforceTetherAccessPermission();
2939 return mTethering.getErroredIfaces();
2940 }
2941
Lorenzo Colitti18660282016-07-04 12:55:44 +09002942 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002943 public String[] getTetheredDhcpRanges() {
2944 enforceConnectivityInternalPermission();
2945 return mTethering.getTetheredDhcpRanges();
2946 }
2947
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002948 // if ro.tether.denied = true we default to no tethering
2949 // gservices could set the secure setting to 1 though to enable it on a build where it
2950 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002951 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002952 public boolean isTetheringSupported() {
2953 enforceTetherAccessPermission();
2954 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002955 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002956 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2957 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002958 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2959 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002960 mTethering.getTetherableWifiRegexs().length != 0 ||
2961 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2962 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002963 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002964
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002965 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002966 public void startTethering(int type, ResultReceiver receiver,
2967 boolean showProvisioningUi) {
2968 ConnectivityManager.enforceTetherChangePermission(mContext);
2969 if (!isTetheringSupported()) {
2970 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2971 return;
2972 }
2973 mTethering.startTethering(type, receiver, showProvisioningUi);
2974 }
2975
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002976 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002977 public void stopTethering(int type) {
2978 ConnectivityManager.enforceTetherChangePermission(mContext);
2979 mTethering.stopTethering(type);
2980 }
2981
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002982 // Called when we lose the default network and have no replacement yet.
2983 // This will automatically be cleared after X seconds or a new default network
2984 // becomes CONNECTED, whichever happens first. The timer is started by the
2985 // first caller and not restarted by subsequent callers.
2986 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002987 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002988 synchronized (this) {
2989 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002990 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002991 mNetTransitionWakeLock.acquire();
2992 mNetTransitionWakeLockCausedBy = forWhom;
2993 }
2994 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002995 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002996 mNetTransitionWakeLockTimeout);
2997 return;
2998 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002999
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003000 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003001 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003002 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003003 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003004 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003005 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003006 }
3007
Lorenzo Colitti18660282016-07-04 12:55:44 +09003008 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003009 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003010 enforceAccessPermission();
3011 enforceInternetPermission();
3012
Paul Jensenbfd17b72015-04-07 12:43:13 -04003013 NetworkAgentInfo nai;
3014 if (network == null) {
3015 nai = getDefaultNetwork();
3016 } else {
3017 nai = getNetworkAgentInfoForNetwork(network);
3018 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003019 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3020 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3021 return;
3022 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003023 // Revalidate if the app report does not match our current validated state.
3024 if (hasConnectivity == nai.lastValidated) return;
3025 final int uid = Binder.getCallingUid();
3026 if (DBG) {
3027 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3028 ") by " + uid);
3029 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003030 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003031 // Validating a network that has not yet connected could result in a call to
3032 // rematchNetworkAndRequests() which is not meant to work on such networks.
3033 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003034
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003035 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003036
3037 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3038 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003039 }
3040
Paul Jensencee9b512015-05-06 07:32:40 -04003041 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003042 // this information is already available as a world read/writable jvm property
3043 // so this API change wouldn't have a benifit. It also breaks the passing
3044 // of proxy info to all the JVMs.
3045 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003046 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003047 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003048 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3049 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003050 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003051 }
3052
Lorenzo Colitti18660282016-07-04 12:55:44 +09003053 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003054 public ProxyInfo getProxyForNetwork(Network network) {
3055 if (network == null) return getDefaultProxy();
3056 final ProxyInfo globalProxy = getGlobalProxy();
3057 if (globalProxy != null) return globalProxy;
3058 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3059 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3060 // caller may not have.
3061 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3062 if (nai == null) return null;
3063 synchronized (nai) {
3064 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3065 if (proxyInfo == null) return null;
3066 return new ProxyInfo(proxyInfo);
3067 }
3068 }
3069
Paul Jensene0bef712014-12-10 15:12:18 -05003070 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3071 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3072 // proxy is null then there is no proxy in place).
3073 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3074 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3075 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3076 proxy = null;
3077 }
3078 return proxy;
3079 }
3080
3081 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3082 // better for determining if a new proxy broadcast is necessary:
3083 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3084 // avoid unnecessary broadcasts.
3085 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3086 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3087 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3088 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3089 // all set.
3090 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3091 a = canonicalizeProxyInfo(a);
3092 b = canonicalizeProxyInfo(b);
3093 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3094 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3095 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3096 }
3097
Jason Monk207900c2014-04-25 15:00:09 -04003098 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003099 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003100
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003101 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003102 if (proxyProperties == mGlobalProxy) return;
3103 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3104 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3105
3106 String host = "";
3107 int port = 0;
3108 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003109 String pacFileUrl = "";
3110 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003111 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003112 if (!proxyProperties.isValid()) {
3113 if (DBG)
3114 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3115 return;
3116 }
Jason Monk207900c2014-04-25 15:00:09 -04003117 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003118 host = mGlobalProxy.getHost();
3119 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003120 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003121 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003122 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003123 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003124 } else {
3125 mGlobalProxy = null;
3126 }
3127 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003128 final long token = Binder.clearCallingIdentity();
3129 try {
3130 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3131 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3132 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3133 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003134 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003135 } finally {
3136 Binder.restoreCallingIdentity(token);
3137 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003138
Jason Monkcf0f97a2014-10-02 15:39:38 -04003139 if (mGlobalProxy == null) {
3140 proxyProperties = mDefaultProxy;
3141 }
3142 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003143 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003144 }
3145
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003146 private void loadGlobalProxy() {
3147 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003148 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3149 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3150 String exclList = Settings.Global.getString(res,
3151 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003152 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3153 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003154 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003155 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003156 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003157 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003158 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003159 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003160 if (!proxyProperties.isValid()) {
3161 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3162 return;
3163 }
3164
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003165 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003166 mGlobalProxy = proxyProperties;
3167 }
3168 }
3169 }
3170
Jason Monk207900c2014-04-25 15:00:09 -04003171 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003172 // this information is already available as a world read/writable jvm property
3173 // so this API change wouldn't have a benifit. It also breaks the passing
3174 // of proxy info to all the JVMs.
3175 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003176 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003177 return mGlobalProxy;
3178 }
3179 }
3180
Jason Monk207900c2014-04-25 15:00:09 -04003181 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003182 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003183 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003184 proxy = null;
3185 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003186 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003187 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003188 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003189 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003190 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3191 return;
3192 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003193
3194 // This call could be coming from the PacManager, containing the port of the local
3195 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3196 // global (to get the correct local port), and send a broadcast.
3197 // TODO: Switch PacManager to have its own message to send back rather than
3198 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003199 if ((mGlobalProxy != null) && (proxy != null)
3200 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003201 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3202 mGlobalProxy = proxy;
3203 sendProxyBroadcast(mGlobalProxy);
3204 return;
3205 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003206 mDefaultProxy = proxy;
3207
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003208 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003209 if (!mDefaultProxyDisabled) {
3210 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003211 }
3212 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003213 }
3214
Paul Jensene0bef712014-12-10 15:12:18 -05003215 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3216 // This method gets called when any network changes proxy, but the broadcast only ever contains
3217 // the default proxy (even if it hasn't changed).
3218 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3219 // world where an app might be bound to a non-default network.
3220 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3221 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3222 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3223
3224 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3225 sendProxyBroadcast(getDefaultProxy());
3226 }
3227 }
3228
Robert Greenwalt434203a2010-10-11 16:00:27 -07003229 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003230 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3231 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003232 if (!TextUtils.isEmpty(proxy)) {
3233 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003234 if (data.length == 0) {
3235 return;
3236 }
3237
Robert Greenwalt434203a2010-10-11 16:00:27 -07003238 String proxyHost = data[0];
3239 int proxyPort = 8080;
3240 if (data.length > 1) {
3241 try {
3242 proxyPort = Integer.parseInt(data[1]);
3243 } catch (NumberFormatException e) {
3244 return;
3245 }
3246 }
Jason Monk207900c2014-04-25 15:00:09 -04003247 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003248 setGlobalProxy(p);
3249 }
3250 }
3251
Jason Monk207900c2014-04-25 15:00:09 -04003252 private void sendProxyBroadcast(ProxyInfo proxy) {
3253 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003254 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003255 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003256 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003257 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3258 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003259 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003260 final long ident = Binder.clearCallingIdentity();
3261 try {
3262 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3263 } finally {
3264 Binder.restoreCallingIdentity(ident);
3265 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003266 }
3267
3268 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003269 final private HashMap<Uri, Integer> mUriEventMap;
3270 final private Context mContext;
3271 final private Handler mHandler;
3272
3273 SettingsObserver(Context context, Handler handler) {
3274 super(null);
3275 mUriEventMap = new HashMap<Uri, Integer>();
3276 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003277 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003278 }
3279
Erik Klineda4bfa82015-04-30 12:58:40 +09003280 void observe(Uri uri, int what) {
3281 mUriEventMap.put(uri, what);
3282 final ContentResolver resolver = mContext.getContentResolver();
3283 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003284 }
3285
3286 @Override
3287 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003288 Slog.wtf(TAG, "Should never be reached.");
3289 }
3290
3291 @Override
3292 public void onChange(boolean selfChange, Uri uri) {
3293 final Integer what = mUriEventMap.get(uri);
3294 if (what != null) {
3295 mHandler.obtainMessage(what.intValue()).sendToTarget();
3296 } else {
3297 loge("No matching event to send for URI=" + uri);
3298 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003299 }
3300 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003301
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003302 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003303 Slog.d(TAG, s);
3304 }
3305
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003306 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003307 Slog.e(TAG, s);
3308 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003309
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003310 private static <T> T checkNotNull(T value, String message) {
3311 if (value == null) {
3312 throw new NullPointerException(message);
3313 }
3314 return value;
3315 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003316
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003317 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003318 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003319 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3320 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3321 *
3322 * @param oldPackage Package name of the application which currently controls VPN, which will
3323 * be replaced. If there is no such application, this should should either be
3324 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3325 * @param newPackage Package name of the application which should gain control of VPN, or
3326 * {@code null} to disable.
3327 * @param userId User for whom to prepare the new VPN.
3328 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003329 * @hide
3330 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003331 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003332 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3333 int userId) {
3334 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003335 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003336
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003337 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003338 Vpn vpn = mVpns.get(userId);
3339 if (vpn != null) {
3340 return vpn.prepare(oldPackage, newPackage);
3341 } else {
3342 return false;
3343 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003344 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003345 }
3346
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003347 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003348 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3349 * This method is used by system-privileged apps.
3350 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3351 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3352 *
3353 * @param packageName The package for which authorization state should change.
3354 * @param userId User for whom {@code packageName} is installed.
3355 * @param authorized {@code true} if this app should be able to start a VPN connection without
3356 * explicit user approval, {@code false} if not.
3357 *
Jeff Davidson05542602014-08-11 14:07:27 -07003358 * @hide
3359 */
3360 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003361 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3362 enforceCrossUserPermission(userId);
3363
Jeff Davidson05542602014-08-11 14:07:27 -07003364 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003365 Vpn vpn = mVpns.get(userId);
3366 if (vpn != null) {
3367 vpn.setPackageAuthorization(packageName, authorized);
3368 }
Jeff Davidson05542602014-08-11 14:07:27 -07003369 }
3370 }
3371
3372 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003373 * Configure a TUN interface and return its file descriptor. Parameters
3374 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003375 * and not available in ConnectivityManager. Permissions are checked in
3376 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003377 * @hide
3378 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003379 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003380 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003381 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003382 int user = UserHandle.getUserId(Binder.getCallingUid());
3383 synchronized(mVpns) {
3384 return mVpns.get(user).establish(config);
3385 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003386 }
3387
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003388 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003389 * Start legacy VPN, controlling native daemons as needed. Creates a
3390 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003391 */
3392 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003393 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003394 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003395 final LinkProperties egress = getActiveLinkProperties();
3396 if (egress == null) {
3397 throw new IllegalStateException("Missing active network connection");
3398 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003399 int user = UserHandle.getUserId(Binder.getCallingUid());
3400 synchronized(mVpns) {
3401 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3402 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003403 }
3404
3405 /**
3406 * Return the information of the ongoing legacy VPN. This method is used
3407 * by VpnSettings and not available in ConnectivityManager. Permissions
3408 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003409 */
3410 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003411 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3412 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003413
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003414 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003415 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003416 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003417 }
3418
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003419 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003420 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3421 * and not available in ConnectivityManager.
3422 */
3423 @Override
3424 public VpnInfo[] getAllVpnInfo() {
3425 enforceConnectivityInternalPermission();
3426 if (mLockdownEnabled) {
3427 return new VpnInfo[0];
3428 }
3429
3430 synchronized(mVpns) {
3431 List<VpnInfo> infoList = new ArrayList<>();
3432 for (int i = 0; i < mVpns.size(); i++) {
3433 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3434 if (info != null) {
3435 infoList.add(info);
3436 }
3437 }
3438 return infoList.toArray(new VpnInfo[infoList.size()]);
3439 }
3440 }
3441
3442 /**
3443 * @return VPN information for accounting, or null if we can't retrieve all required
3444 * information, e.g primary underlying iface.
3445 */
3446 @Nullable
3447 private VpnInfo createVpnInfo(Vpn vpn) {
3448 VpnInfo info = vpn.getVpnInfo();
3449 if (info == null) {
3450 return null;
3451 }
3452 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3453 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3454 // the underlyingNetworks list.
3455 if (underlyingNetworks == null) {
3456 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3457 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3458 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3459 }
3460 } else if (underlyingNetworks.length > 0) {
3461 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3462 if (linkProperties != null) {
3463 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3464 }
3465 }
3466 return info.primaryUnderlyingIface == null ? null : info;
3467 }
3468
3469 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003470 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3471 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003472 * Permissions are checked in Vpn class.
3473 * @hide
3474 */
3475 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003476 public VpnConfig getVpnConfig(int userId) {
3477 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003478 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003479 Vpn vpn = mVpns.get(userId);
3480 if (vpn != null) {
3481 return vpn.getVpnConfig();
3482 } else {
3483 return null;
3484 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003485 }
3486 }
3487
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003488 @Override
3489 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003490 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3491 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3492 return false;
3493 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003494
3495 // Tear down existing lockdown if profile was removed
3496 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3497 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003498 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3499 final VpnProfile profile = VpnProfile.decode(
3500 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003501 if (profile == null) {
3502 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3503 setLockdownTracker(null);
3504 return true;
3505 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003506 int user = UserHandle.getUserId(Binder.getCallingUid());
3507 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003508 Vpn vpn = mVpns.get(user);
3509 if (vpn == null) {
3510 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3511 return false;
3512 }
3513 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003514 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003515 } else {
3516 setLockdownTracker(null);
3517 }
3518
3519 return true;
3520 }
3521
3522 /**
3523 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3524 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3525 */
3526 private void setLockdownTracker(LockdownVpnTracker tracker) {
3527 // Shutdown any existing tracker
3528 final LockdownVpnTracker existing = mLockdownTracker;
3529 mLockdownTracker = null;
3530 if (existing != null) {
3531 existing.shutdown();
3532 }
3533
3534 try {
3535 if (tracker != null) {
3536 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003537 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003538 mLockdownTracker = tracker;
3539 mLockdownTracker.init();
3540 } else {
3541 mNetd.setFirewallEnabled(false);
3542 }
3543 } catch (RemoteException e) {
3544 // ignored; NMS lives inside system_server
3545 }
3546 }
3547
3548 private void throwIfLockdownEnabled() {
3549 if (mLockdownEnabled) {
3550 throw new IllegalStateException("Unavailable in lockdown mode");
3551 }
3552 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003553
Robin Lee244ce8e2016-01-05 18:03:46 +00003554 /**
Robin Lee17e61832016-05-09 13:46:28 +01003555 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3556 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003557 *
Robin Lee17e61832016-05-09 13:46:28 +01003558 * @return {@code true} if the service was started, the service was already connected, or there
3559 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003560 */
Robin Lee17e61832016-05-09 13:46:28 +01003561 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003562 synchronized (mVpns) {
3563 Vpn vpn = mVpns.get(userId);
3564 if (vpn == null) {
3565 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3566 // exists already.
3567 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3568 return false;
3569 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003570
Robin Lee812800c2016-05-13 15:38:08 +01003571 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003572 }
3573 }
3574
3575 @Override
Robin Leedc679712016-05-03 13:23:03 +01003576 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003577 enforceConnectivityInternalPermission();
3578 enforceCrossUserPermission(userId);
3579
3580 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3581 if (LockdownVpnTracker.isEnabled()) {
3582 return false;
3583 }
3584
Robin Lee244ce8e2016-01-05 18:03:46 +00003585 synchronized (mVpns) {
3586 Vpn vpn = mVpns.get(userId);
3587 if (vpn == null) {
3588 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3589 return false;
3590 }
Robin Lee17e61832016-05-09 13:46:28 +01003591 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003592 return false;
3593 }
Robin Lee17e61832016-05-09 13:46:28 +01003594 if (!startAlwaysOnVpn(userId)) {
3595 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003596 return false;
3597 }
Robin Lee17e61832016-05-09 13:46:28 +01003598
Robin Lee812800c2016-05-13 15:38:08 +01003599 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003600 }
3601 return true;
3602 }
3603
3604 @Override
3605 public String getAlwaysOnVpnPackage(int userId) {
3606 enforceConnectivityInternalPermission();
3607 enforceCrossUserPermission(userId);
3608
3609 synchronized (mVpns) {
3610 Vpn vpn = mVpns.get(userId);
3611 if (vpn == null) {
3612 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3613 return null;
3614 }
3615 return vpn.getAlwaysOnPackage();
3616 }
3617 }
3618
Wink Savilleab9321d2013-06-29 21:10:57 -07003619 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003620 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003621 // TODO: Remove? Any reason to trigger a provisioning check?
3622 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003623 }
3624
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003625 /** Location to an updatable file listing carrier provisioning urls.
3626 * An example:
3627 *
3628 * <?xml version="1.0" encoding="utf-8"?>
3629 * <provisioningUrls>
3630 * <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 -07003631 * </provisioningUrls>
3632 */
3633 private static final String PROVISIONING_URL_PATH =
3634 "/data/misc/radio/provisioning_urls.xml";
3635 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003636
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003637 /** XML tag for root element. */
3638 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3639 /** XML tag for individual url */
3640 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003641 /** XML attribute for mcc */
3642 private static final String ATTR_MCC = "mcc";
3643 /** XML attribute for mnc */
3644 private static final String ATTR_MNC = "mnc";
3645
Paul Jensen434dde82015-06-11 09:43:30 -04003646 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003647 FileReader fileReader = null;
3648 XmlPullParser parser = null;
3649 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003650
3651 try {
3652 fileReader = new FileReader(mProvisioningUrlFile);
3653 parser = Xml.newPullParser();
3654 parser.setInput(fileReader);
3655 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3656
3657 while (true) {
3658 XmlUtils.nextElement(parser);
3659
3660 String element = parser.getName();
3661 if (element == null) break;
3662
Paul Jensen434dde82015-06-11 09:43:30 -04003663 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003664 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3665 try {
3666 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3667 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3668 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3669 parser.next();
3670 if (parser.getEventType() == XmlPullParser.TEXT) {
3671 return parser.getText();
3672 }
3673 }
3674 }
3675 } catch (NumberFormatException e) {
3676 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3677 }
3678 }
3679 }
3680 return null;
3681 } catch (FileNotFoundException e) {
3682 loge("Carrier Provisioning Urls file not found");
3683 } catch (XmlPullParserException e) {
3684 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3685 } catch (IOException e) {
3686 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3687 } finally {
3688 if (fileReader != null) {
3689 try {
3690 fileReader.close();
3691 } catch (IOException e) {}
3692 }
3693 }
3694 return null;
3695 }
3696
Wink Saville42d4f082013-07-20 20:31:59 -07003697 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003698 public String getMobileProvisioningUrl() {
3699 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003700 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003701 if (TextUtils.isEmpty(url)) {
3702 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003703 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003704 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003705 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003706 }
Wink Saville8cf35602013-07-10 23:00:07 -07003707 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003708 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003709 String phoneNumber = mTelephonyManager.getLine1Number();
3710 if (TextUtils.isEmpty(phoneNumber)) {
3711 phoneNumber = "0000000000";
3712 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003713 url = String.format(url,
3714 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3715 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003716 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003717 }
3718
Wink Savilleab9321d2013-06-29 21:10:57 -07003719 return url;
3720 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003721
Wink Saville948282b2013-08-29 08:55:16 -07003722 @Override
3723 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003724 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003725 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003726 final long ident = Binder.clearCallingIdentity();
3727 try {
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +09003728 mNotifier.setProvNotificationVisible(visible, networkType, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003729 } finally {
3730 Binder.restoreCallingIdentity(ident);
3731 }
Wink Saville948282b2013-08-29 08:55:16 -07003732 }
Wink Saville7788c612013-08-29 14:57:08 -07003733
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003734 @Override
3735 public void setAirplaneMode(boolean enable) {
3736 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003737 final long ident = Binder.clearCallingIdentity();
3738 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003739 final ContentResolver cr = mContext.getContentResolver();
3740 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3741 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3742 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003743 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003744 } finally {
3745 Binder.restoreCallingIdentity(ident);
3746 }
3747 }
3748
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003749 private void onUserStart(int userId) {
3750 synchronized(mVpns) {
3751 Vpn userVpn = mVpns.get(userId);
3752 if (userVpn != null) {
3753 loge("Starting user already has a VPN");
3754 return;
3755 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003756 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003757 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003758
3759 final ContentResolver cr = mContext.getContentResolver();
3760 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3761 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3762 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3763 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3764 if (alwaysOnPackage != null) {
3765 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3766 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003767 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003768 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3769 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003770 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003771 }
3772
3773 private void onUserStop(int userId) {
3774 synchronized(mVpns) {
3775 Vpn userVpn = mVpns.get(userId);
3776 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003777 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003778 return;
3779 }
Robin Lee17e61832016-05-09 13:46:28 +01003780 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003781 mVpns.delete(userId);
3782 }
3783 }
3784
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003785 private void onUserAdded(int userId) {
3786 synchronized(mVpns) {
3787 final int vpnsSize = mVpns.size();
3788 for (int i = 0; i < vpnsSize; i++) {
3789 Vpn vpn = mVpns.valueAt(i);
3790 vpn.onUserAdded(userId);
3791 }
3792 }
3793 }
3794
3795 private void onUserRemoved(int userId) {
3796 synchronized(mVpns) {
3797 final int vpnsSize = mVpns.size();
3798 for (int i = 0; i < vpnsSize; i++) {
3799 Vpn vpn = mVpns.valueAt(i);
3800 vpn.onUserRemoved(userId);
3801 }
3802 }
3803 }
3804
Robin Lee89e7a692016-02-29 14:38:17 +00003805 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003806 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3807 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3808 updateLockdownVpn();
3809 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003810 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003811 }
3812 }
3813
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003814 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3815 @Override
3816 public void onReceive(Context context, Intent intent) {
3817 final String action = intent.getAction();
3818 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3819 if (userId == UserHandle.USER_NULL) return;
3820
Robin Lee323f29d2016-05-04 16:38:06 +01003821 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003822 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003823 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003824 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003825 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3826 onUserAdded(userId);
3827 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3828 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003829 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3830 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003831 }
3832 }
3833 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003834
Robert Greenwalta67be032014-05-16 15:49:14 -07003835 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3836 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003837 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3838 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003839
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003840 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3841 // Map from UID to number of NetworkRequests that UID has filed.
3842 @GuardedBy("mUidToNetworkRequestCount")
3843 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3844
Robert Greenwalta67be032014-05-16 15:49:14 -07003845 private static class NetworkFactoryInfo {
3846 public final String name;
3847 public final Messenger messenger;
3848 public final AsyncChannel asyncChannel;
3849
3850 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3851 this.name = name;
3852 this.messenger = messenger;
3853 this.asyncChannel = asyncChannel;
3854 }
3855 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003856
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003857 private void ensureNetworkRequestHasType(NetworkRequest request) {
3858 if (request.type == NetworkRequest.Type.NONE) {
3859 throw new IllegalArgumentException(
3860 "All NetworkRequests in ConnectivityService must have a type");
3861 }
3862 }
3863
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003864 /**
3865 * Tracks info about the requester.
3866 * Also used to notice when the calling process dies so we can self-expire
3867 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003868 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003869 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003870 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003871 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003872 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003873 final int mPid;
3874 final int mUid;
3875 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003876
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003877 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003878 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003879 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003880 mPendingIntent = pi;
3881 messenger = null;
3882 mBinder = null;
3883 mPid = getCallingPid();
3884 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003885 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003886 }
3887
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003888 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003889 super();
3890 messenger = m;
3891 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003892 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003893 mBinder = binder;
3894 mPid = getCallingPid();
3895 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003896 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003897 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003898
3899 try {
3900 mBinder.linkToDeath(this, 0);
3901 } catch (RemoteException e) {
3902 binderDied();
3903 }
3904 }
3905
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003906 private void enforceRequestCountLimit() {
3907 synchronized (mUidToNetworkRequestCount) {
3908 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3909 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3910 throw new IllegalArgumentException("Too many NetworkRequests filed");
3911 }
3912 mUidToNetworkRequestCount.put(mUid, networkRequests);
3913 }
3914 }
3915
Robert Greenwalt9258c642014-03-26 16:47:06 -07003916 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003917 if (mBinder != null) {
3918 mBinder.unlinkToDeath(this, 0);
3919 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003920 }
3921
3922 public void binderDied() {
3923 log("ConnectivityService NetworkRequestInfo binderDied(" +
3924 request + ", " + mBinder + ")");
3925 releaseNetworkRequest(request);
3926 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003927
3928 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003929 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003930 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003931 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003932 }
3933
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003934 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3935 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3936 if (badCapability != null) {
3937 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003938 }
3939 }
3940
Erik Kline9d598e12015-07-13 16:37:51 +09003941 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003942 final SortedSet<Integer> thresholds = new TreeSet();
3943 synchronized (nai) {
3944 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3945 if (nri.request.networkCapabilities.hasSignalStrength() &&
3946 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3947 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3948 }
3949 }
3950 }
Erik Kline9d598e12015-07-13 16:37:51 +09003951 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003952 }
3953
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003954 private void updateSignalStrengthThresholds(
3955 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3956 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003957 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003958 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3959
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003960 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003961 String detail;
3962 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3963 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3964 } else {
3965 detail = reason;
3966 }
3967 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3968 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3969 }
3970
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003971 nai.asyncChannel.sendMessage(
3972 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003973 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003974 }
3975
Robert Greenwalt9258c642014-03-26 16:47:06 -07003976 @Override
3977 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003978 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003979 final NetworkRequest.Type type = (networkCapabilities == null)
3980 ? NetworkRequest.Type.TRACK_DEFAULT
3981 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003982 // If the requested networkCapabilities is null, take them instead from
3983 // the default network request. This allows callers to keep track of
3984 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003985 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003986 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3987 enforceAccessPermission();
3988 } else {
3989 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3990 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09003991 // TODO: this is incorrect. We mark the request as metered or not depending on the state
3992 // of the app when the request is filed, but we never change the request if the app
3993 // changes network state. http://b/29964605
3994 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09003995 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003996 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003997
Robert Greenwalt6078b502014-06-11 16:05:07 -07003998 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003999 throw new IllegalArgumentException("Bad timeout specified");
4000 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004001
Etan Cohenddb9ef02015-11-18 10:56:15 -08004002 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4003 .equals(networkCapabilities.getNetworkSpecifier())) {
4004 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4005 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4006 }
4007
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004008 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004009 nextNetworkRequestId(), type);
4010 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004011 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004012
4013 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004014 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004015 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004016 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004017 }
4018 return networkRequest;
4019 }
4020
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004021 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004022 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004023 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004024 } else {
4025 enforceChangePermission();
4026 }
4027 }
4028
fenglub15e72b2015-03-20 11:29:56 -07004029 @Override
fengludb571472015-04-21 17:12:05 -07004030 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004031 enforceAccessPermission();
4032 NetworkAgentInfo nai = null;
4033 if (network == null) {
4034 return false;
4035 }
4036 synchronized (mNetworkForNetId) {
4037 nai = mNetworkForNetId.get(network.netId);
4038 }
4039 if (nai != null) {
4040 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4041 return true;
4042 }
4043 return false;
4044 }
4045
Felipe Lemeee27cab2016-06-20 16:36:29 -07004046 private boolean isSystem(int uid) {
4047 return uid < Process.FIRST_APPLICATION_UID;
4048 }
fenglub15e72b2015-03-20 11:29:56 -07004049
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004050 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004051 final int uid = Binder.getCallingUid();
4052 if (isSystem(uid)) {
4053 return;
4054 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004055 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004056 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004057 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004058 synchronized(mRulesLock) {
4059 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4060 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004061 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4062 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004063 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004064 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004065 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004066 }
4067 }
4068 }
4069
Robert Greenwalt9258c642014-03-26 16:47:06 -07004070 @Override
4071 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4072 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004073 checkNotNull(operation, "PendingIntent cannot be null.");
4074 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4075 enforceNetworkRequestPermissions(networkCapabilities);
4076 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004077 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004078
4079 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004080 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4081 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004082 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004083 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4084 nri));
4085 return networkRequest;
4086 }
4087
Jeremy Joslin79294842014-12-03 17:15:28 -08004088 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4089 mHandler.sendMessageDelayed(
4090 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4091 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4092 }
4093
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004094 @Override
4095 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004096 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004097 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4098 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004099 }
4100
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004101 // In order to implement the compatibility measure for pre-M apps that call
4102 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4103 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4104 // This ensures it has permission to do so.
4105 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4106 if (nc == null) {
4107 return false;
4108 }
4109 int[] transportTypes = nc.getTransportTypes();
4110 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4111 return false;
4112 }
4113 try {
4114 mContext.enforceCallingOrSelfPermission(
4115 android.Manifest.permission.ACCESS_WIFI_STATE,
4116 "ConnectivityService");
4117 } catch (SecurityException e) {
4118 return false;
4119 }
4120 return true;
4121 }
4122
Robert Greenwalt9258c642014-03-26 16:47:06 -07004123 @Override
4124 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4125 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004126 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4127 enforceAccessPermission();
4128 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004129
Erik Kline7523eb32015-07-09 18:24:03 +09004130 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004131 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4132 NetworkRequest.Type.LISTEN);
4133 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004134 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004135
4136 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4137 return networkRequest;
4138 }
4139
4140 @Override
4141 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4142 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004143 checkNotNull(operation, "PendingIntent cannot be null.");
4144 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4145 enforceAccessPermission();
4146 }
4147
Erik Kline7523eb32015-07-09 18:24:03 +09004148 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004149 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4150 NetworkRequest.Type.LISTEN);
4151 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004152 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004153
4154 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004155 }
4156
4157 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004158 public void requestLinkProperties(NetworkRequest networkRequest) {
4159 ensureNetworkRequestHasType(networkRequest);
4160 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4161 mHandler.sendMessage(mHandler.obtainMessage(
4162 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4163 }
4164
4165 @Override
4166 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4167 ensureNetworkRequestHasType(networkRequest);
4168 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4169 mHandler.sendMessage(mHandler.obtainMessage(
4170 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4171 }
4172
4173 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004174 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004175 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004176 mHandler.sendMessage(mHandler.obtainMessage(
4177 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 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 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004266 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4267 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004268 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004269 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004270 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004271 }
4272
4273 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4274 if (VDBG) log("Got NetworkAgent Messenger");
4275 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004276 synchronized (mNetworkForNetId) {
4277 mNetworkForNetId.put(na.network.netId, na);
4278 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004279 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4280 NetworkInfo networkInfo = na.networkInfo;
4281 na.networkInfo = null;
4282 updateNetworkInfo(na, networkInfo);
4283 }
4284
4285 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4286 LinkProperties newLp = networkAgent.linkProperties;
4287 int netId = networkAgent.network.netId;
4288
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004289 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4290 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004291 if (networkAgent.clatd != null) {
4292 networkAgent.clatd.fixupLinkProperties(oldLp);
4293 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004294
Paul Jensen992f2522014-04-28 10:33:11 -04004295 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004296 updateMtu(newLp, oldLp);
4297 // TODO - figure out what to do for clat
4298// for (LinkProperties lp : newLp.getStackedLinks()) {
4299// updateMtu(lp, null);
4300// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004301 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004302
Erik Kline94887872016-04-05 13:30:49 +09004303 updateRoutes(newLp, oldLp, netId);
4304 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004305
Paul Jensen3b759822014-05-13 11:44:01 -04004306 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004307 if (isDefaultNetwork(networkAgent)) {
4308 handleApplyDefaultProxy(newLp.getHttpProxy());
4309 } else {
4310 updateProxy(newLp, oldLp, networkAgent);
4311 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004312 // TODO - move this check to cover the whole function
4313 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004314 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004315 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4316 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004317
4318 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004319 }
4320
Lorenzo Colitti95439462014-10-09 13:44:48 +09004321 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4322 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4323 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004324
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004325 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004326 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4327 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004328 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004329 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004330 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004331 }
Paul Jensen992f2522014-04-28 10:33:11 -04004332
4333 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4334 CompareResult<String> interfaceDiff = new CompareResult<String>();
4335 if (oldLp != null) {
4336 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4337 } else if (newLp != null) {
4338 interfaceDiff.added = newLp.getAllInterfaceNames();
4339 }
4340 for (String iface : interfaceDiff.added) {
4341 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004342 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004343 mNetd.addInterfaceToNetwork(iface, netId);
4344 } catch (Exception e) {
4345 loge("Exception adding interface: " + e);
4346 }
4347 }
4348 for (String iface : interfaceDiff.removed) {
4349 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004350 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004351 mNetd.removeInterfaceFromNetwork(iface, netId);
4352 } catch (Exception e) {
4353 loge("Exception removing interface: " + e);
4354 }
4355 }
4356 }
4357
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004358 /**
4359 * Have netd update routes from oldLp to newLp.
4360 * @return true if routes changed between oldLp and newLp
4361 */
4362 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004363 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4364 if (oldLp != null) {
4365 routeDiff = oldLp.compareAllRoutes(newLp);
4366 } else if (newLp != null) {
4367 routeDiff.added = newLp.getAllRoutes();
4368 }
4369
4370 // add routes before removing old in case it helps with continuous connectivity
4371
4372 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4373 for (RouteInfo route : routeDiff.added) {
4374 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004375 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004376 try {
4377 mNetd.addRoute(netId, route);
4378 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004379 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4380 loge("Exception in addRoute for non-gateway: " + e);
4381 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004382 }
4383 }
4384 for (RouteInfo route : routeDiff.added) {
4385 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004386 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004387 try {
4388 mNetd.addRoute(netId, route);
4389 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004390 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4391 loge("Exception in addRoute for gateway: " + e);
4392 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004393 }
4394 }
4395
4396 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004397 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004398 try {
4399 mNetd.removeRoute(netId, route);
4400 } catch (Exception e) {
4401 loge("Exception in removeRoute: " + e);
4402 }
4403 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004404 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004405 }
Erik Kline41368502015-06-17 13:19:54 +09004406
Erik Kline94887872016-04-05 13:30:49 +09004407 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4408 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4409 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004410 }
Erik Kline94887872016-04-05 13:30:49 +09004411
4412 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004413 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004414 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004415 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004416 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4417 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004418 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004419 }
4420 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4421 if (defaultNai != null && defaultNai.network.netId == netId) {
4422 setDefaultDnsSystemProperties(dnses);
4423 }
4424 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004425 }
4426
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004427 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4428 int last = 0;
4429 for (InetAddress dns : dnses) {
4430 ++last;
4431 String key = "net.dns" + last;
4432 String value = dns.getHostAddress();
4433 SystemProperties.set(key, value);
4434 }
4435 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4436 String key = "net.dns" + i;
4437 SystemProperties.set(key, "");
4438 }
4439 mNumDnsEntries = last;
4440 }
4441
Paul Jensen3d194ea2015-06-16 14:27:36 -04004442 /**
4443 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4444 * augmented with any stateful capabilities implied from {@code networkAgent}
4445 * (e.g., validated status and captive portal status).
4446 *
Paul Jensene0988542015-06-25 15:30:08 -04004447 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004448 * @param networkCapabilities the new network capabilities.
4449 */
Paul Jensene0988542015-06-25 15:30:08 -04004450 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004451 // Don't modify caller's NetworkCapabilities.
4452 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004453 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004454 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4455 } else {
4456 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4457 }
Paul Jensene0988542015-06-25 15:30:08 -04004458 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004459 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4460 } else {
4461 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4462 }
Paul Jensene0988542015-06-25 15:30:08 -04004463 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4464 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004465 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4466 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4467 try {
4468 mNetd.setNetworkPermission(nai.network.netId,
4469 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4470 null : NetworkManagementService.PERMISSION_SYSTEM);
4471 } catch (RemoteException e) {
4472 loge("Exception in setNetworkPermission: " + e);
4473 }
4474 }
Paul Jensene0988542015-06-25 15:30:08 -04004475 synchronized (nai) {
4476 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004477 }
Paul Jensene0988542015-06-25 15:30:08 -04004478 rematchAllNetworksAndRequests(nai, oldScore);
4479 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004480 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004481 }
4482
Paul Jensenc8b9a742014-09-30 15:37:41 -04004483 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004484 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4485 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004486 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004487 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004488 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4489 }
4490 }
4491
Robert Greenwalt7b816022014-04-18 15:25:25 -07004492 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4493 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004494 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004495 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4496 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004497 }
4498 }
4499
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004500 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4501 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004502 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004503 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004504 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4505 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004506 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004507 sendIntent(nri.mPendingIntent, intent);
4508 }
4509 // else not handled
4510 }
4511
4512 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4513 mPendingIntentWakeLock.acquire();
4514 try {
4515 if (DBG) log("Sending " + pendingIntent);
4516 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4517 } catch (PendingIntent.CanceledException e) {
4518 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4519 mPendingIntentWakeLock.release();
4520 releasePendingNetworkRequest(pendingIntent);
4521 }
4522 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4523 }
4524
4525 @Override
4526 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4527 String resultData, Bundle resultExtras) {
4528 if (DBG) log("Finished sending " + pendingIntent);
4529 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004530 // Release with a delay so the receiving client has an opportunity to put in its
4531 // own request.
4532 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004533 }
4534
Robert Greenwalt9258c642014-03-26 16:47:06 -07004535 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004536 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004537 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004538 Bundle bundle = new Bundle();
4539 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4540 new NetworkRequest(nri.request));
4541 Message msg = Message.obtain();
4542 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4543 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4544 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4545 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004546 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004547 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004548 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004549 break;
4550 }
4551 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4552 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4553 new NetworkCapabilities(networkAgent.networkCapabilities));
4554 break;
4555 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004556 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004557 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4558 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004559 break;
4560 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004561 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004562 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004563 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004564 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004565 if (VDBG) {
4566 log("sending notification " + notifyTypeToName(notificationType) +
4567 " for " + nri.request);
4568 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004569 nri.messenger.send(msg);
4570 } catch (RemoteException e) {
4571 // may occur naturally in the race of binder death.
4572 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4573 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004574 }
4575
Paul Jensenc8b9a742014-09-30 15:37:41 -04004576 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004577 if (nai.numRequestNetworkRequests() != 0) {
4578 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4579 NetworkRequest nr = nai.requestAt(i);
4580 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004581 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004582 loge("Dead network still had at least " + nr);
4583 break;
4584 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004585 }
4586 nai.asyncChannel.disconnect();
4587 }
4588
Robert Greenwalt7b816022014-04-18 15:25:25 -07004589 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4590 if (oldNetwork == null) {
4591 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4592 return;
4593 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004594 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004595
4596 // If we get here it means that the last linger timeout for this network expired. So there
4597 // must be no other active linger timers, and we must stop lingering.
4598 oldNetwork.clearLingerState();
4599
4600 if (unneeded(oldNetwork)) {
4601 teardownUnneededNetwork(oldNetwork);
4602 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004603 }
4604
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004605 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004606 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004607 setupDataActivityTracking(newNetwork);
4608 try {
4609 mNetd.setDefaultNetId(newNetwork.network.netId);
4610 } catch (Exception e) {
4611 loge("Exception setting default network :" + e);
4612 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004613 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004614 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004615 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004616 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004617 }
4618
Paul Jensen2161a8e2014-09-11 11:00:39 -04004619 // Handles a network appearing or improving its score.
4620 //
4621 // - Evaluates all current NetworkRequests that can be
4622 // satisfied by newNetwork, and reassigns to newNetwork
4623 // any such requests for which newNetwork is the best.
4624 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004625 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004626 // needed. A network is needed if it is the best network for
4627 // one or more NetworkRequests, or if it is a VPN.
4628 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004629 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004630 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004631 //
4632 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4633 // networks that have no chance (i.e. even if validated)
4634 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004635 //
4636 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4637 // it does not remove NetworkRequests that other Networks could better satisfy.
4638 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4639 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4640 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004641 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004642 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004643 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4644 // performed to tear down unvalidated networks that have no chance (i.e. even if
4645 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004646 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004647 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004648 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004649 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004650 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004651 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004652 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004653 // Find and migrate to this Network any NetworkRequests for
4654 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004655 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004656 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004657 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004658 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004659 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4660 final boolean satisfies = newNetwork.satisfies(nri.request);
4661 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004662 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004663 log("Network " + newNetwork.name() + " was already satisfying" +
4664 " request " + nri.request.requestId + ". No change.");
4665 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004666 keep = true;
4667 continue;
4668 }
4669
4670 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004671 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004672 if (satisfies) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004673 if (nri.request.isListen()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004674 // This is not a request, it's a callback listener.
4675 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004676 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004677 continue;
4678 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004679
Robert Greenwalt7b816022014-04-18 15:25:25 -07004680 // next check if it's better than any current network we're using for
4681 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004682 if (VDBG) {
4683 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004684 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4685 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004686 }
4687 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004688 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004689 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004690 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004691 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004692 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004693 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004694 affectedNetworks.add(currentNetwork);
4695 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004696 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004697 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004698 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004699 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004700 if (!newNetwork.addRequest(nri.request)) {
4701 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4702 }
4703 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004704 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004705 // Tell NetworkFactories about the new score, so they can stop
4706 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004707 // TODO - this could get expensive if we have alot of requests for this
4708 // network. Think about if there is a way to reduce this. Push
4709 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004710 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004711 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004712 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004713 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004714 }
4715 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004716 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004717 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4718 // mark it as no longer satisfying "nri". Because networks are processed by
4719 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4720 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4721 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4722 // This means this code doesn't have to handle the case where "currentNetwork" no
4723 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4724 if (DBG) {
4725 log("Network " + newNetwork.name() + " stopped satisfying" +
4726 " request " + nri.request.requestId);
4727 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004728 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004729 if (currentNetwork == newNetwork) {
4730 mNetworkForRequestId.remove(nri.request.requestId);
4731 sendUpdatedScoreToFactories(nri.request, 0);
4732 } else {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004733 if (nri.request.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004734 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4735 newNetwork.name() +
4736 " without updating mNetworkForRequestId or factories!");
4737 }
4738 }
4739 // TODO: technically, sending CALLBACK_LOST here is
4740 // incorrect if nri is a request (not a listen) and there
4741 // is a replacement network currently connected that can
4742 // satisfy it. However, the only capability that can both
4743 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4744 // so this code is only incorrect for a network that loses
4745 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004746 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004747 }
4748 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004749 if (isNewDefault) {
4750 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004751 makeDefault(newNetwork);
4752 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4753 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004754 synchronized (ConnectivityService.this) {
4755 // have a new default network, release the transition wakelock in
4756 // a second if it's held. The second pause is to allow apps
4757 // to reconnect over the new network
4758 if (mNetTransitionWakeLock.isHeld()) {
4759 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4760 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4761 mNetTransitionWakeLockSerialNumber, 0),
4762 1000);
4763 }
4764 }
4765 }
4766
4767 // do this after the default net is switched, but
4768 // before LegacyTypeTracker sends legacy broadcasts
4769 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4770
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004771 // Linger any networks that are no longer needed. This should be done after sending the
4772 // available callback for newNetwork.
4773 for (NetworkAgentInfo nai : affectedNetworks) {
4774 updateLingerState(nai, now);
4775 }
4776 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4777 // does not need to be done in any particular order.
4778 updateLingerState(newNetwork, now);
4779
Paul Jensencf4c2c62015-07-01 14:16:32 -04004780 if (isNewDefault) {
4781 // Maintain the illusion: since the legacy API only
4782 // understands one network at a time, we must pretend
4783 // that the current default network disconnected before
4784 // the new one connected.
4785 if (oldDefaultNetwork != null) {
4786 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4787 oldDefaultNetwork, true);
4788 }
4789 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4790 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4791 notifyLockdownVpn(newNetwork);
4792 }
4793
Robert Greenwalt7b816022014-04-18 15:25:25 -07004794 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004795 // Notify battery stats service about this network, both the normal
4796 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004797 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004798 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004799 final IBatteryStats bs = BatteryStatsService.getService();
4800 final int type = newNetwork.networkInfo.getType();
4801
4802 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4803 bs.noteNetworkInterfaceType(baseIface, type);
4804 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4805 final String stackedIface = stacked.getInterfaceName();
4806 bs.noteNetworkInterfaceType(stackedIface, type);
4807 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4808 }
4809 } catch (RemoteException ignored) {
4810 }
4811
Robert Greenwalt152ed372014-12-17 17:19:53 -08004812 // This has to happen after the notifyNetworkCallbacks as that tickles each
4813 // ConnectivityManager instance so that legacy requests correctly bind dns
4814 // requests to this network. The legacy users are listening for this bcast
4815 // and will generally do a dns request so they can ensureRouteToHost and if
4816 // they do that before the callbacks happen they'll use the default network.
4817 //
4818 // TODO: Is there still a race here? We send the broadcast
4819 // after sending the callback, but if the app can receive the
4820 // broadcast before the callback, it might still break.
4821 //
4822 // This *does* introduce a race where if the user uses the new api
4823 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4824 // they may get old info. Reverse this after the old startUsing api is removed.
4825 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004826 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4827 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004828 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004829 // legacy type tracker filters out repeat adds
4830 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4831 }
4832 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004833
4834 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4835 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4836 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4837 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4838 if (newNetwork.isVPN()) {
4839 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4840 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004841 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004842 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4843 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004844 if (unneeded(nai)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004845 if (nai.getLingerExpiry() > 0) {
4846 // This network has active linger timers and no requests, but is not
4847 // lingering. Linger it.
4848 //
4849 // One way (the only way?) this can happen if this network is unvalidated
4850 // and became unneeded due to another network improving its score to the
4851 // point where this network will no longer be able to satisfy any requests
4852 // even if it validates.
4853 updateLingerState(nai, now);
4854 } else {
4855 if (DBG) log("Reaping " + nai.name());
4856 teardownUnneededNetwork(nai);
4857 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004858 }
4859 }
4860 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004861 }
4862
Paul Jensen1c7ba022015-06-16 14:27:36 -04004863 /**
4864 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4865 * being disconnected.
4866 * @param changed If only one Network's score or capabilities have been modified since the last
4867 * time this function was called, pass this Network in this argument, otherwise pass
4868 * null.
4869 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4870 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4871 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4872 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4873 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004874 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004875 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004876 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4877 // to avoid the slowness. It is not simply enough to process just "changed", for
4878 // example in the case where "changed"'s score decreases and another network should begin
4879 // satifying a NetworkRequest that "changed" currently satisfies.
4880
4881 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4882 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4883 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004884 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04004885 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004886 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004887 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004888 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4889 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4890 // Rematch higher scoring networks first to prevent requests first matching a lower
4891 // scoring network and then a higher scoring network, which could produce multiple
4892 // callbacks and inadvertently unlinger networks.
4893 Arrays.sort(nais);
4894 for (NetworkAgentInfo nai : nais) {
4895 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004896 // Only reap the last time through the loop. Reaping before all rematching
4897 // is complete could incorrectly teardown a network that hasn't yet been
4898 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004899 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004900 : ReapUnvalidatedNetworks.REAP,
4901 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004902 }
4903 }
4904 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004905
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004906 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004907 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004908 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004909 // For now only update icons for default connection.
4910 // TODO: Update WiFi and cellular icons separately. b/17237507
4911 if (!isDefaultNetwork(nai)) return;
4912
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004913 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004914 // Don't repeat publish.
4915 if (newInetCondition == mDefaultInetConditionPublished) return;
4916
4917 mDefaultInetConditionPublished = newInetCondition;
4918 sendInetConditionBroadcast(nai.networkInfo);
4919 }
4920
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004921 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4922 if (mLockdownTracker != null) {
4923 if (nai != null && nai.isVPN()) {
4924 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4925 } else {
4926 mLockdownTracker.onNetworkInfoChanged();
4927 }
4928 }
4929 }
4930
Robert Greenwalt7b816022014-04-18 15:25:25 -07004931 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4932 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004933 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004934 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004935 synchronized (networkAgent) {
4936 oldInfo = networkAgent.networkInfo;
4937 networkAgent.networkInfo = newInfo;
4938 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004939 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004940
4941 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004942 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4943 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4944 notifyIfacesChangedForNetworkStats();
4945 } else if (VDBG) log("ignoring duplicate network state non-change");
4946 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004947 return;
4948 }
4949 if (DBG) {
4950 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4951 (oldInfo == null ? "null" : oldInfo.getState()) +
4952 " to " + state);
4953 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004954
Robin Lee585e2482016-05-01 23:00:00 +01004955 if (!networkAgent.created
4956 && (state == NetworkInfo.State.CONNECTED
4957 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004958 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004959 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004960 if (networkAgent.isVPN()) {
4961 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004962 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4963 (networkAgent.networkMisc == null ||
4964 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004965 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004966 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4967 networkAgent.networkCapabilities.hasCapability(
4968 NET_CAPABILITY_NOT_RESTRICTED) ?
4969 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004970 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004971 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004972 loge("Error creating network " + networkAgent.network.netId + ": "
4973 + e.getMessage());
4974 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004975 }
Paul Jenseneec75412014-08-04 12:21:19 -04004976 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004977 }
4978
4979 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4980 networkAgent.everConnected = true;
4981
Robert Greenwalt7b816022014-04-18 15:25:25 -07004982 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004983 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004984
Paul Jensenca8f16a2014-05-09 12:47:55 -04004985 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004986 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004987
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004988 if (networkAgent.isVPN()) {
4989 // Temporarily disable the default proxy (not global).
4990 synchronized (mProxyLock) {
4991 if (!mDefaultProxyDisabled) {
4992 mDefaultProxyDisabled = true;
4993 if (mGlobalProxy == null && mDefaultProxy != null) {
4994 sendProxyBroadcast(null);
4995 }
4996 }
4997 }
4998 // TODO: support proxy per network.
4999 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005000
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005001 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5002 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5003 // capabilities, so it only needs to be done once on initial connect, not every time the
5004 // network's capabilities change. Note that we do this before rematching the network,
5005 // so we could decide to tear it down immediately afterwards. That's fine though - on
5006 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5007 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005008 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005009
Paul Jensen2161a8e2014-09-11 11:00:39 -04005010 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005011 final long now = SystemClock.elapsedRealtime();
5012 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005013
5014 // This has to happen after matching the requests, because callbacks are just requests.
5015 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005016 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005017 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005018 if (networkAgent.isVPN()) {
5019 synchronized (mProxyLock) {
5020 if (mDefaultProxyDisabled) {
5021 mDefaultProxyDisabled = false;
5022 if (mGlobalProxy == null && mDefaultProxy != null) {
5023 sendProxyBroadcast(mDefaultProxy);
5024 }
5025 }
5026 }
5027 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005028 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5029 state == NetworkInfo.State.SUSPENDED) {
5030 // going into or coming out of SUSPEND: rescore and notify
5031 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005032 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005033 }
5034 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5035 ConnectivityManager.CALLBACK_SUSPENDED :
5036 ConnectivityManager.CALLBACK_RESUMED));
5037 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005038 }
5039 }
5040
Robert Greenwaltac96c522014-06-03 16:43:57 -07005041 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005042 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005043 if (score < 0) {
5044 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5045 "). Bumping score to min of 0");
5046 score = 0;
5047 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005048
Paul Jensen2161a8e2014-09-11 11:00:39 -04005049 final int oldScore = nai.getCurrentScore();
5050 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005051
Paul Jensen85cf78e2015-06-25 13:25:07 -04005052 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005053
Paul Jensenc8b9a742014-09-30 15:37:41 -04005054 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005055 }
5056
Robert Greenwalt9258c642014-03-26 16:47:06 -07005057 // notify only this one new request of the current state
5058 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5059 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005060 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005061 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005062 } else {
5063 sendPendingIntentForRequest(nri, nai, notifyType);
5064 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005065 }
5066
Robert Greenwalt8d482522015-06-24 13:23:42 -07005067 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005068 // The NetworkInfo we actually send out has no bearing on the real
5069 // state of affairs. For example, if the default connection is mobile,
5070 // and a request for HIPRI has just gone away, we need to pretend that
5071 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5072 // the state to DISCONNECTED, even though the network is of type MOBILE
5073 // and is still connected.
5074 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5075 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005076 if (state != DetailedState.DISCONNECTED) {
5077 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005078 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005079 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005080 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005081 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5082 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5083 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5084 if (info.isFailover()) {
5085 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5086 nai.networkInfo.setFailover(false);
5087 }
5088 if (info.getReason() != null) {
5089 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5090 }
5091 if (info.getExtraInfo() != null) {
5092 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5093 }
5094 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005095 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005096 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005097 if (newDefaultAgent != null) {
5098 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5099 newDefaultAgent.networkInfo);
5100 } else {
5101 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5102 }
5103 }
5104 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5105 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005106 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005107 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005108 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005109 }
5110 }
5111 }
5112
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005113 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005114 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005115 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5116 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005117 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5118 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005119 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005120 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005121 } else {
5122 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5123 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005124 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005125 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005126
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005127 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5128 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5129 }
5130
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005131 private String notifyTypeToName(int notifyType) {
5132 switch (notifyType) {
5133 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5134 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5135 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5136 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5137 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5138 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5139 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5140 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5141 }
5142 return "UNKNOWN";
5143 }
5144
Jeff Sharkey69736342014-12-08 14:50:12 -08005145 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005146 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5147 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005148 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005149 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005150 try {
5151 mStatsService.forceUpdateIfaces();
5152 } catch (Exception ignored) {
5153 }
5154 }
5155
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005156 @Override
5157 public boolean addVpnAddress(String address, int prefixLength) {
5158 throwIfLockdownEnabled();
5159 int user = UserHandle.getUserId(Binder.getCallingUid());
5160 synchronized (mVpns) {
5161 return mVpns.get(user).addAddress(address, prefixLength);
5162 }
5163 }
5164
5165 @Override
5166 public boolean removeVpnAddress(String address, int prefixLength) {
5167 throwIfLockdownEnabled();
5168 int user = UserHandle.getUserId(Binder.getCallingUid());
5169 synchronized (mVpns) {
5170 return mVpns.get(user).removeAddress(address, prefixLength);
5171 }
5172 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005173
5174 @Override
5175 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5176 throwIfLockdownEnabled();
5177 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005178 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005179 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005180 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005181 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005182 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005183 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005184 }
5185 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005186 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005187
5188 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005189 public String getCaptivePortalServerUrl() {
5190 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5191 }
5192
5193 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005194 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5195 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5196 enforceKeepalivePermission();
5197 mKeepaliveTracker.startNattKeepalive(
5198 getNetworkAgentInfoForNetwork(network),
5199 intervalSeconds, messenger, binder,
5200 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5201 }
5202
5203 @Override
5204 public void stopKeepalive(Network network, int slot) {
5205 mHandler.sendMessage(mHandler.obtainMessage(
5206 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5207 }
5208
5209 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005210 public void factoryReset() {
5211 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005212
5213 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5214 return;
5215 }
5216
Robin Lee3b3dd942015-05-12 18:14:58 +01005217 final int userId = UserHandle.getCallingUserId();
5218
Stuart Scottf1fb3972015-04-02 18:00:02 -07005219 // Turn airplane mode off
5220 setAirplaneMode(false);
5221
Stuart Scotte3e314d2015-04-20 14:07:45 -07005222 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5223 // Untether
5224 for (String tether : getTetheredIfaces()) {
5225 untether(tether);
5226 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005227 }
5228
Stuart Scotte3e314d2015-04-20 14:07:45 -07005229 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005230 // Remove always-on package
5231 synchronized (mVpns) {
5232 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5233 if (alwaysOnPackage != null) {
5234 setAlwaysOnVpnPackage(userId, null, false);
5235 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5236 }
5237 }
5238
Stuart Scotte3e314d2015-04-20 14:07:45 -07005239 // Turn VPN off
5240 VpnConfig vpnConfig = getVpnConfig(userId);
5241 if (vpnConfig != null) {
5242 if (vpnConfig.legacy) {
5243 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5244 } else {
5245 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5246 // in the future without user intervention.
5247 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005248
Victor Changb04a5ea2016-05-30 20:36:30 +01005249 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005250 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005251 }
5252 }
5253 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005254
5255 @VisibleForTesting
5256 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5257 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5258 return new NetworkMonitor(context, handler, nai, defaultRequest);
5259 }
Erik Kline48f12f22016-04-14 17:30:59 +09005260
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005261 @VisibleForTesting
5262 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5263 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5264 }
5265
Hugo Benichicfddd682016-05-31 16:28:06 +09005266 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005267 int newNetid = NETID_UNSET;
5268 int prevNetid = NETID_UNSET;
5269 int[] transports = new int[0];
5270 boolean hadIPv4 = false;
5271 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005272
Hugo Benichi5f16f762016-04-20 12:09:33 +09005273 if (newNai != null) {
5274 newNetid = newNai.network.netId;
5275 transports = newNai.networkCapabilities.getTransportTypes();
5276 }
5277 if (prevNai != null) {
5278 prevNetid = prevNai.network.netId;
5279 final LinkProperties lp = prevNai.linkProperties;
5280 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5281 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5282 }
5283
Hugo Benichicfddd682016-05-31 16:28:06 +09005284 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5285 }
5286
5287 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5288 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005290}