blob: 1f4427f760c3c197eae585752e8c65b55ad5fcc2 [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;
Amith Yamasani15e472352015-04-24 19:06:07 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070036import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
43import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070046import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090047import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090050import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070058import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070059import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070064import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040070import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040073import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070075import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040076import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070078import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070079import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070080import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Looper;
82import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070083import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070084import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070085import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070086import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070088import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070090import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040091import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070093import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070094import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070095import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070097import android.util.LocalLog;
98import android.util.LocalLog.ReadOnlyLocalLog;
99import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800100import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700101import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500102import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700103import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700104import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Wink Savilleab9321d2013-06-29 21:10:57 -0700106import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400107import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400108import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700109import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700110import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700111import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700112import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800113import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700114import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700115import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700116import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700117import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700118import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700119import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400120import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900121import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900122import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900123import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700124import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400125import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400126import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700127import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800128import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700129import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700130import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700131import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700132import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700133import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700134
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700135import org.xmlpull.v1.XmlPullParser;
136import org.xmlpull.v1.XmlPullParserException;
137
138import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700140import java.io.FileNotFoundException;
141import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700142import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700144import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700145import java.net.InetAddress;
146import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700147import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700148import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700149import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700150import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700151import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700152import java.util.HashSet;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900153import java.util.SortedSet;
154import java.util.TreeSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500155import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700156import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700157import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700158import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700159import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
161/**
162 * @hide
163 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800164public class ConnectivityService extends IConnectivityManager.Stub
165 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700166 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700168 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700169 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
Jake Hamby786e71a2014-02-06 14:43:50 -0800171 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700172
Jeff Sharkey899223b2012-08-04 15:24:58 -0700173 // TODO: create better separation between radio types and network types
174
Robert Greenwalt42acef32009-08-12 16:08:25 -0700175 // how long to wait before switching back to a radio's default network
176 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
177 // system property that can override the above value
178 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
179 "android.telephony.apn-restore";
180
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900181 // How long to wait before putting up a "This network doesn't have an Internet connection,
182 // connect anyway?" dialog after the user selects a network that doesn't validate.
183 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
184
Jeremy Joslin79294842014-12-03 17:15:28 -0800185 // How long to delay to removal of a pending intent based request.
186 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
187 private final int mReleasePendingIntentDelayMs;
188
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800189 private Tethering mTethering;
190
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700191 private final PermissionMonitor mPermissionMonitor;
192
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700193 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700194
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700195 @GuardedBy("mVpns")
196 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700197
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700198 private boolean mLockdownEnabled;
199 private LockdownVpnTracker mLockdownTracker;
200
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700201 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
202 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700203 /** Currently active network rules by UID. */
204 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700205 /** Set of ifaces that are costly. */
206 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700207
Erik Klineda4bfa82015-04-30 12:58:40 +0900208 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700210 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700211 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800213 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
215 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700216 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700218 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800219 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700220 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700221
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700222 private String mCurrentTcpBufferSizes;
223
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700224 private static final int ENABLED = 1;
225 private static final int DISABLED = 0;
226
Paul Jensenb10e37f2014-11-25 12:33:08 -0500227 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400228 // Tear down networks that have no chance (e.g. even if validated) of becoming
229 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500230 // all networks have been rematched against all NetworkRequests.
231 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400232 // Don't reap networks. This should be passed when some networks have not yet been
233 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500234 DONT_REAP
235 };
236
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700238 * used internally to change our mobile data enabled flag
239 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700240 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241
242 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700243 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700244 * from one net to another. Clear happens when we get a new
245 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
246 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700247 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700248 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700249
Robert Greenwalt434203a2010-10-11 16:00:27 -0700250 /**
251 * used internally to reload global proxy settings
252 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700253 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700254
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700255 /**
Wink Saville628b0852011-08-04 15:01:58 -0700256 * used internally to send a sticky broadcast delayed.
257 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700258 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700259
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700260 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400261 * PAC manager has received new port.
262 */
263 private static final int EVENT_PROXY_HAS_CHANGED = 16;
264
Robert Greenwalte049c232014-04-11 15:53:27 -0700265 /**
266 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700267 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700268 */
269 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
270
Robert Greenwalt7b816022014-04-18 15:25:25 -0700271 /**
272 * used internally when registering NetworkAgents
273 * obj = Messenger
274 */
275 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
276
Robert Greenwalt9258c642014-03-26 16:47:06 -0700277 /**
278 * used to add a network request
279 * includes a NetworkRequestInfo
280 */
281 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
282
283 /**
284 * indicates a timeout period is over - check if we had a network yet or not
285 * and if not, call the timeout calback (but leave the request live until they
286 * cancel it.
287 * includes a NetworkRequestInfo
288 */
289 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
290
291 /**
292 * used to add a network listener - no request
293 * includes a NetworkRequestInfo
294 */
295 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
296
297 /**
298 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400299 * arg1 = UID of caller
300 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700301 */
302 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
303
Robert Greenwalta67be032014-05-16 15:49:14 -0700304 /**
305 * used internally when registering NetworkFactories
306 * obj = Messenger
307 */
308 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
309
Robert Greenwalt27711812014-06-25 16:45:57 -0700310 /**
311 * used internally to expire a wakelock when transitioning
312 * from one net to another. Expire happens when we fail to find
313 * a new network (typically after 1 minute) -
314 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
315 * a replacement network.
316 */
317 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
318
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700319 /**
320 * Used internally to indicate the system is ready.
321 */
322 private static final int EVENT_SYSTEM_READY = 25;
323
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800324 /**
325 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400326 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800327 */
328 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
329
330 /**
331 * used to remove a pending intent and its associated network request.
332 * arg1 = UID of caller
333 * obj = PendingIntent
334 */
335 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
336
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900337 /**
338 * used to specify whether a network should be used even if unvalidated.
339 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
340 * arg2 = whether to remember this choice in the future (1 or 0)
341 * obj = network
342 */
343 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
344
345 /**
346 * used to ask the user to confirm a connection to an unvalidated network.
347 * obj = network
348 */
349 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700350
Erik Klineda4bfa82015-04-30 12:58:40 +0900351 /**
352 * used internally to (re)configure mobile data always-on settings.
353 */
354 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
355
Paul Jensen694f2b82015-06-17 14:15:39 -0400356 /**
357 * used to add a network listener with a pending intent
358 * obj = NetworkRequestInfo
359 */
360 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
361
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700362 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700363 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700364 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700365 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700366
Mike Lockwood0f79b542009-08-14 14:18:49 -0400367 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800368 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400369
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700370 private PowerManager.WakeLock mNetTransitionWakeLock;
371 private String mNetTransitionWakeLockCausedBy = "";
372 private int mNetTransitionWakeLockSerialNumber;
373 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800374 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700375
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700376 private InetAddress mDefaultDns;
377
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700378 // used in DBG mode to track inet condition reports
379 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
380 private ArrayList mInetLog;
381
Robert Greenwalt434203a2010-10-11 16:00:27 -0700382 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400383 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700384 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700385 private boolean mDefaultProxyDisabled = false;
386
Robert Greenwalt434203a2010-10-11 16:00:27 -0700387 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400388 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700389
Jason Monk602b2322013-07-03 17:04:33 -0400390 private PacManager mPacManager = null;
391
Erik Klineda4bfa82015-04-30 12:58:40 +0900392 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700393
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400394 private UserManager mUserManager;
395
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700396 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700397 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700398
Robert Greenwalt50393202011-06-21 17:26:14 -0700399 // the set of network types that can only be enabled by system/sig apps
400 List mProtectedNetworks;
401
John Spurlockbf991a82013-06-24 14:20:23 -0400402 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700403
Wink Savilleab9321d2013-06-29 21:10:57 -0700404 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400405
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900406 private KeepaliveTracker mKeepaliveTracker;
407
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700408 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
409 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700410 private final static int MAX_NET_ID = 65535;
411 private int mNextNetId = MIN_NET_ID;
412
Robert Greenwalt34524f02014-05-18 16:22:10 -0700413 // sequence number of NetworkRequests
414 private int mNextNetworkRequestId = 1;
415
Erik Kline7523eb32015-07-09 18:24:03 +0900416 // NetworkRequest activity String log entries.
417 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
418 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
419
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700420 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
421 private static final int MAX_VALIDATION_LOGS = 10;
422 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
423 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
424
425 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
426 synchronized(mValidationLogs) {
427 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
428 mValidationLogs.removeLast();
429 }
430 mValidationLogs.addFirst(new Pair(network, log));
431 }
432 }
433
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700434 /**
435 * Implements support for the legacy "one network per network type" model.
436 *
437 * We used to have a static array of NetworkStateTrackers, one for each
438 * network type, but that doesn't work any more now that we can have,
439 * for example, more that one wifi network. This class stores all the
440 * NetworkAgentInfo objects that support a given type, but the legacy
441 * API will only see the first one.
442 *
443 * It serves two main purposes:
444 *
445 * 1. Provide information about "the network for a given type" (since this
446 * API only supports one).
447 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
448 * the first network for a given type changes, or if the default network
449 * changes.
450 */
451 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900452
453 private static final boolean DBG = true;
454 private static final boolean VDBG = false;
455 private static final String TAG = "CSLegacyTypeTracker";
456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 /**
458 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
459 * Each list holds references to all NetworkAgentInfos that are used to
460 * satisfy requests for that network type.
461 *
462 * This array is built out at startup such that an unsupported network
463 * doesn't get an ArrayList instance, making this a tristate:
464 * unsupported, supported but not active and active.
465 *
466 * The actual lists are populated when we scan the network types that
467 * are supported on this device.
468 */
469 private ArrayList<NetworkAgentInfo> mTypeLists[];
470
471 public LegacyTypeTracker() {
472 mTypeLists = (ArrayList<NetworkAgentInfo>[])
473 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
474 }
475
476 public void addSupportedType(int type) {
477 if (mTypeLists[type] != null) {
478 throw new IllegalStateException(
479 "legacy list for type " + type + "already initialized");
480 }
481 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
482 }
483
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700484 public boolean isTypeSupported(int type) {
485 return isNetworkTypeValid(type) && mTypeLists[type] != null;
486 }
487
488 public NetworkAgentInfo getNetworkForType(int type) {
489 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
490 return mTypeLists[type].get(0);
491 } else {
492 return null;
493 }
494 }
495
Robert Greenwalt8d482522015-06-24 13:23:42 -0700496 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900497 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700499 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900500 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900501 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900502 }
503 }
504
505 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700506 public void add(int type, NetworkAgentInfo nai) {
507 if (!isTypeSupported(type)) {
508 return; // Invalid network type.
509 }
510 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
511
512 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
513 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700514 return;
515 }
516
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900517 list.add(nai);
518
519 // 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 +0900520 final boolean isDefaultNetwork = isDefaultNetwork(nai);
521 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700522 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
523 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700524 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700525 }
526
Lorenzo Colittia793a672014-07-31 23:20:17 +0900527 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900528 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900529 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
530 if (list == null || list.isEmpty()) {
531 return;
532 }
533
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900534 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900535
536 if (!list.remove(nai)) {
537 return;
538 }
539
Robert Greenwalt8d482522015-06-24 13:23:42 -0700540 final DetailedState state = DetailedState.DISCONNECTED;
541
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900542 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700543 maybeLogBroadcast(nai, state, type, wasDefault);
544 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900545 }
546
547 if (!list.isEmpty() && wasFirstNetwork) {
548 if (DBG) log("Other network available for type " + type +
549 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900550 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700551 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
552 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900553 }
554 }
555
556 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900557 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
558 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900560 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
562 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700563
Robert Greenwalt8d482522015-06-24 13:23:42 -0700564 // send out another legacy broadcast - currently only used for suspend/unsuspend
565 // toggle
566 public void update(NetworkAgentInfo nai) {
567 final boolean isDefault = isDefaultNetwork(nai);
568 final DetailedState state = nai.networkInfo.getDetailedState();
569 for (int type = 0; type < mTypeLists.length; type++) {
570 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700571 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700572 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700573 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 maybeLogBroadcast(nai, state, type, isDefault);
575 sendLegacyNetworkBroadcast(nai, state, type);
576 }
577 }
578 }
579
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 private String naiToString(NetworkAgentInfo nai) {
581 String name = (nai != null) ? nai.name() : "null";
582 String state = (nai.networkInfo != null) ?
583 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
584 "???/???";
585 return name + " " + state;
586 }
587
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700588 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900589 pw.println("mLegacyTypeTracker:");
590 pw.increaseIndent();
591 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700592 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900593 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700594 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900595 pw.println();
596 pw.println("Current state:");
597 pw.increaseIndent();
598 for (int type = 0; type < mTypeLists.length; type++) {
599 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
600 for (NetworkAgentInfo nai : mTypeLists[type]) {
601 pw.println(type + " " + naiToString(nai));
602 }
603 }
604 pw.decreaseIndent();
605 pw.decreaseIndent();
606 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700607 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608
609 // This class needs its own log method because it has a different TAG.
610 private void log(String s) {
611 Slog.d(TAG, s);
612 }
613
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700614 }
615 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
616
Jeff Sharkey899223b2012-08-04 15:24:58 -0700617 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700618 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800619 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800620
Erik Klineda4bfa82015-04-30 12:58:40 +0900621 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900622 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
623 new Binder(), NetworkRequestInfo.REQUEST);
624 mNetworkRequests.put(mDefaultRequest, defaultNRI);
625 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900626
627 mDefaultMobileDataRequest = createInternetRequestForTransport(
628 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700629
Wink Savillebb08caf2010-09-02 19:23:52 -0700630 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
631 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700632 mHandler = new InternalHandler(handlerThread.getLooper());
633 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700634
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800635 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800636 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
637 String id = Settings.Secure.getString(context.getContentResolver(),
638 Settings.Secure.ANDROID_ID);
639 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700640 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800641 SystemProperties.set("net.hostname", name);
642 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800643 }
644
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700645 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700646 String dns = Settings.Global.getString(context.getContentResolver(),
647 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700648 if (dns == null || dns.length() == 0) {
649 dns = context.getResources().getString(
650 com.android.internal.R.string.config_default_dns_server);
651 }
652 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800653 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
654 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800655 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700656 }
657
Jeremy Joslin79294842014-12-03 17:15:28 -0800658 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
659 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
660
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700661 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700662 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800663 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700664 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700665 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700666 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700667
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700668 try {
669 mPolicyManager.registerListener(mPolicyListener);
670 } catch (RemoteException e) {
671 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700672 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700673 }
674
675 final PowerManager powerManager = (PowerManager) context.getSystemService(
676 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700677 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
678 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
679 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800680 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700681
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700682 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700683
Wink Saville51f456f2013-04-23 14:26:51 -0700684 // TODO: What is the "correct" way to do determine if this is a wifi only device?
685 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
686 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700687 String[] naStrings = context.getResources().getStringArray(
688 com.android.internal.R.array.networkAttributes);
689 for (String naString : naStrings) {
690 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700691 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700692 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700693 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800694 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700695 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700696 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700697 }
Wink Saville51f456f2013-04-23 14:26:51 -0700698 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
699 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
700 n.type);
701 continue;
702 }
Wink Saville975c8482011-04-07 14:23:45 -0700703 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800704 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700705 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700706 continue;
707 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700708 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700709
Wink Saville975c8482011-04-07 14:23:45 -0700710 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700711 mNetworksDefined++;
712 } catch(Exception e) {
713 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700714 }
715 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700716
717 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
718 if (mNetConfigs[TYPE_VPN] == null) {
719 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
720 // don't need to add TYPE_VPN to mNetConfigs.
721 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
722 mNetworksDefined++; // used only in the log() statement below.
723 }
724
Wink Saville5e56bc52013-07-29 15:00:57 -0700725 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700726
Robert Greenwalt50393202011-06-21 17:26:14 -0700727 mProtectedNetworks = new ArrayList<Integer>();
728 int[] protectedNetworks = context.getResources().getIntArray(
729 com.android.internal.R.array.config_protectedNetworks);
730 for (int p : protectedNetworks) {
731 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
732 mProtectedNetworks.add(p);
733 } else {
734 if (DBG) loge("Ignoring protectedNetwork " + p);
735 }
736 }
737
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700738 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
739 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700740
Robert Greenwaltfab501672014-07-23 11:44:01 -0700741 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800742
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700743 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
744
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700745 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700746 IntentFilter intentFilter = new IntentFilter();
747 intentFilter.addAction(Intent.ACTION_USER_STARTING);
748 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
749 mContext.registerReceiverAsUser(
750 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900751
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700752 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700753 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700754 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700755 } catch (RemoteException e) {
756 loge("Error registering observer :" + e);
757 }
758
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700759 if (DBG) {
760 mInetLog = new ArrayList();
761 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700762
Erik Klineda4bfa82015-04-30 12:58:40 +0900763 mSettingsObserver = new SettingsObserver(mContext, mHandler);
764 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800765
John Spurlockbf991a82013-06-24 14:20:23 -0400766 mDataConnectionStats = new DataConnectionStats(mContext);
767 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400768
Jason Monkdecd2952013-10-10 14:02:51 -0400769 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700770
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400771 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900772
773 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700775
Erik Klineda4bfa82015-04-30 12:58:40 +0900776 private NetworkRequest createInternetRequestForTransport(int transportType) {
777 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900778 netCap.addCapability(NET_CAPABILITY_INTERNET);
779 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900780 if (transportType > -1) {
781 netCap.addTransportType(transportType);
782 }
783 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
784 }
785
786 private void handleMobileDataAlwaysOn() {
787 final boolean enable = (Settings.Global.getInt(
788 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
789 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
790 if (enable == isEnabled) {
791 return; // Nothing to do.
792 }
793
794 if (enable) {
795 handleRegisterNetworkRequest(new NetworkRequestInfo(
796 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
797 } else {
798 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
799 }
800 }
801
802 private void registerSettingsCallbacks() {
803 // Watch for global HTTP proxy changes.
804 mSettingsObserver.observe(
805 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
806 EVENT_APPLY_GLOBAL_HTTP_PROXY);
807
808 // Watch for whether or not to keep mobile data always on.
809 mSettingsObserver.observe(
810 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
811 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
812 }
813
Robert Greenwalt34524f02014-05-18 16:22:10 -0700814 private synchronized int nextNetworkRequestId() {
815 return mNextNetworkRequestId++;
816 }
817
Paul Jensen67b0b072015-06-10 11:22:17 -0400818 @VisibleForTesting
819 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400820 synchronized (mNetworkForNetId) {
821 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
822 int netId = mNextNetId;
823 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
824 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500825 if (!mNetIdInUse.get(netId)) {
826 mNetIdInUse.put(netId, true);
827 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400828 }
829 }
830 }
831 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700832 }
833
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800834 private NetworkState getFilteredNetworkState(int networkType, int uid) {
835 NetworkInfo info = null;
836 LinkProperties lp = null;
837 NetworkCapabilities nc = null;
838 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800839 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800840
841 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
842 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
843 if (nai != null) {
844 synchronized (nai) {
845 info = new NetworkInfo(nai.networkInfo);
846 lp = new LinkProperties(nai.linkProperties);
847 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400848 // Network objects are outwardly immutable so there is no point to duplicating.
849 // Duplicating also precludes sharing socket factories and connection pools.
850 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800851 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800852 }
853 info.setType(networkType);
854 } else {
855 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
856 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
857 info.setIsAvailable(true);
858 lp = new LinkProperties();
859 nc = new NetworkCapabilities();
860 network = null;
861 }
862 info = getFilteredNetworkInfo(info, lp, uid);
863 }
864
Jeff Sharkey32566012014-12-02 18:30:14 -0800865 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400866 }
867
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800868 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
869 if (network == null) {
870 return null;
871 }
872 synchronized (mNetworkForNetId) {
873 return mNetworkForNetId.get(network.netId);
874 }
875 };
876
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900877 private Network[] getVpnUnderlyingNetworks(int uid) {
878 if (!mLockdownEnabled) {
879 int user = UserHandle.getUserId(uid);
880 synchronized (mVpns) {
881 Vpn vpn = mVpns.get(user);
882 if (vpn != null && vpn.appliesToUid(uid)) {
883 return vpn.getUnderlyingNetworks();
884 }
885 }
886 }
887 return null;
888 }
889
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800890 private NetworkState getUnfilteredActiveNetworkState(int uid) {
891 NetworkInfo info = null;
892 LinkProperties lp = null;
893 NetworkCapabilities nc = null;
894 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800895 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800896
Paul Jensen85cf78e2015-06-25 13:25:07 -0400897 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800898
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900899 final Network[] networks = getVpnUnderlyingNetworks(uid);
900 if (networks != null) {
901 // getUnderlyingNetworks() returns:
902 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
903 // empty array => the VPN explicitly said "no default network".
904 // non-empty array => the VPN specified one or more default networks; we use the
905 // first one.
906 if (networks.length > 0) {
907 nai = getNetworkAgentInfoForNetwork(networks[0]);
908 } else {
909 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800910 }
911 }
912
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800913 if (nai != null) {
914 synchronized (nai) {
915 info = new NetworkInfo(nai.networkInfo);
916 lp = new LinkProperties(nai.linkProperties);
917 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400918 // Network objects are outwardly immutable so there is no point to duplicating.
919 // Duplicating also precludes sharing socket factories and connection pools.
920 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800921 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800922 }
923 }
924
Jeff Sharkey32566012014-12-02 18:30:14 -0800925 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400926 }
927
928 /**
929 * Check if UID should be blocked from using the network with the given LinkProperties.
930 */
931 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700932 final boolean networkCostly;
933 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700934
Robert Greenwalt12e67352014-05-13 21:41:06 -0700935 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700936 synchronized (mRulesLock) {
937 networkCostly = mMeteredIfaces.contains(iface);
938 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700939 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700940
Amith Yamasani15e472352015-04-24 19:06:07 -0700941 if ((uidRules & RULE_REJECT_ALL) != 0
942 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700943 return true;
944 }
945
946 // no restrictive rules; network is visible
947 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700948 }
949
950 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700951 * Return a filtered {@link NetworkInfo}, potentially marked
952 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800953 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700954 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800955 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
956 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400957 // network is blocked; clone and override state
958 info = new NetworkInfo(info);
959 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900960 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900961 log("returning Blocked NetworkInfo for ifname=" +
962 lp.getInterfaceName() + ", uid=" + uid);
963 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700964 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800965 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700966 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900967 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700968 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700969 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700970 }
971
972 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 * Return NetworkInfo for the active (i.e., connected) network interface.
974 * It is assumed that at most one network is active at a time. If more
975 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700976 * @return the info for the active network, or {@code null} if none is
977 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700979 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700981 enforceAccessPermission();
982 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800983 NetworkState state = getUnfilteredActiveNetworkState(uid);
984 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 }
986
Paul Jensen31a94f42015-02-13 14:18:39 -0500987 @Override
988 public Network getActiveNetwork() {
989 enforceAccessPermission();
990 final int uid = Binder.getCallingUid();
991 final int user = UserHandle.getUserId(uid);
992 int vpnNetId = NETID_UNSET;
993 synchronized (mVpns) {
994 final Vpn vpn = mVpns.get(user);
995 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
996 }
997 NetworkAgentInfo nai;
998 if (vpnNetId != NETID_UNSET) {
999 synchronized (mNetworkForNetId) {
1000 nai = mNetworkForNetId.get(vpnNetId);
1001 }
1002 if (nai != null) return nai.network;
1003 }
1004 nai = getDefaultNetwork();
1005 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1006 return nai != null ? nai.network : null;
1007 }
1008
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001009 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1010 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001011 final int uid = Binder.getCallingUid();
1012 NetworkState state = getUnfilteredActiveNetworkState(uid);
1013 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001014 }
1015
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001016 @Override
1017 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1018 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001019 NetworkState state = getUnfilteredActiveNetworkState(uid);
1020 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001021 }
1022
1023 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 public NetworkInfo getNetworkInfo(int networkType) {
1025 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001026 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001027 if (getVpnUnderlyingNetworks(uid) != null) {
1028 // A VPN is active, so we may need to return one of its underlying networks. This
1029 // information is not available in LegacyTypeTracker, so we have to get it from
1030 // getUnfilteredActiveNetworkState.
1031 NetworkState state = getUnfilteredActiveNetworkState(uid);
1032 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1033 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1034 }
1035 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001036 NetworkState state = getFilteredNetworkState(networkType, uid);
1037 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
1039
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001040 @Override
1041 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1042 enforceAccessPermission();
1043 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001044 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001045 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1046 if (nai != null) {
1047 synchronized (nai) {
1048 info = new NetworkInfo(nai.networkInfo);
1049 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001050 }
1051 }
1052 return info;
1053 }
1054
1055 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 public NetworkInfo[] getAllNetworkInfo() {
1057 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001058 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001059 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1060 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001061 NetworkInfo info = getNetworkInfo(networkType);
1062 if (info != null) {
1063 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001066 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001069 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001070 public Network getNetworkForType(int networkType) {
1071 enforceAccessPermission();
1072 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001073 NetworkState state = getFilteredNetworkState(networkType, uid);
1074 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1075 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001076 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001077 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001078 }
1079
1080 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001081 public Network[] getAllNetworks() {
1082 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001083 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001084 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001085 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001086 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001087 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001088 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001089 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001090 }
1091
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001092 @Override
1093 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1094 // The basic principle is: if an app's traffic could possibly go over a
1095 // network, without the app doing anything multinetwork-specific,
1096 // (hence, by "default"), then include that network's capabilities in
1097 // the array.
1098 //
1099 // In the normal case, app traffic only goes over the system's default
1100 // network connection, so that's the only network returned.
1101 //
1102 // With a VPN in force, some app traffic may go into the VPN, and thus
1103 // over whatever underlying networks the VPN specifies, while other app
1104 // traffic may go over the system default network (e.g.: a split-tunnel
1105 // VPN, or an app disallowed by the VPN), so the set of networks
1106 // returned includes the VPN's underlying networks and the system
1107 // default.
1108 enforceAccessPermission();
1109
1110 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1111
1112 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001113 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001114 if (nc != null) {
1115 result.put(nai.network, nc);
1116 }
1117
1118 if (!mLockdownEnabled) {
1119 synchronized (mVpns) {
1120 Vpn vpn = mVpns.get(userId);
1121 if (vpn != null) {
1122 Network[] networks = vpn.getUnderlyingNetworks();
1123 if (networks != null) {
1124 for (Network network : networks) {
1125 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001126 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001127 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001128 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001129 }
1130 }
1131 }
1132 }
1133 }
1134 }
1135
1136 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1137 out = result.values().toArray(out);
1138 return out;
1139 }
1140
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001141 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001142 public boolean isNetworkSupported(int networkType) {
1143 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001144 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001145 }
1146
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001147 /**
1148 * Return LinkProperties for the active (i.e., connected) default
1149 * network interface. It is assumed that at most one default network
1150 * is active at a time. If more than one is active, it is indeterminate
1151 * which will be returned.
1152 * @return the ip properties for the active network, or {@code null} if
1153 * none is active
1154 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001155 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001156 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001157 enforceAccessPermission();
1158 final int uid = Binder.getCallingUid();
1159 NetworkState state = getUnfilteredActiveNetworkState(uid);
1160 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001161 }
1162
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001163 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001164 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001165 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001166 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1167 if (nai != null) {
1168 synchronized (nai) {
1169 return new LinkProperties(nai.linkProperties);
1170 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001171 }
1172 return null;
1173 }
1174
Robert Greenwalt12e67352014-05-13 21:41:06 -07001175 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001176 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001177 public LinkProperties getLinkProperties(Network network) {
1178 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001180 if (nai != null) {
1181 synchronized (nai) {
1182 return new LinkProperties(nai.linkProperties);
1183 }
1184 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001185 return null;
1186 }
1187
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001188 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001189 if (nai != null) {
1190 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001191 if (nai.networkCapabilities != null) {
1192 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001193 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001194 }
1195 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001196 return null;
1197 }
1198
1199 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001200 public NetworkCapabilities getNetworkCapabilities(Network network) {
1201 enforceAccessPermission();
1202 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1203 }
1204
1205 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001206 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001207 // Require internal since we're handing out IMSI details
1208 enforceConnectivityInternalPermission();
1209
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001210 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001211 for (Network network : getAllNetworks()) {
1212 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1213 if (nai != null) {
1214 synchronized (nai) {
1215 final String subscriberId = (nai.networkMisc != null)
1216 ? nai.networkMisc.subscriberId : null;
1217 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1218 nai.networkCapabilities, network, subscriberId, null));
1219 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001220 }
1221 }
1222 return result.toArray(new NetworkState[result.size()]);
1223 }
1224
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001225 @Override
1226 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1227 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001228 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001229 final long token = Binder.clearCallingIdentity();
1230 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001231 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1232 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001233 try {
1234 return mPolicyManager.getNetworkQuotaInfo(state);
1235 } catch (RemoteException e) {
1236 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001237 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001238 return null;
1239 } finally {
1240 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001241 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001242 }
1243
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001244 @Override
1245 public boolean isActiveNetworkMetered() {
1246 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001247 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001248 final long token = Binder.clearCallingIdentity();
1249 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001250 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001251 } finally {
1252 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001253 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001254 }
1255
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001256 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1257 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1258 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001259 try {
1260 return mPolicyManager.isNetworkMetered(state);
1261 } catch (RemoteException e) {
1262 }
1263 }
1264 return false;
1265 }
1266
Jeff Sharkey216c1812012-08-05 14:29:23 -07001267 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1268 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001269 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001270 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001271 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001272 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001273 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001274
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001275 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 * Ensure that a network route exists to deliver traffic to the specified
1277 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001278 * @param networkType the type of the network over which traffic to the
1279 * specified host is to be routed
1280 * @param hostAddress the IP address of the host to which the route is
1281 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 * @return {@code true} on success, {@code false} on failure
1283 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001284 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001286 if (mProtectedNetworks.contains(networkType)) {
1287 enforceConnectivityInternalPermission();
1288 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001289
Chad Brubakerc0234532014-02-14 13:24:29 -08001290 InetAddress addr;
1291 try {
1292 addr = InetAddress.getByAddress(hostAddress);
1293 } catch (UnknownHostException e) {
1294 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1295 return false;
1296 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001299 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 return false;
1301 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001302
1303 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1304 if (nai == null) {
1305 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1306 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1307 } else {
1308 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1309 }
1310 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001311 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001312
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001313 DetailedState netState;
1314 synchronized (nai) {
1315 netState = nai.networkInfo.getDetailedState();
1316 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001317
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001318 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001319 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001320 log("requestRouteToHostAddress on down network "
1321 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001322 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001323 }
1324 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001326
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001327 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001328 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001329 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001330 LinkProperties lp;
1331 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001332 synchronized (nai) {
1333 lp = nai.linkProperties;
1334 netId = nai.network.netId;
1335 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001336 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001337 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1338 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001339 } finally {
1340 Binder.restoreCallingIdentity(token);
1341 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001342 }
1343
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001344 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001345 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001346 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001347 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001348 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001349 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001350 if (bestRoute.getGateway().equals(addr)) {
1351 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001352 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001353 } else {
1354 // if we will connect to this through another route, add a direct route
1355 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001356 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001357 }
1358 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001359 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001360 try {
1361 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1362 } catch (Exception e) {
1363 // never crash - catch them all
1364 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001365 return false;
1366 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001367 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 }
1369
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001370 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1371 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001372 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001373 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001374 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001375 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001376 }
1377
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001378 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001379 // skip update when we've already applied rules
1380 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1381 if (oldRules == uidRules) return;
1382
1383 mUidRules.put(uid, uidRules);
1384 }
1385
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001386 // TODO: notify UID when it has requested targeted updates
1387 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001388
1389 @Override
1390 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001391 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001392 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001393 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001394 }
1395
1396 synchronized (mRulesLock) {
1397 mMeteredIfaces.clear();
1398 for (String iface : meteredIfaces) {
1399 mMeteredIfaces.add(iface);
1400 }
1401 }
1402 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001403
1404 @Override
1405 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1406 // caller is NPMS, since we only register with them
1407 if (LOGD_RULES) {
1408 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1409 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001410 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001411 };
1412
Robin Lee3b3dd942015-05-12 18:14:58 +01001413 /**
1414 * Require that the caller is either in the same user or has appropriate permission to interact
1415 * across users.
1416 *
1417 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1418 */
1419 private void enforceCrossUserPermission(int userId) {
1420 if (userId == UserHandle.getCallingUserId()) {
1421 // Not a cross-user call.
1422 return;
1423 }
1424 mContext.enforceCallingOrSelfPermission(
1425 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1426 "ConnectivityService");
1427 }
1428
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001429 private void enforceInternetPermission() {
1430 mContext.enforceCallingOrSelfPermission(
1431 android.Manifest.permission.INTERNET,
1432 "ConnectivityService");
1433 }
1434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001436 mContext.enforceCallingOrSelfPermission(
1437 android.Manifest.permission.ACCESS_NETWORK_STATE,
1438 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440
1441 private void enforceChangePermission() {
Billy Laua7238a32015-08-01 12:45:02 +01001442 int uid = Binder.getCallingUid();
1443 Settings.checkAndNoteChangeNetworkStateOperation(mContext, uid, Settings
1444 .getPackageNameForUid(mContext, uid), true);
1445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 }
1447
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001448 private void enforceTetherAccessPermission() {
1449 mContext.enforceCallingOrSelfPermission(
1450 android.Manifest.permission.ACCESS_NETWORK_STATE,
1451 "ConnectivityService");
1452 }
1453
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001454 private void enforceConnectivityInternalPermission() {
1455 mContext.enforceCallingOrSelfPermission(
1456 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1457 "ConnectivityService");
1458 }
1459
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001460 private void enforceKeepalivePermission() {
1461 mContext.enforceCallingPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
1462 }
1463
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001464 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001465 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001466 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001467 }
1468
1469 private void sendInetConditionBroadcast(NetworkInfo info) {
1470 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1471 }
1472
Wink Saville628b0852011-08-04 15:01:58 -07001473 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001474 if (mLockdownTracker != null) {
1475 info = mLockdownTracker.augmentNetworkInfo(info);
1476 }
1477
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001478 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001479 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001480 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 if (info.isFailover()) {
1482 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1483 info.setFailover(false);
1484 }
1485 if (info.getReason() != null) {
1486 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1487 }
1488 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001489 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1490 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001492 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001493 return intent;
1494 }
1495
1496 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1497 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1498 }
1499
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001500 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001501 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1502 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1503 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001504 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001505 final long ident = Binder.clearCallingIdentity();
1506 try {
1507 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1508 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1509 } finally {
1510 Binder.restoreCallingIdentity(ident);
1511 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001512 }
1513
Mike Lockwood0f79b542009-08-14 14:18:49 -04001514 private void sendStickyBroadcast(Intent intent) {
1515 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001516 if (!mSystemReady) {
1517 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001518 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001519 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001520 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001521 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001522 }
1523
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001524 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001525 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001526 final NetworkInfo ni = intent.getParcelableExtra(
1527 ConnectivityManager.EXTRA_NETWORK_INFO);
1528 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1529 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1530 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1531 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001532 final IBatteryStats bs = BatteryStatsService.getService();
1533 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001534 bs.noteConnectivityChanged(intent.getIntExtra(
1535 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1536 ni != null ? ni.getState().toString() : "?");
1537 } catch (RemoteException e) {
1538 }
1539 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001540 try {
1541 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1542 } finally {
1543 Binder.restoreCallingIdentity(ident);
1544 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001545 }
1546 }
1547
1548 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001549 loadGlobalProxy();
1550
Mike Lockwood0f79b542009-08-14 14:18:49 -04001551 synchronized(this) {
1552 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001553 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001554 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001555 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001556 }
1557 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001558 // load the global proxy at startup
1559 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001560
1561 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1562 // for user to unlock device.
1563 if (!updateLockdownVpn()) {
1564 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1565 mContext.registerReceiver(mUserPresentReceiver, filter);
1566 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001567
Erik Klineda4bfa82015-04-30 12:58:40 +09001568 // Configure whether mobile data is always on.
1569 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1570
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001571 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001572
1573 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 }
1575
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001576 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1577 @Override
1578 public void onReceive(Context context, Intent intent) {
1579 // Try creating lockdown tracker, since user present usually means
1580 // unlocked keystore.
1581 if (updateLockdownVpn()) {
1582 mContext.unregisterReceiver(this);
1583 }
1584 }
1585 };
1586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001588 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001589 *
1590 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001591 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001592 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001593 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1594 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001595
1596 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001597 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001598
Robert Greenwalt7b816022014-04-18 15:25:25 -07001599 if (networkAgent.networkCapabilities.hasTransport(
1600 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001601 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1602 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001603 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001604 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001605 } else if (networkAgent.networkCapabilities.hasTransport(
1606 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001607 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1608 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001609 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001610 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001611 } else {
1612 // do not track any other networks
1613 timeout = 0;
1614 }
1615
Robert Greenwalt7b816022014-04-18 15:25:25 -07001616 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001617 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001618 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001619 } catch (Exception e) {
1620 // You shall not crash!
1621 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001622 }
1623 }
1624 }
1625
1626 /**
1627 * Remove data activity tracking when network disconnects.
1628 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001629 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1630 final String iface = networkAgent.linkProperties.getInterfaceName();
1631 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001632
Robert Greenwalt7b816022014-04-18 15:25:25 -07001633 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1634 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001635 try {
1636 // the call fails silently if no idletimer setup for this interface
1637 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001638 } catch (Exception e) {
1639 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001640 }
1641 }
1642 }
1643
1644 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001645 * Reads the network specific MTU size from reources.
1646 * and set it on it's iface.
1647 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001648 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1649 final String iface = newLp.getInterfaceName();
1650 final int mtu = newLp.getMtu();
1651 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1652 if (VDBG) log("identical MTU - not setting");
1653 return;
1654 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001655
Robert Greenwalt43074032014-08-15 17:53:05 -07001656 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001657 loge("Unexpected mtu value: " + mtu + ", " + iface);
1658 return;
1659 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001660
w1997615afd812014-08-05 15:18:11 -07001661 // Cannot set MTU without interface name
1662 if (TextUtils.isEmpty(iface)) {
1663 loge("Setting MTU size with null iface.");
1664 return;
1665 }
1666
Robert Greenwalt7b816022014-04-18 15:25:25 -07001667 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001668 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001669 mNetd.setMtu(iface, mtu);
1670 } catch (Exception e) {
1671 Slog.e(TAG, "exception in setMtu()" + e);
1672 }
1673 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001674
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001675 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001676 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1677
1678 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001679 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001680 protected int getDefaultTcpRwnd() {
1681 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1682 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001683
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001684 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1685 if (isDefaultNetwork(nai) == false) {
1686 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001687 }
1688
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001689 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1690 String[] values = null;
1691 if (tcpBufferSizes != null) {
1692 values = tcpBufferSizes.split(",");
1693 }
1694
1695 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001696 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001697 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1698 values = tcpBufferSizes.split(",");
1699 }
1700
1701 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1702
1703 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001704 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001705
1706 final String prefix = "/sys/kernel/ipv4/tcp_";
1707 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1708 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1709 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1710 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1711 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1712 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1713 mCurrentTcpBufferSizes = tcpBufferSizes;
1714 } catch (IOException e) {
1715 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001716 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001717
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001718 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001719 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001720 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1721 if (rwndValue != 0) {
1722 SystemProperties.set(sysctlKey, rwndValue.toString());
1723 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001724 }
1725
Mattias Falk8b47b362011-08-23 14:15:13 +02001726 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001727 /*
1728 * Tell the VMs to toss their DNS caches
1729 */
1730 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1731 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001732 /*
1733 * Connectivity events can happen before boot has completed ...
1734 */
1735 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001736 final long ident = Binder.clearCallingIdentity();
1737 try {
1738 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1739 } finally {
1740 Binder.restoreCallingIdentity(ident);
1741 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001742 }
1743
Robert Greenwalt562cc542014-05-15 18:07:26 -07001744 @Override
1745 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001746 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1747 NETWORK_RESTORE_DELAY_PROP_NAME);
1748 if(restoreDefaultNetworkDelayStr != null &&
1749 restoreDefaultNetworkDelayStr.length() != 0) {
1750 try {
1751 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1752 } catch (NumberFormatException e) {
1753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001755 // if the system property isn't set, use the value for the apn type
1756 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1757
1758 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1759 (mNetConfigs[networkType] != null)) {
1760 ret = mNetConfigs[networkType].restoreTime;
1761 }
1762 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 }
1764
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001765 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001766 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001767 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001768 }
1769 return false;
1770 }
1771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001773 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1774 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001775 if (mContext.checkCallingOrSelfPermission(
1776 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001778 pw.println("Permission Denial: can't dump ConnectivityService " +
1779 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1780 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 return;
1782 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001783
Erik Kline379747a2015-06-05 17:47:34 +09001784 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001785 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001786 final long DIAG_TIME_MS = 5000;
1787 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1788 // Start gathering diagnostic information.
1789 netDiags.add(new NetworkDiagnostics(
1790 nai.network,
Lorenzo Colitti87cfc702015-07-27 16:35:33 +09001791 new LinkProperties(nai.linkProperties), // Must be a copy.
Erik Kline379747a2015-06-05 17:47:34 +09001792 DIAG_TIME_MS));
1793 }
1794
1795 for (NetworkDiagnostics netDiag : netDiags) {
1796 pw.println();
1797 netDiag.waitForMeasurements();
1798 netDiag.dump(pw);
1799 }
1800
1801 return;
1802 }
1803
Lorenzo Colittie3805462015-06-03 11:18:24 +09001804 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001805 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001806 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001807 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001808 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001809 pw.println();
1810
Paul Jensen85cf78e2015-06-25 13:25:07 -04001811 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001812 pw.print("Active default network: ");
1813 if (defaultNai == null) {
1814 pw.println("none");
1815 } else {
1816 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001818 pw.println();
1819
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001820 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001821 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001822 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1823 pw.println(nai.toString());
1824 pw.increaseIndent();
1825 pw.println("Requests:");
1826 pw.increaseIndent();
1827 for (int i = 0; i < nai.networkRequests.size(); i++) {
1828 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001829 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001830 pw.decreaseIndent();
1831 pw.println("Lingered:");
1832 pw.increaseIndent();
1833 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1834 pw.decreaseIndent();
1835 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001836 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001837 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001838 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001839
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001840 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001841 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001842 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1843 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001844 }
1845 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001846 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001847
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001848 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001849
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001850 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001851 pw.print("mNetTransitionWakeLock: currently " +
1852 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1853 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1854 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1855 } else {
1856 pw.println(", last requested never");
1857 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001858 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001859
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001860 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001861 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001862
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001863 pw.println();
1864 mKeepaliveTracker.dump(pw);
1865
Lorenzo Colittie3805462015-06-03 11:18:24 +09001866 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001867 pw.println();
1868 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001869 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001870 for(int i = 0; i < mInetLog.size(); i++) {
1871 pw.println(mInetLog.get(i));
1872 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001873 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001874 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001875
1876 if (argsContain(args, "--short") == false) {
1877 pw.println();
1878 synchronized (mValidationLogs) {
1879 pw.println("mValidationLogs (most recent first):");
1880 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1881 pw.println(p.first);
1882 pw.increaseIndent();
1883 p.second.dump(fd, pw, args);
1884 pw.decreaseIndent();
1885 }
1886 }
Erik Kline7523eb32015-07-09 18:24:03 +09001887
1888 pw.println();
1889 pw.println("mNetworkRequestInfoLogs (most recent first):");
1890 pw.increaseIndent();
1891 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1892 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
1895
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001896 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001897 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001898 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001899 if (officialNai != null && officialNai.equals(nai)) return true;
1900 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001901 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001902 " - " + nai);
1903 }
1904 return false;
1905 }
1906
Paul Jensenc8b9a742014-09-30 15:37:41 -04001907 private boolean isRequest(NetworkRequest request) {
1908 return mNetworkRequests.get(request).isRequest;
1909 }
1910
Robert Greenwalt42acef32009-08-12 16:08:25 -07001911 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001912 private class NetworkStateTrackerHandler extends Handler {
1913 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001914 super(looper);
1915 }
1916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 @Override
1918 public void handleMessage(Message msg) {
1919 NetworkInfo info;
1920 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001921 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001922 handleAsyncChannelHalfConnect(msg);
1923 break;
1924 }
1925 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1926 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1927 if (nai != null) nai.asyncChannel.disconnect();
1928 break;
1929 }
1930 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1931 handleAsyncChannelDisconnected(msg);
1932 break;
1933 }
1934 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1935 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1936 if (nai == null) {
1937 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1938 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001939 final NetworkCapabilities networkCapabilities =
1940 (NetworkCapabilities)msg.obj;
1941 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1942 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001943 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Paul Jensen1c7ba022015-06-16 14:27:36 -04001944 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001945 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1946 networkCapabilities)) {
1947 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1948 + nai.networkCapabilities + " -> " + networkCapabilities);
1949 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001950 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001951 }
1952 break;
1953 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001954 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1955 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1956 if (nai == null) {
1957 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1958 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001959 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001960 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001961 "; created=" + nai.created);
1962 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001963 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001964 synchronized (nai) {
1965 nai.linkProperties = (LinkProperties)msg.obj;
1966 }
Paul Jenseneec75412014-08-04 12:21:19 -04001967 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001968 }
1969 break;
1970 }
1971 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1972 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1973 if (nai == null) {
1974 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1975 break;
1976 }
1977 info = (NetworkInfo) msg.obj;
1978 updateNetworkInfo(nai, info);
1979 break;
1980 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001981 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1982 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1983 if (nai == null) {
1984 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1985 break;
1986 }
1987 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001988 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001989 break;
1990 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001991 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1992 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1993 if (nai == null) {
1994 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1995 break;
1996 }
1997 try {
1998 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001999 } catch (Exception e) {
2000 // Never crash!
2001 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002002 }
2003 break;
2004 }
2005 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2006 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2007 if (nai == null) {
2008 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
2009 break;
2010 }
2011 try {
2012 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002013 } catch (Exception e) {
2014 // Never crash!
2015 loge("Exception in removeVpnUidRanges: " + e);
2016 }
2017 break;
2018 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002019 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2020 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2021 if (nai == null) {
2022 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
2023 break;
2024 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002025 if (nai.created && !nai.networkMisc.explicitlySelected) {
2026 loge("ERROR: created network explicitly selected.");
2027 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002028 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002029 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002030 break;
2031 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002032 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2033 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2034 if (nai == null) {
2035 loge("EVENT_PACKET_KEEPALIVE from unknown NetworkAgent");
2036 break;
2037 }
2038 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2039 break;
2040 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002041 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002042 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002043 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2044 final boolean valid =
2045 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002046 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2047 if (valid != nai.lastValidated) {
2048 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002049 nai.lastValidated = valid;
2050 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002051 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002052 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2053 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002054 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002055 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002056 // Let the NetworkAgent know the state of its network
2057 nai.asyncChannel.sendMessage(
2058 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2059 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2060 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002061 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002062 break;
2063 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002064 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002065 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002066 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2067 handleLingerComplete(nai);
2068 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002069 break;
2070 }
Paul Jensen869868be2014-05-15 10:33:05 -04002071 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002072 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002073 final boolean visible = (msg.arg1 != 0);
2074 final NetworkAgentInfo nai;
2075 synchronized (mNetworkForNetId) {
2076 nai = mNetworkForNetId.get(netId);
2077 }
2078 // If captive portal status has changed, update capabilities.
2079 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2080 nai.lastCaptivePortalDetected = visible;
2081 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002082 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002083 }
2084 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002085 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002086 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002087 if (nai == null) {
2088 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2089 break;
2090 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002091 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002092 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2093 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002094 }
Paul Jensen869868be2014-05-15 10:33:05 -04002095 break;
2096 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002097 }
2098 }
2099 }
2100
Paul Jensen85cf78e2015-06-25 13:25:07 -04002101 private void linger(NetworkAgentInfo nai) {
2102 nai.lingering = true;
2103 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2104 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2105 }
2106
Paul Jensen0cc17322014-11-25 15:26:53 -05002107 // Cancel any lingering so the linger timeout doesn't teardown a network.
2108 // This should be called when a network begins satisfying a NetworkRequest.
2109 // Note: depending on what state the NetworkMonitor is in (e.g.,
2110 // if it's awaiting captive portal login, or if validation failed), this
2111 // may trigger a re-evaluation of the network.
2112 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002113 nai.networkLingered.clear();
2114 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002115 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002116 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002117 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2118 }
2119
Robert Greenwalt7b816022014-04-18 15:25:25 -07002120 private void handleAsyncChannelHalfConnect(Message msg) {
2121 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002122 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002123 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2124 if (VDBG) log("NetworkFactory connected");
2125 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002126 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002127 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002128 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002129 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002130 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002131 }
2132 } else {
2133 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002134 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 }
2136 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2137 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2138 if (VDBG) log("NetworkAgent connected");
2139 // A network agent has requested a connection. Establish the connection.
2140 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2141 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2142 } else {
2143 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002144 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002145 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002146 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002147 synchronized (mNetworkForNetId) {
2148 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002149 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002150 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002151 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002152 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002153 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002154 }
2155 }
2156 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002157
Robert Greenwalt7b816022014-04-18 15:25:25 -07002158 private void handleAsyncChannelDisconnected(Message msg) {
2159 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2160 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002161 if (DBG) {
2162 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2163 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002164 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002165 // TODO - if we move the logic to the network agent (have them disconnect
2166 // because they lost all their requests or because their score isn't good)
2167 // then they would disconnect organically, report their new state and then
2168 // disconnect the channel.
2169 if (nai.networkInfo.isConnected()) {
2170 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2171 null, null);
2172 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002173 final boolean wasDefault = isDefaultNetwork(nai);
2174 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002175 mDefaultInetConditionPublished = 0;
2176 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002177 notifyIfacesChanged();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002178 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2179 // by other networks that are already connected. Perhaps that can be done by
2180 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2181 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002182 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002183 mKeepaliveTracker.handleStopAllKeepalives(nai,
2184 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002185 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002186 mNetworkAgentInfos.remove(msg.replyTo);
2187 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002188 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002189 // Remove the NetworkAgent, but don't mark the netId as
2190 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002191 mNetworkForNetId.remove(nai.network.netId);
2192 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002193 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002194 for (int i = 0; i < nai.networkRequests.size(); i++) {
2195 NetworkRequest request = nai.networkRequests.valueAt(i);
2196 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2197 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2198 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002199 sendUpdatedScoreToFactories(request, 0);
2200 }
2201 }
2202 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2203 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002204 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002205 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002206 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002207 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002208 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002209 if (nai.created) {
2210 // Tell netd to clean up the configuration for this network
2211 // (routing rules, DNS, etc).
2212 // This may be slow as it requires a lot of netd shelling out to ip and
2213 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2214 // after we've rematched networks with requests which should make a potential
2215 // fallback network the default or requested a new network from the
2216 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2217 // long time.
2218 try {
2219 mNetd.removeNetwork(nai.network.netId);
2220 } catch (Exception e) {
2221 loge("Exception removing network: " + e);
2222 }
2223 }
2224 synchronized (mNetworkForNetId) {
2225 mNetIdInUse.delete(nai.network.netId);
2226 }
2227 } else {
2228 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2229 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002230 }
2231 }
2232
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002233 // If this method proves to be too slow then we can maintain a separate
2234 // pendingIntent => NetworkRequestInfo map.
2235 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2236 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2237 Intent intent = pendingIntent.getIntent();
2238 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2239 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2240 if (existingPendingIntent != null &&
2241 existingPendingIntent.getIntent().filterEquals(intent)) {
2242 return entry.getValue();
2243 }
2244 }
2245 return null;
2246 }
2247
2248 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2249 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2250
2251 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2252 if (existingRequest != null) { // remove the existing request.
2253 if (DBG) log("Replacing " + existingRequest.request + " with "
2254 + nri.request + " because their intents matched.");
2255 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2256 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002257 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002258 }
2259
Erik Klineda4bfa82015-04-30 12:58:40 +09002260 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002261 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002262 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002263 if (!nri.isRequest) {
2264 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
2265 if (network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2266 updateSignalStrengthThresholds(network);
2267 }
2268 }
2269 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002270 rematchAllNetworksAndRequests(null, 0);
2271 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2272 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002273 }
2274 }
2275
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002276 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2277 int callingUid) {
2278 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2279 if (nri != null) {
2280 handleReleaseNetworkRequest(nri.request, callingUid);
2281 }
2282 }
2283
Paul Jensen99364842014-12-09 11:43:45 -05002284 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002285 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2286 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002287 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002288 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002289 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2290 // If this Network is already the highest scoring Network for a request, or if
2291 // there is hope for it to become one if it validated, then it is needed.
2292 if (nri.isRequest && nai.satisfies(nri.request) &&
2293 (nai.networkRequests.get(nri.request.requestId) != null ||
2294 // Note that this catches two important cases:
2295 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2296 // is currently satisfying the request. This is desirable when
2297 // cellular ends up validating but WiFi does not.
2298 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002299 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002300 // WiFi ends up validating and out scoring cellular.
2301 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2302 nai.getCurrentScoreAsValidated())) {
2303 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002304 }
2305 }
Paul Jensene0988542015-06-25 15:30:08 -04002306 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002307 }
2308
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002309 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2310 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002311 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002312 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002313 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2314 return;
2315 }
2316 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002317 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002318 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002319 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002320 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002321 // Find all networks that are satisfying this request and remove the request
2322 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002323 // TODO - it's my understanding that for a request there is only a single
2324 // network satisfying it, so this loop is wasteful
2325 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002326 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2327 if (nai.networkRequests.get(nri.request.requestId) != null) {
2328 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002329 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002330 log(" Removing from current network " + nai.name() +
2331 ", leaving " + nai.networkRequests.size() +
2332 " requests.");
2333 }
Paul Jensen99364842014-12-09 11:43:45 -05002334 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002335 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002336 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002337 } else {
2338 // suspect there should only be one pass through here
2339 // but if any were kept do the check below
2340 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002341 }
2342 }
2343 }
2344
Robert Greenwalt51481852015-01-08 14:43:31 -08002345 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2346 if (nai != null) {
2347 mNetworkForRequestId.remove(nri.request.requestId);
2348 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002349 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002350 // that a network connected to serve it, even though the network was already
2351 // connected. Now that this request has gone away, we might have to pretend
2352 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002353 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002354 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2355 boolean doRemove = true;
2356 if (wasKept) {
2357 // check if any of the remaining requests for this network are for the
2358 // same legacy type - if so, don't remove the nai
2359 for (int i = 0; i < nai.networkRequests.size(); i++) {
2360 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2361 if (otherRequest.legacyType == nri.request.legacyType &&
2362 isRequest(otherRequest)) {
2363 if (DBG) log(" still have other legacy request - leaving");
2364 doRemove = false;
2365 }
2366 }
2367 }
2368
2369 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002370 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002371 }
2372 }
2373
Robert Greenwalta67be032014-05-16 15:49:14 -07002374 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002375 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2376 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002377 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002378 } else {
2379 // listens don't have a singular affectedNetwork. Check all networks to see
2380 // if this listen request applies and remove it.
2381 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2382 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002383 if (nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2384 updateSignalStrengthThresholds(nai);
2385 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002386 }
2387 }
2388 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2389 }
2390 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002391
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002392 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2393 enforceConnectivityInternalPermission();
2394 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2395 accept ? 1 : 0, always ? 1: 0, network));
2396 }
2397
2398 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2399 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2400 " accept=" + accept + " always=" + always);
2401
2402 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2403 if (nai == null) {
2404 // Nothing to do.
2405 return;
2406 }
2407
2408 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002409 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002410 return;
2411 }
2412
2413 if (!nai.networkMisc.explicitlySelected) {
2414 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2415 }
2416
2417 if (accept != nai.networkMisc.acceptUnvalidated) {
2418 int oldScore = nai.getCurrentScore();
2419 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002420 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002421 sendUpdatedScoreToFactories(nai);
2422 }
2423
2424 if (always) {
2425 nai.asyncChannel.sendMessage(
2426 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2427 }
2428
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002429 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002430 // Tell the NetworkAgent to not automatically reconnect to the network.
2431 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2432 // Teardown the nework.
2433 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002434 }
2435
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002436 }
2437
2438 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002439 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002440 mHandler.sendMessageDelayed(
2441 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2442 PROMPT_UNVALIDATED_DELAY_MS);
2443 }
2444
2445 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002446 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002447 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2448
2449 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2450 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002451 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002452 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002453 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2454 return;
2455 }
2456
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002457 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002458 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002459 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2460 intent.setClassName("com.android.settings",
2461 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002462
2463 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2464 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2465 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002466 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002467 }
2468
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002469 private class InternalHandler extends Handler {
2470 public InternalHandler(Looper looper) {
2471 super(looper);
2472 }
2473
2474 @Override
2475 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002476 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002477 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002478 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002479 String causedBy = null;
2480 synchronized (ConnectivityService.this) {
2481 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2482 mNetTransitionWakeLock.isHeld()) {
2483 mNetTransitionWakeLock.release();
2484 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002485 } else {
2486 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002487 }
2488 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002489 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2490 log("Failed to find a new network - expiring NetTransition Wakelock");
2491 } else {
2492 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2493 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002494 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002495 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002496 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002497 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002498 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002499 break;
2500 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002501 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002502 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002503 sendStickyBroadcast(intent);
2504 break;
2505 }
Jason Monkdecd2952013-10-10 14:02:51 -04002506 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002507 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002508 break;
2509 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002510 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002511 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2512 break;
2513 }
2514 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2515 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002516 break;
2517 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002518 case EVENT_REGISTER_NETWORK_AGENT: {
2519 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2520 break;
2521 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002522 case EVENT_REGISTER_NETWORK_REQUEST:
2523 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002524 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002525 break;
2526 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002527 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2528 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002529 handleRegisterNetworkRequestWithIntent(msg);
2530 break;
2531 }
2532 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2533 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2534 break;
2535 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002536 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002537 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002538 break;
2539 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002540 case EVENT_SET_ACCEPT_UNVALIDATED: {
2541 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2542 break;
2543 }
2544 case EVENT_PROMPT_UNVALIDATED: {
2545 handlePromptUnvalidated((Network) msg.obj);
2546 break;
2547 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002548 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2549 handleMobileDataAlwaysOn();
2550 break;
2551 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002552 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2553 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2554 mKeepaliveTracker.handleStartKeepalive(msg);
2555 break;
2556 }
2557 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2558 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2559 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2560 int slot = msg.arg1;
2561 int reason = msg.arg2;
2562 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2563 break;
2564 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002565 case EVENT_SYSTEM_READY: {
2566 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2567 nai.networkMonitor.systemReady = true;
2568 }
2569 break;
2570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 }
2572 }
2573 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002574
2575 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002576 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002577 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002578 if (isTetheringSupported()) {
2579 return mTethering.tether(iface);
2580 } else {
2581 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2582 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002583 }
2584
2585 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002586 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002587 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002588
2589 if (isTetheringSupported()) {
2590 return mTethering.untether(iface);
2591 } else {
2592 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2593 }
2594 }
2595
2596 // javadoc from interface
2597 public int getLastTetherError(String iface) {
2598 enforceTetherAccessPermission();
2599
2600 if (isTetheringSupported()) {
2601 return mTethering.getLastTetherError(iface);
2602 } else {
2603 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2604 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002605 }
2606
2607 // TODO - proper iface API for selection by property, inspection, etc
2608 public String[] getTetherableUsbRegexs() {
2609 enforceTetherAccessPermission();
2610 if (isTetheringSupported()) {
2611 return mTethering.getTetherableUsbRegexs();
2612 } else {
2613 return new String[0];
2614 }
2615 }
2616
2617 public String[] getTetherableWifiRegexs() {
2618 enforceTetherAccessPermission();
2619 if (isTetheringSupported()) {
2620 return mTethering.getTetherableWifiRegexs();
2621 } else {
2622 return new String[0];
2623 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002624 }
2625
Danica Chang6fdd0c62010-08-11 14:54:43 -07002626 public String[] getTetherableBluetoothRegexs() {
2627 enforceTetherAccessPermission();
2628 if (isTetheringSupported()) {
2629 return mTethering.getTetherableBluetoothRegexs();
2630 } else {
2631 return new String[0];
2632 }
2633 }
2634
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002635 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002636 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002637 if (isTetheringSupported()) {
2638 return mTethering.setUsbTethering(enable);
2639 } else {
2640 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2641 }
2642 }
2643
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002644 // TODO - move iface listing, queries, etc to new module
2645 // javadoc from interface
2646 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002647 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002648 return mTethering.getTetherableIfaces();
2649 }
2650
2651 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002652 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002653 return mTethering.getTetheredIfaces();
2654 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002655
Robert Greenwalt5a735062010-03-02 17:25:02 -08002656 public String[] getTetheringErroredIfaces() {
2657 enforceTetherAccessPermission();
2658 return mTethering.getErroredIfaces();
2659 }
2660
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002661 public String[] getTetheredDhcpRanges() {
2662 enforceConnectivityInternalPermission();
2663 return mTethering.getTetheredDhcpRanges();
2664 }
2665
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002666 // if ro.tether.denied = true we default to no tethering
2667 // gservices could set the secure setting to 1 though to enable it on a build where it
2668 // had previously been turned off.
2669 public boolean isTetheringSupported() {
2670 enforceTetherAccessPermission();
2671 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002672 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002673 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2674 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002675 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2676 mTethering.getTetherableWifiRegexs().length != 0 ||
2677 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2678 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002679 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002680
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002681 // Called when we lose the default network and have no replacement yet.
2682 // This will automatically be cleared after X seconds or a new default network
2683 // becomes CONNECTED, whichever happens first. The timer is started by the
2684 // first caller and not restarted by subsequent callers.
2685 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002686 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002687 synchronized (this) {
2688 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002689 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002690 mNetTransitionWakeLock.acquire();
2691 mNetTransitionWakeLockCausedBy = forWhom;
2692 }
2693 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002694 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002695 mNetTransitionWakeLockTimeout);
2696 return;
2697 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002698
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002699 // 100 percent is full good, 0 is full bad.
2700 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002701 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002702 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002703 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002704 }
2705
Paul Jensenbfd17b72015-04-07 12:43:13 -04002706 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002707 enforceAccessPermission();
2708 enforceInternetPermission();
2709
Paul Jensenbfd17b72015-04-07 12:43:13 -04002710 NetworkAgentInfo nai;
2711 if (network == null) {
2712 nai = getDefaultNetwork();
2713 } else {
2714 nai = getNetworkAgentInfoForNetwork(network);
2715 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002716 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2717 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2718 return;
2719 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002720 // Revalidate if the app report does not match our current validated state.
2721 if (hasConnectivity == nai.lastValidated) return;
2722 final int uid = Binder.getCallingUid();
2723 if (DBG) {
2724 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2725 ") by " + uid);
2726 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002727 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002728 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2729 // which isn't meant to work on uncreated networks.
2730 if (!nai.created) return;
2731
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002732 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002733
2734 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2735 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002736 }
2737
Paul Jensencee9b512015-05-06 07:32:40 -04002738 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002739 // this information is already available as a world read/writable jvm property
2740 // so this API change wouldn't have a benifit. It also breaks the passing
2741 // of proxy info to all the JVMs.
2742 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002743 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002744 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002745 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2746 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002747 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002748 }
2749
Paul Jensencee9b512015-05-06 07:32:40 -04002750 public ProxyInfo getProxyForNetwork(Network network) {
2751 if (network == null) return getDefaultProxy();
2752 final ProxyInfo globalProxy = getGlobalProxy();
2753 if (globalProxy != null) return globalProxy;
2754 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2755 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2756 // caller may not have.
2757 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2758 if (nai == null) return null;
2759 synchronized (nai) {
2760 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2761 if (proxyInfo == null) return null;
2762 return new ProxyInfo(proxyInfo);
2763 }
2764 }
2765
Paul Jensene0bef712014-12-10 15:12:18 -05002766 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2767 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2768 // proxy is null then there is no proxy in place).
2769 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2770 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2771 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2772 proxy = null;
2773 }
2774 return proxy;
2775 }
2776
2777 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2778 // better for determining if a new proxy broadcast is necessary:
2779 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2780 // avoid unnecessary broadcasts.
2781 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2782 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2783 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2784 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2785 // all set.
2786 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2787 a = canonicalizeProxyInfo(a);
2788 b = canonicalizeProxyInfo(b);
2789 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2790 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2791 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2792 }
2793
Jason Monk207900c2014-04-25 15:00:09 -04002794 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002795 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002796
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002797 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002798 if (proxyProperties == mGlobalProxy) return;
2799 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2800 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2801
2802 String host = "";
2803 int port = 0;
2804 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002805 String pacFileUrl = "";
2806 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002807 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002808 if (!proxyProperties.isValid()) {
2809 if (DBG)
2810 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2811 return;
2812 }
Jason Monk207900c2014-04-25 15:00:09 -04002813 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002814 host = mGlobalProxy.getHost();
2815 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002816 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002817 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002818 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002819 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002820 } else {
2821 mGlobalProxy = null;
2822 }
2823 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002824 final long token = Binder.clearCallingIdentity();
2825 try {
2826 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2827 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2828 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2829 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002830 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002831 } finally {
2832 Binder.restoreCallingIdentity(token);
2833 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002834
Jason Monkcf0f97a2014-10-02 15:39:38 -04002835 if (mGlobalProxy == null) {
2836 proxyProperties = mDefaultProxy;
2837 }
2838 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002839 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002840 }
2841
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002842 private void loadGlobalProxy() {
2843 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002844 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2845 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2846 String exclList = Settings.Global.getString(res,
2847 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002848 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2849 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002850 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002851 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002852 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002853 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002854 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002855 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002856 if (!proxyProperties.isValid()) {
2857 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2858 return;
2859 }
2860
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002861 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002862 mGlobalProxy = proxyProperties;
2863 }
2864 }
2865 }
2866
Jason Monk207900c2014-04-25 15:00:09 -04002867 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002868 // this information is already available as a world read/writable jvm property
2869 // so this API change wouldn't have a benifit. It also breaks the passing
2870 // of proxy info to all the JVMs.
2871 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002872 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002873 return mGlobalProxy;
2874 }
2875 }
2876
Jason Monk207900c2014-04-25 15:00:09 -04002877 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002878 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002879 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002880 proxy = null;
2881 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002882 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002883 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002884 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002885 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002886 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2887 return;
2888 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002889
2890 // This call could be coming from the PacManager, containing the port of the local
2891 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2892 // global (to get the correct local port), and send a broadcast.
2893 // TODO: Switch PacManager to have its own message to send back rather than
2894 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002895 if ((mGlobalProxy != null) && (proxy != null)
2896 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002897 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2898 mGlobalProxy = proxy;
2899 sendProxyBroadcast(mGlobalProxy);
2900 return;
2901 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002902 mDefaultProxy = proxy;
2903
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002904 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002905 if (!mDefaultProxyDisabled) {
2906 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002907 }
2908 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002909 }
2910
Paul Jensene0bef712014-12-10 15:12:18 -05002911 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2912 // This method gets called when any network changes proxy, but the broadcast only ever contains
2913 // the default proxy (even if it hasn't changed).
2914 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2915 // world where an app might be bound to a non-default network.
2916 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2917 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2918 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2919
2920 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2921 sendProxyBroadcast(getDefaultProxy());
2922 }
2923 }
2924
Robert Greenwalt434203a2010-10-11 16:00:27 -07002925 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002926 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2927 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002928 if (!TextUtils.isEmpty(proxy)) {
2929 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002930 if (data.length == 0) {
2931 return;
2932 }
2933
Robert Greenwalt434203a2010-10-11 16:00:27 -07002934 String proxyHost = data[0];
2935 int proxyPort = 8080;
2936 if (data.length > 1) {
2937 try {
2938 proxyPort = Integer.parseInt(data[1]);
2939 } catch (NumberFormatException e) {
2940 return;
2941 }
2942 }
Jason Monk207900c2014-04-25 15:00:09 -04002943 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002944 setGlobalProxy(p);
2945 }
2946 }
2947
Jason Monk207900c2014-04-25 15:00:09 -04002948 private void sendProxyBroadcast(ProxyInfo proxy) {
2949 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002950 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002951 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002952 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002953 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2954 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002955 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002956 final long ident = Binder.clearCallingIdentity();
2957 try {
2958 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2959 } finally {
2960 Binder.restoreCallingIdentity(ident);
2961 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002962 }
2963
2964 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002965 final private HashMap<Uri, Integer> mUriEventMap;
2966 final private Context mContext;
2967 final private Handler mHandler;
2968
2969 SettingsObserver(Context context, Handler handler) {
2970 super(null);
2971 mUriEventMap = new HashMap<Uri, Integer>();
2972 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002973 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002974 }
2975
Erik Klineda4bfa82015-04-30 12:58:40 +09002976 void observe(Uri uri, int what) {
2977 mUriEventMap.put(uri, what);
2978 final ContentResolver resolver = mContext.getContentResolver();
2979 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002980 }
2981
2982 @Override
2983 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002984 Slog.wtf(TAG, "Should never be reached.");
2985 }
2986
2987 @Override
2988 public void onChange(boolean selfChange, Uri uri) {
2989 final Integer what = mUriEventMap.get(uri);
2990 if (what != null) {
2991 mHandler.obtainMessage(what.intValue()).sendToTarget();
2992 } else {
2993 loge("No matching event to send for URI=" + uri);
2994 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002995 }
2996 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002997
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002998 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002999 Slog.d(TAG, s);
3000 }
3001
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003002 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003003 Slog.e(TAG, s);
3004 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003005
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003006 private static <T> T checkNotNull(T value, String message) {
3007 if (value == null) {
3008 throw new NullPointerException(message);
3009 }
3010 return value;
3011 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003012
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003013 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003014 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003015 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3016 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3017 *
3018 * @param oldPackage Package name of the application which currently controls VPN, which will
3019 * be replaced. If there is no such application, this should should either be
3020 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3021 * @param newPackage Package name of the application which should gain control of VPN, or
3022 * {@code null} to disable.
3023 * @param userId User for whom to prepare the new VPN.
3024 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003025 * @hide
3026 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003027 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003028 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3029 int userId) {
3030 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003031 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003032
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003033 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003034 Vpn vpn = mVpns.get(userId);
3035 if (vpn != null) {
3036 return vpn.prepare(oldPackage, newPackage);
3037 } else {
3038 return false;
3039 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003040 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003041 }
3042
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003043 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003044 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3045 * This method is used by system-privileged apps.
3046 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3047 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3048 *
3049 * @param packageName The package for which authorization state should change.
3050 * @param userId User for whom {@code packageName} is installed.
3051 * @param authorized {@code true} if this app should be able to start a VPN connection without
3052 * explicit user approval, {@code false} if not.
3053 *
Jeff Davidson05542602014-08-11 14:07:27 -07003054 * @hide
3055 */
3056 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003057 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3058 enforceCrossUserPermission(userId);
3059
Jeff Davidson05542602014-08-11 14:07:27 -07003060 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003061 Vpn vpn = mVpns.get(userId);
3062 if (vpn != null) {
3063 vpn.setPackageAuthorization(packageName, authorized);
3064 }
Jeff Davidson05542602014-08-11 14:07:27 -07003065 }
3066 }
3067
3068 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003069 * Configure a TUN interface and return its file descriptor. Parameters
3070 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003071 * and not available in ConnectivityManager. Permissions are checked in
3072 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003073 * @hide
3074 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003075 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003076 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003077 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003078 int user = UserHandle.getUserId(Binder.getCallingUid());
3079 synchronized(mVpns) {
3080 return mVpns.get(user).establish(config);
3081 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003082 }
3083
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003084 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003085 * Start legacy VPN, controlling native daemons as needed. Creates a
3086 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003087 */
3088 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003089 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003090 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003091 final LinkProperties egress = getActiveLinkProperties();
3092 if (egress == null) {
3093 throw new IllegalStateException("Missing active network connection");
3094 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003095 int user = UserHandle.getUserId(Binder.getCallingUid());
3096 synchronized(mVpns) {
3097 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3098 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003099 }
3100
3101 /**
3102 * Return the information of the ongoing legacy VPN. This method is used
3103 * by VpnSettings and not available in ConnectivityManager. Permissions
3104 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003105 */
3106 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003107 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3108 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003109 if (mLockdownEnabled) {
3110 return null;
3111 }
3112
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003113 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003114 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003115 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003116 }
3117
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003118 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003119 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3120 * and not available in ConnectivityManager.
3121 */
3122 @Override
3123 public VpnInfo[] getAllVpnInfo() {
3124 enforceConnectivityInternalPermission();
3125 if (mLockdownEnabled) {
3126 return new VpnInfo[0];
3127 }
3128
3129 synchronized(mVpns) {
3130 List<VpnInfo> infoList = new ArrayList<>();
3131 for (int i = 0; i < mVpns.size(); i++) {
3132 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3133 if (info != null) {
3134 infoList.add(info);
3135 }
3136 }
3137 return infoList.toArray(new VpnInfo[infoList.size()]);
3138 }
3139 }
3140
3141 /**
3142 * @return VPN information for accounting, or null if we can't retrieve all required
3143 * information, e.g primary underlying iface.
3144 */
3145 @Nullable
3146 private VpnInfo createVpnInfo(Vpn vpn) {
3147 VpnInfo info = vpn.getVpnInfo();
3148 if (info == null) {
3149 return null;
3150 }
3151 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3152 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3153 // the underlyingNetworks list.
3154 if (underlyingNetworks == null) {
3155 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3156 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3157 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3158 }
3159 } else if (underlyingNetworks.length > 0) {
3160 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3161 if (linkProperties != null) {
3162 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3163 }
3164 }
3165 return info.primaryUnderlyingIface == null ? null : info;
3166 }
3167
3168 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003169 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3170 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003171 * Permissions are checked in Vpn class.
3172 * @hide
3173 */
3174 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003175 public VpnConfig getVpnConfig(int userId) {
3176 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003177 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003178 Vpn vpn = mVpns.get(userId);
3179 if (vpn != null) {
3180 return vpn.getVpnConfig();
3181 } else {
3182 return null;
3183 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003184 }
3185 }
3186
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003187 @Override
3188 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003189 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3190 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3191 return false;
3192 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003193
3194 // Tear down existing lockdown if profile was removed
3195 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3196 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003197 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003198 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3199 return false;
3200 }
3201
3202 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3203 final VpnProfile profile = VpnProfile.decode(
3204 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003205 int user = UserHandle.getUserId(Binder.getCallingUid());
3206 synchronized(mVpns) {
3207 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3208 profile));
3209 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003210 } else {
3211 setLockdownTracker(null);
3212 }
3213
3214 return true;
3215 }
3216
3217 /**
3218 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3219 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3220 */
3221 private void setLockdownTracker(LockdownVpnTracker tracker) {
3222 // Shutdown any existing tracker
3223 final LockdownVpnTracker existing = mLockdownTracker;
3224 mLockdownTracker = null;
3225 if (existing != null) {
3226 existing.shutdown();
3227 }
3228
3229 try {
3230 if (tracker != null) {
3231 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003232 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003233 mLockdownTracker = tracker;
3234 mLockdownTracker.init();
3235 } else {
3236 mNetd.setFirewallEnabled(false);
3237 }
3238 } catch (RemoteException e) {
3239 // ignored; NMS lives inside system_server
3240 }
3241 }
3242
3243 private void throwIfLockdownEnabled() {
3244 if (mLockdownEnabled) {
3245 throw new IllegalStateException("Unavailable in lockdown mode");
3246 }
3247 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003248
Wink Savilleab9321d2013-06-29 21:10:57 -07003249 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003250 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003251 // TODO: Remove? Any reason to trigger a provisioning check?
3252 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003253 }
3254
3255 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003256 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003257
Paul Jensen89e0f092014-09-15 15:59:36 -04003258 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003259 if (DBG) {
3260 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003261 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003262 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003263 Intent intent = new Intent(action);
3264 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003265 // Concatenate the range of types onto the range of NetIDs.
3266 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003267 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003268 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003269 }
3270
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003271 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003272 * Show or hide network provisioning notifications.
3273 *
3274 * We use notifications for two purposes: to notify that a network requires sign in
3275 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3276 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3277 * particular network we can display the notification type that was most recently requested.
3278 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3279 * might first display NO_INTERNET, and then when the captive portal check completes, display
3280 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003281 *
3282 * @param id an identifier that uniquely identifies this notification. This must match
3283 * between show and hide calls. We use the NetID value but for legacy callers
3284 * we concatenate the range of types with the range of NetIDs.
3285 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003286 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003287 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3288 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003289 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003290 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3291 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003292 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003293 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003294
3295 Resources r = Resources.getSystem();
3296 NotificationManager notificationManager = (NotificationManager) mContext
3297 .getSystemService(Context.NOTIFICATION_SERVICE);
3298
3299 if (visible) {
3300 CharSequence title;
3301 CharSequence details;
3302 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003303 if (notifyType == NotificationType.NO_INTERNET &&
3304 networkType == ConnectivityManager.TYPE_WIFI) {
3305 title = r.getString(R.string.wifi_no_internet, 0);
3306 details = r.getString(R.string.wifi_no_internet_detailed);
3307 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3308 } else if (notifyType == NotificationType.SIGN_IN) {
3309 switch (networkType) {
3310 case ConnectivityManager.TYPE_WIFI:
3311 title = r.getString(R.string.wifi_available_sign_in, 0);
3312 details = r.getString(R.string.network_available_sign_in_detailed,
3313 extraInfo);
3314 icon = R.drawable.stat_notify_wifi_in_range;
3315 break;
3316 case ConnectivityManager.TYPE_MOBILE:
3317 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3318 title = r.getString(R.string.network_available_sign_in, 0);
3319 // TODO: Change this to pull from NetworkInfo once a printable
3320 // name has been added to it
3321 details = mTelephonyManager.getNetworkOperatorName();
3322 icon = R.drawable.stat_notify_rssi_in_range;
3323 break;
3324 default:
3325 title = r.getString(R.string.network_available_sign_in, 0);
3326 details = r.getString(R.string.network_available_sign_in_detailed,
3327 extraInfo);
3328 icon = R.drawable.stat_notify_rssi_in_range;
3329 break;
3330 }
3331 } else {
3332 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3333 + getNetworkTypeName(networkType));
3334 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003335 }
3336
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003337 Notification notification = new Notification.Builder(mContext)
3338 .setWhen(0)
3339 .setSmallIcon(icon)
3340 .setAutoCancel(true)
3341 .setTicker(title)
3342 .setColor(mContext.getColor(
3343 com.android.internal.R.color.system_notification_accent_color))
3344 .setContentTitle(title)
3345 .setContentText(details)
3346 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003347 .setLocalOnly(true)
3348 .setPriority(highPriority ?
3349 Notification.PRIORITY_HIGH :
3350 Notification.PRIORITY_DEFAULT)
3351 .setDefaults(Notification.DEFAULT_ALL)
3352 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003353 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003354
Wink Saville948282b2013-08-29 08:55:16 -07003355 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003356 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003357 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003358 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003359 npe.printStackTrace();
3360 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003361 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003362 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003363 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003364 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003365 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003366 npe.printStackTrace();
3367 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003368 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003369 }
3370
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003371 /** Location to an updatable file listing carrier provisioning urls.
3372 * An example:
3373 *
3374 * <?xml version="1.0" encoding="utf-8"?>
3375 * <provisioningUrls>
3376 * <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 -07003377 * </provisioningUrls>
3378 */
3379 private static final String PROVISIONING_URL_PATH =
3380 "/data/misc/radio/provisioning_urls.xml";
3381 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003382
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003383 /** XML tag for root element. */
3384 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3385 /** XML tag for individual url */
3386 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003387 /** XML attribute for mcc */
3388 private static final String ATTR_MCC = "mcc";
3389 /** XML attribute for mnc */
3390 private static final String ATTR_MNC = "mnc";
3391
Paul Jensen434dde82015-06-11 09:43:30 -04003392 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003393 FileReader fileReader = null;
3394 XmlPullParser parser = null;
3395 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003396
3397 try {
3398 fileReader = new FileReader(mProvisioningUrlFile);
3399 parser = Xml.newPullParser();
3400 parser.setInput(fileReader);
3401 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3402
3403 while (true) {
3404 XmlUtils.nextElement(parser);
3405
3406 String element = parser.getName();
3407 if (element == null) break;
3408
Paul Jensen434dde82015-06-11 09:43:30 -04003409 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003410 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3411 try {
3412 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3413 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3414 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3415 parser.next();
3416 if (parser.getEventType() == XmlPullParser.TEXT) {
3417 return parser.getText();
3418 }
3419 }
3420 }
3421 } catch (NumberFormatException e) {
3422 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3423 }
3424 }
3425 }
3426 return null;
3427 } catch (FileNotFoundException e) {
3428 loge("Carrier Provisioning Urls file not found");
3429 } catch (XmlPullParserException e) {
3430 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3431 } catch (IOException e) {
3432 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3433 } finally {
3434 if (fileReader != null) {
3435 try {
3436 fileReader.close();
3437 } catch (IOException e) {}
3438 }
3439 }
3440 return null;
3441 }
3442
Wink Saville42d4f082013-07-20 20:31:59 -07003443 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003444 public String getMobileProvisioningUrl() {
3445 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003446 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003447 if (TextUtils.isEmpty(url)) {
3448 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003449 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003450 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003451 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003452 }
Wink Saville8cf35602013-07-10 23:00:07 -07003453 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003454 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003455 String phoneNumber = mTelephonyManager.getLine1Number();
3456 if (TextUtils.isEmpty(phoneNumber)) {
3457 phoneNumber = "0000000000";
3458 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003459 url = String.format(url,
3460 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3461 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003462 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003463 }
3464
Wink Savilleab9321d2013-06-29 21:10:57 -07003465 return url;
3466 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003467
Wink Saville948282b2013-08-29 08:55:16 -07003468 @Override
3469 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003470 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003471 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003472 final long ident = Binder.clearCallingIdentity();
3473 try {
3474 setProvNotificationVisible(visible, networkType, action);
3475 } finally {
3476 Binder.restoreCallingIdentity(ident);
3477 }
Wink Saville948282b2013-08-29 08:55:16 -07003478 }
Wink Saville7788c612013-08-29 14:57:08 -07003479
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003480 @Override
3481 public void setAirplaneMode(boolean enable) {
3482 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003483 final long ident = Binder.clearCallingIdentity();
3484 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003485 final ContentResolver cr = mContext.getContentResolver();
3486 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3487 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3488 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003489 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003490 } finally {
3491 Binder.restoreCallingIdentity(ident);
3492 }
3493 }
3494
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003495 private void onUserStart(int userId) {
3496 synchronized(mVpns) {
3497 Vpn userVpn = mVpns.get(userId);
3498 if (userVpn != null) {
3499 loge("Starting user already has a VPN");
3500 return;
3501 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003502 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003503 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003504 }
3505 }
3506
3507 private void onUserStop(int userId) {
3508 synchronized(mVpns) {
3509 Vpn userVpn = mVpns.get(userId);
3510 if (userVpn == null) {
3511 loge("Stopping user has no VPN");
3512 return;
3513 }
3514 mVpns.delete(userId);
3515 }
3516 }
3517
3518 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3519 @Override
3520 public void onReceive(Context context, Intent intent) {
3521 final String action = intent.getAction();
3522 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3523 if (userId == UserHandle.USER_NULL) return;
3524
3525 if (Intent.ACTION_USER_STARTING.equals(action)) {
3526 onUserStart(userId);
3527 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3528 onUserStop(userId);
3529 }
3530 }
3531 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003532
Robert Greenwalta67be032014-05-16 15:49:14 -07003533 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3534 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003535 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3536 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003537
Robert Greenwalta67be032014-05-16 15:49:14 -07003538 private static class NetworkFactoryInfo {
3539 public final String name;
3540 public final Messenger messenger;
3541 public final AsyncChannel asyncChannel;
3542
3543 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3544 this.name = name;
3545 this.messenger = messenger;
3546 this.asyncChannel = asyncChannel;
3547 }
3548 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003549
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003550 /**
3551 * Tracks info about the requester.
3552 * Also used to notice when the calling process dies so we can self-expire
3553 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003554 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3555 static final boolean REQUEST = true;
3556 static final boolean LISTEN = false;
3557
3558 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003559 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003560 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003561 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003562 final int mPid;
3563 final int mUid;
3564 final Messenger messenger;
3565 final boolean isRequest;
3566
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003567 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3568 request = r;
3569 mPendingIntent = pi;
3570 messenger = null;
3571 mBinder = null;
3572 mPid = getCallingPid();
3573 mUid = getCallingUid();
3574 this.isRequest = isRequest;
3575 }
3576
Robert Greenwalt9258c642014-03-26 16:47:06 -07003577 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3578 super();
3579 messenger = m;
3580 request = r;
3581 mBinder = binder;
3582 mPid = getCallingPid();
3583 mUid = getCallingUid();
3584 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003585 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003586
3587 try {
3588 mBinder.linkToDeath(this, 0);
3589 } catch (RemoteException e) {
3590 binderDied();
3591 }
3592 }
3593
3594 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003595 if (mBinder != null) {
3596 mBinder.unlinkToDeath(this, 0);
3597 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003598 }
3599
3600 public void binderDied() {
3601 log("ConnectivityService NetworkRequestInfo binderDied(" +
3602 request + ", " + mBinder + ")");
3603 releaseNetworkRequest(request);
3604 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003605
3606 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003607 return (isRequest ? "Request" : "Listen") +
3608 " from uid/pid:" + mUid + "/" + mPid +
3609 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003610 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003611 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003612 }
3613
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003614 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3615 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3616 if (badCapability != null) {
3617 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003618 }
3619 }
3620
Erik Kline9d598e12015-07-13 16:37:51 +09003621 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003622 final SortedSet<Integer> thresholds = new TreeSet();
3623 synchronized (nai) {
3624 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3625 if (nri.request.networkCapabilities.hasSignalStrength() &&
3626 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3627 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3628 }
3629 }
3630 }
Erik Kline9d598e12015-07-13 16:37:51 +09003631 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003632 }
3633
3634 private void updateSignalStrengthThresholds(NetworkAgentInfo nai) {
Erik Kline9d598e12015-07-13 16:37:51 +09003635 Bundle thresholds = new Bundle();
3636 thresholds.putIntegerArrayList("thresholds", getSignalStrengthThresholds(nai));
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003637 nai.asyncChannel.sendMessage(
3638 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003639 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003640 }
3641
Robert Greenwalt9258c642014-03-26 16:47:06 -07003642 @Override
3643 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003644 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003645 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003646 enforceNetworkRequestPermissions(networkCapabilities);
3647 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003648 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003649
Robert Greenwalt6078b502014-06-11 16:05:07 -07003650 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003651 throw new IllegalArgumentException("Bad timeout specified");
3652 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003653
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003654 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3655 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003656 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3657 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003658 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003659
3660 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003661 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003662 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003663 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003664 }
3665 return networkRequest;
3666 }
3667
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003668 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003669 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003670 enforceConnectivityInternalPermission();
3671 } else {
3672 enforceChangePermission();
3673 }
3674 }
3675
fenglub15e72b2015-03-20 11:29:56 -07003676 @Override
fengludb571472015-04-21 17:12:05 -07003677 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003678 enforceAccessPermission();
3679 NetworkAgentInfo nai = null;
3680 if (network == null) {
3681 return false;
3682 }
3683 synchronized (mNetworkForNetId) {
3684 nai = mNetworkForNetId.get(network.netId);
3685 }
3686 if (nai != null) {
3687 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3688 return true;
3689 }
3690 return false;
3691 }
3692
3693
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003694 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3695 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003696 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003697 final int uidRules;
3698 final int uid = Binder.getCallingUid();
3699 synchronized(mRulesLock) {
3700 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3701 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003702 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003703 // we could silently fail or we can filter the available nets to only give
3704 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003705 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003706 }
3707 }
3708 }
3709
Robert Greenwalt9258c642014-03-26 16:47:06 -07003710 @Override
3711 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3712 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003713 checkNotNull(operation, "PendingIntent cannot be null.");
3714 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3715 enforceNetworkRequestPermissions(networkCapabilities);
3716 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003717 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003718
3719 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3720 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003721 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3722 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003723 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3725 nri));
3726 return networkRequest;
3727 }
3728
Jeremy Joslin79294842014-12-03 17:15:28 -08003729 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3730 mHandler.sendMessageDelayed(
3731 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3732 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3733 }
3734
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003735 @Override
3736 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003737 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003738 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3739 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003740 }
3741
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003742 // In order to implement the compatibility measure for pre-M apps that call
3743 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3744 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3745 // This ensures it has permission to do so.
3746 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3747 if (nc == null) {
3748 return false;
3749 }
3750 int[] transportTypes = nc.getTransportTypes();
3751 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3752 return false;
3753 }
3754 try {
3755 mContext.enforceCallingOrSelfPermission(
3756 android.Manifest.permission.ACCESS_WIFI_STATE,
3757 "ConnectivityService");
3758 } catch (SecurityException e) {
3759 return false;
3760 }
3761 return true;
3762 }
3763
Robert Greenwalt9258c642014-03-26 16:47:06 -07003764 @Override
3765 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3766 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003767 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3768 enforceAccessPermission();
3769 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003770
Erik Kline7523eb32015-07-09 18:24:03 +09003771 NetworkRequest networkRequest = new NetworkRequest(
3772 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003773 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3774 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003775 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003776
3777 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3778 return networkRequest;
3779 }
3780
3781 @Override
3782 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3783 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003784 checkNotNull(operation, "PendingIntent cannot be null.");
3785 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3786 enforceAccessPermission();
3787 }
3788
Erik Kline7523eb32015-07-09 18:24:03 +09003789 NetworkRequest networkRequest = new NetworkRequest(
3790 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003791 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3792 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003793 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003794
3795 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003796 }
3797
3798 @Override
3799 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003800 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3801 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003802 }
3803
3804 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003805 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003806 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003807 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3808 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003809 }
3810
Robert Greenwalta67be032014-05-16 15:49:14 -07003811 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003812 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003813 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3814 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3815 }
3816
3817 @Override
3818 public void unregisterNetworkFactory(Messenger messenger) {
3819 enforceConnectivityInternalPermission();
3820 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3821 }
3822
3823 private void handleUnregisterNetworkFactory(Messenger messenger) {
3824 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3825 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003826 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003827 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003828 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003829 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003830 }
3831
Robert Greenwalt7b816022014-04-18 15:25:25 -07003832 /**
3833 * NetworkAgentInfo supporting a request by requestId.
3834 * These have already been vetted (their Capabilities satisfy the request)
3835 * and the are the highest scored network available.
3836 * the are keyed off the Requests requestId.
3837 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003838 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003839 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3840 new SparseArray<NetworkAgentInfo>();
3841
Paul Jensen31a94f42015-02-13 14:18:39 -05003842 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3843 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003844 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3845 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003846 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3847 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3848 // there may not be a strict 1:1 correlation between the two.
3849 @GuardedBy("mNetworkForNetId")
3850 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003851
Robert Greenwalt7b816022014-04-18 15:25:25 -07003852 // NetworkAgentInfo keyed off its connecting messenger
3853 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003854 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003855 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3856 new HashMap<Messenger, NetworkAgentInfo>();
3857
Paul Jensen2c311d62014-11-17 12:34:51 -05003858 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003859 private final NetworkRequest mDefaultRequest;
3860
Erik Klineda4bfa82015-04-30 12:58:40 +09003861 // Request used to optionally keep mobile data active even when higher
3862 // priority networks like Wi-Fi are active.
3863 private final NetworkRequest mDefaultMobileDataRequest;
3864
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003865 private NetworkAgentInfo getDefaultNetwork() {
3866 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3867 }
3868
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003869 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003870 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003871 }
3872
Paul Jensen31a94f42015-02-13 14:18:39 -05003873 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003874 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003875 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003876 enforceConnectivityInternalPermission();
3877
Paul Jensen2c311d62014-11-17 12:34:51 -05003878 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3879 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04003880 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003881 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3882 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04003883 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003884 synchronized (this) {
3885 nai.networkMonitor.systemReady = mSystemReady;
3886 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003887 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003888 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003889 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003890 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003891 }
3892
3893 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3894 if (VDBG) log("Got NetworkAgent Messenger");
3895 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003896 synchronized (mNetworkForNetId) {
3897 mNetworkForNetId.put(na.network.netId, na);
3898 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003899 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3900 NetworkInfo networkInfo = na.networkInfo;
3901 na.networkInfo = null;
3902 updateNetworkInfo(na, networkInfo);
3903 }
3904
3905 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3906 LinkProperties newLp = networkAgent.linkProperties;
3907 int netId = networkAgent.network.netId;
3908
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003909 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3910 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003911 if (networkAgent.clatd != null) {
3912 networkAgent.clatd.fixupLinkProperties(oldLp);
3913 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003914
Paul Jensen992f2522014-04-28 10:33:11 -04003915 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003916 updateMtu(newLp, oldLp);
3917 // TODO - figure out what to do for clat
3918// for (LinkProperties lp : newLp.getStackedLinks()) {
3919// updateMtu(lp, null);
3920// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003921 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003922
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003923 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3924 // In L, we used it only when the network had Internet access but provided no DNS servers.
3925 // For now, just disable it, and if disabling it doesn't break things, remove it.
3926 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3927 // NET_CAPABILITY_INTERNET);
3928 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003929 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003930 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3931
Paul Jensen3b759822014-05-13 11:44:01 -04003932 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003933 if (isDefaultNetwork(networkAgent)) {
3934 handleApplyDefaultProxy(newLp.getHttpProxy());
3935 } else {
3936 updateProxy(newLp, oldLp, networkAgent);
3937 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003938 // TODO - move this check to cover the whole function
3939 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003940 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003941 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3942 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003943
3944 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04003945 }
3946
Lorenzo Colitti95439462014-10-09 13:44:48 +09003947 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3948 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3949 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003950
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003951 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003952 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3953 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003954 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003955 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003956 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003957 }
Paul Jensen992f2522014-04-28 10:33:11 -04003958
3959 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3960 CompareResult<String> interfaceDiff = new CompareResult<String>();
3961 if (oldLp != null) {
3962 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3963 } else if (newLp != null) {
3964 interfaceDiff.added = newLp.getAllInterfaceNames();
3965 }
3966 for (String iface : interfaceDiff.added) {
3967 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003968 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003969 mNetd.addInterfaceToNetwork(iface, netId);
3970 } catch (Exception e) {
3971 loge("Exception adding interface: " + e);
3972 }
3973 }
3974 for (String iface : interfaceDiff.removed) {
3975 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003976 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003977 mNetd.removeInterfaceFromNetwork(iface, netId);
3978 } catch (Exception e) {
3979 loge("Exception removing interface: " + e);
3980 }
3981 }
3982 }
3983
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003984 /**
3985 * Have netd update routes from oldLp to newLp.
3986 * @return true if routes changed between oldLp and newLp
3987 */
3988 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003989 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3990 if (oldLp != null) {
3991 routeDiff = oldLp.compareAllRoutes(newLp);
3992 } else if (newLp != null) {
3993 routeDiff.added = newLp.getAllRoutes();
3994 }
3995
3996 // add routes before removing old in case it helps with continuous connectivity
3997
3998 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3999 for (RouteInfo route : routeDiff.added) {
4000 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004001 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004002 try {
4003 mNetd.addRoute(netId, route);
4004 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004005 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4006 loge("Exception in addRoute for non-gateway: " + e);
4007 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004008 }
4009 }
4010 for (RouteInfo route : routeDiff.added) {
4011 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004012 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004013 try {
4014 mNetd.addRoute(netId, route);
4015 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004016 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4017 loge("Exception in addRoute for gateway: " + e);
4018 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004019 }
4020 }
4021
4022 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004023 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004024 try {
4025 mNetd.removeRoute(netId, route);
4026 } catch (Exception e) {
4027 loge("Exception in removeRoute: " + e);
4028 }
4029 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004030 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004031 }
Erik Kline41368502015-06-17 13:19:54 +09004032
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004033 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4034 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004035 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09004036 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004037 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004038 dnses = new ArrayList();
4039 dnses.add(mDefaultDns);
4040 if (DBG) {
4041 loge("no dns provided for netId " + netId + ", so using defaults");
4042 }
4043 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004044 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004045 try {
4046 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4047 newLp.getDomains());
4048 } catch (Exception e) {
4049 loge("Exception in setDnsServersForNetwork: " + e);
4050 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04004051 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004052 if (defaultNai != null && defaultNai.network.netId == netId) {
4053 setDefaultDnsSystemProperties(dnses);
4054 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004055 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004056 } else if (flush) {
4057 try {
4058 mNetd.flushNetworkDnsCache(netId);
4059 } catch (Exception e) {
4060 loge("Exception in flushNetworkDnsCache: " + e);
4061 }
4062 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004063 }
4064 }
4065
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004066 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4067 int last = 0;
4068 for (InetAddress dns : dnses) {
4069 ++last;
4070 String key = "net.dns" + last;
4071 String value = dns.getHostAddress();
4072 SystemProperties.set(key, value);
4073 }
4074 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4075 String key = "net.dns" + i;
4076 SystemProperties.set(key, "");
4077 }
4078 mNumDnsEntries = last;
4079 }
4080
Paul Jensen3d194ea2015-06-16 14:27:36 -04004081 /**
4082 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4083 * augmented with any stateful capabilities implied from {@code networkAgent}
4084 * (e.g., validated status and captive portal status).
4085 *
Paul Jensene0988542015-06-25 15:30:08 -04004086 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004087 * @param networkCapabilities the new network capabilities.
4088 */
Paul Jensene0988542015-06-25 15:30:08 -04004089 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004090 // Don't modify caller's NetworkCapabilities.
4091 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004092 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004093 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4094 } else {
4095 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4096 }
Paul Jensene0988542015-06-25 15:30:08 -04004097 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004098 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4099 } else {
4100 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4101 }
Paul Jensene0988542015-06-25 15:30:08 -04004102 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4103 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004104 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4105 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4106 try {
4107 mNetd.setNetworkPermission(nai.network.netId,
4108 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4109 null : NetworkManagementService.PERMISSION_SYSTEM);
4110 } catch (RemoteException e) {
4111 loge("Exception in setNetworkPermission: " + e);
4112 }
4113 }
Paul Jensene0988542015-06-25 15:30:08 -04004114 synchronized (nai) {
4115 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004116 }
Paul Jensene0988542015-06-25 15:30:08 -04004117 rematchAllNetworksAndRequests(nai, oldScore);
4118 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004119 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004120 }
4121
Paul Jensenc8b9a742014-09-30 15:37:41 -04004122 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4123 for (int i = 0; i < nai.networkRequests.size(); i++) {
4124 NetworkRequest nr = nai.networkRequests.valueAt(i);
4125 // Don't send listening requests to factories. b/17393458
4126 if (!isRequest(nr)) continue;
4127 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4128 }
4129 }
4130
Robert Greenwalt7b816022014-04-18 15:25:25 -07004131 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4132 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004133 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004134 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4135 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004136 }
4137 }
4138
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004139 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4140 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004141 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004142 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004143 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4144 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004145 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004146 sendIntent(nri.mPendingIntent, intent);
4147 }
4148 // else not handled
4149 }
4150
4151 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4152 mPendingIntentWakeLock.acquire();
4153 try {
4154 if (DBG) log("Sending " + pendingIntent);
4155 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4156 } catch (PendingIntent.CanceledException e) {
4157 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4158 mPendingIntentWakeLock.release();
4159 releasePendingNetworkRequest(pendingIntent);
4160 }
4161 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4162 }
4163
4164 @Override
4165 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4166 String resultData, Bundle resultExtras) {
4167 if (DBG) log("Finished sending " + pendingIntent);
4168 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004169 // Release with a delay so the receiving client has an opportunity to put in its
4170 // own request.
4171 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004172 }
4173
Robert Greenwalt9258c642014-03-26 16:47:06 -07004174 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004175 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004176 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004177 Bundle bundle = new Bundle();
4178 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4179 new NetworkRequest(nri.request));
4180 Message msg = Message.obtain();
4181 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4182 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4183 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4184 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004185 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004186 case ConnectivityManager.CALLBACK_LOSING: {
4187 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4188 break;
4189 }
4190 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4191 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4192 new NetworkCapabilities(networkAgent.networkCapabilities));
4193 break;
4194 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004195 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004196 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4197 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004198 break;
4199 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004200 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004201 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004202 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004203 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004204 if (VDBG) {
4205 log("sending notification " + notifyTypeToName(notificationType) +
4206 " for " + nri.request);
4207 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004208 nri.messenger.send(msg);
4209 } catch (RemoteException e) {
4210 // may occur naturally in the race of binder death.
4211 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4212 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004213 }
4214
Paul Jensenc8b9a742014-09-30 15:37:41 -04004215 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4216 for (int i = 0; i < nai.networkRequests.size(); i++) {
4217 NetworkRequest nr = nai.networkRequests.valueAt(i);
4218 // Ignore listening requests.
4219 if (!isRequest(nr)) continue;
4220 loge("Dead network still had at least " + nr);
4221 break;
4222 }
4223 nai.asyncChannel.disconnect();
4224 }
4225
Robert Greenwalt7b816022014-04-18 15:25:25 -07004226 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4227 if (oldNetwork == null) {
4228 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4229 return;
4230 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004231 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4232 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004233 }
4234
Paul Jensen27b02b72014-07-14 12:03:33 -04004235 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004236 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004237 setupDataActivityTracking(newNetwork);
4238 try {
4239 mNetd.setDefaultNetId(newNetwork.network.netId);
4240 } catch (Exception e) {
4241 loge("Exception setting default network :" + e);
4242 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004243 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004244 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004245 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004246 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004247 }
4248
Paul Jensen2161a8e2014-09-11 11:00:39 -04004249 // Handles a network appearing or improving its score.
4250 //
4251 // - Evaluates all current NetworkRequests that can be
4252 // satisfied by newNetwork, and reassigns to newNetwork
4253 // any such requests for which newNetwork is the best.
4254 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004255 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004256 // needed. A network is needed if it is the best network for
4257 // one or more NetworkRequests, or if it is a VPN.
4258 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004259 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004260 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004261 //
4262 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4263 // networks that have no chance (i.e. even if validated)
4264 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004265 //
4266 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4267 // it does not remove NetworkRequests that other Networks could better satisfy.
4268 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4269 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4270 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004271 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004272 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004273 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4274 // performed to tear down unvalidated networks that have no chance (i.e. even if
4275 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004276 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004277 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004278 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004279 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004280 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004281 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004282 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004283 // Find and migrate to this Network any NetworkRequests for
4284 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004285 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004286 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004287 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004288 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004289 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4290 final boolean satisfies = newNetwork.satisfies(nri.request);
4291 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004292 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004293 log("Network " + newNetwork.name() + " was already satisfying" +
4294 " request " + nri.request.requestId + ". No change.");
4295 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004296 keep = true;
4297 continue;
4298 }
4299
4300 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004301 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004302 if (satisfies) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004303 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004304 // This is not a request, it's a callback listener.
4305 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004306 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004307 continue;
4308 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004309
Robert Greenwalt7b816022014-04-18 15:25:25 -07004310 // next check if it's better than any current network we're using for
4311 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004312 if (VDBG) {
4313 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004314 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4315 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004316 }
4317 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004318 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004319 if (DBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004320 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004321 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004322 currentNetwork.networkRequests.remove(nri.request.requestId);
4323 currentNetwork.networkLingered.add(nri.request);
4324 affectedNetworks.add(currentNetwork);
4325 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004326 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004327 }
Paul Jensen573a0352015-01-08 10:49:34 -05004328 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004329 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004330 if (!newNetwork.addRequest(nri.request)) {
4331 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4332 }
4333 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004334 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004335 // Tell NetworkFactories about the new score, so they can stop
4336 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004337 // TODO - this could get expensive if we have alot of requests for this
4338 // network. Think about if there is a way to reduce this. Push
4339 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004340 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004341 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004342 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004343 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004344 }
4345 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004346 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4347 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4348 // mark it as no longer satisfying "nri". Because networks are processed by
4349 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4350 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4351 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4352 // This means this code doesn't have to handle the case where "currentNetwork" no
4353 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4354 if (DBG) {
4355 log("Network " + newNetwork.name() + " stopped satisfying" +
4356 " request " + nri.request.requestId);
4357 }
4358 newNetwork.networkRequests.remove(nri.request.requestId);
4359 if (currentNetwork == newNetwork) {
4360 mNetworkForRequestId.remove(nri.request.requestId);
4361 sendUpdatedScoreToFactories(nri.request, 0);
4362 } else {
4363 if (nri.isRequest == true) {
4364 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4365 newNetwork.name() +
4366 " without updating mNetworkForRequestId or factories!");
4367 }
4368 }
4369 // TODO: technically, sending CALLBACK_LOST here is
4370 // incorrect if nri is a request (not a listen) and there
4371 // is a replacement network currently connected that can
4372 // satisfy it. However, the only capability that can both
4373 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4374 // so this code is only incorrect for a network that loses
4375 // the TRUSTED capability, which is a rare case.
4376 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004377 }
4378 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004379 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004380 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004381 if (nai.lingering) {
4382 // Already lingered. Nothing to do. This can only happen if "nai" is in
4383 // "affectedNetworks" twice. The reasoning being that to get added to
4384 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4385 // (i.e. not lingered) so it could have only been lingered by this loop.
4386 // unneeded(nai) will be false and we'll call unlinger() below which would
4387 // be bad, so handle it here.
4388 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004389 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004390 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004391 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004392 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004393 }
4394 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004395 if (isNewDefault) {
4396 // Notify system services that this network is up.
4397 makeDefault(newNetwork);
4398 synchronized (ConnectivityService.this) {
4399 // have a new default network, release the transition wakelock in
4400 // a second if it's held. The second pause is to allow apps
4401 // to reconnect over the new network
4402 if (mNetTransitionWakeLock.isHeld()) {
4403 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4404 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4405 mNetTransitionWakeLockSerialNumber, 0),
4406 1000);
4407 }
4408 }
4409 }
4410
4411 // do this after the default net is switched, but
4412 // before LegacyTypeTracker sends legacy broadcasts
4413 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4414
4415 if (isNewDefault) {
4416 // Maintain the illusion: since the legacy API only
4417 // understands one network at a time, we must pretend
4418 // that the current default network disconnected before
4419 // the new one connected.
4420 if (oldDefaultNetwork != null) {
4421 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4422 oldDefaultNetwork, true);
4423 }
4424 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4425 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4426 notifyLockdownVpn(newNetwork);
4427 }
4428
Robert Greenwalt7b816022014-04-18 15:25:25 -07004429 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004430 // Notify battery stats service about this network, both the normal
4431 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004432 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004433 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004434 final IBatteryStats bs = BatteryStatsService.getService();
4435 final int type = newNetwork.networkInfo.getType();
4436
4437 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4438 bs.noteNetworkInterfaceType(baseIface, type);
4439 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4440 final String stackedIface = stacked.getInterfaceName();
4441 bs.noteNetworkInterfaceType(stackedIface, type);
4442 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4443 }
4444 } catch (RemoteException ignored) {
4445 }
4446
Robert Greenwalt152ed372014-12-17 17:19:53 -08004447 // This has to happen after the notifyNetworkCallbacks as that tickles each
4448 // ConnectivityManager instance so that legacy requests correctly bind dns
4449 // requests to this network. The legacy users are listening for this bcast
4450 // and will generally do a dns request so they can ensureRouteToHost and if
4451 // they do that before the callbacks happen they'll use the default network.
4452 //
4453 // TODO: Is there still a race here? We send the broadcast
4454 // after sending the callback, but if the app can receive the
4455 // broadcast before the callback, it might still break.
4456 //
4457 // This *does* introduce a race where if the user uses the new api
4458 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4459 // they may get old info. Reverse this after the old startUsing api is removed.
4460 // This is on top of the multiple intent sequencing referenced in the todo above.
4461 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4462 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4463 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4464 // legacy type tracker filters out repeat adds
4465 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4466 }
4467 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004468
4469 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4470 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4471 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4472 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4473 if (newNetwork.isVPN()) {
4474 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4475 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004476 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004477 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4478 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004479 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004480 if (DBG) log("Reaping " + nai.name());
4481 teardownUnneededNetwork(nai);
4482 }
4483 }
4484 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004485 }
4486
Paul Jensen1c7ba022015-06-16 14:27:36 -04004487 /**
4488 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4489 * being disconnected.
4490 * @param changed If only one Network's score or capabilities have been modified since the last
4491 * time this function was called, pass this Network in this argument, otherwise pass
4492 * null.
4493 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4494 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4495 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4496 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4497 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004498 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004499 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004500 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4501 // to avoid the slowness. It is not simply enough to process just "changed", for
4502 // example in the case where "changed"'s score decreases and another network should begin
4503 // satifying a NetworkRequest that "changed" currently satisfies.
4504
4505 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4506 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4507 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004508 if (changed != null && oldScore < changed.getCurrentScore()) {
4509 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004510 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004511 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4512 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4513 // Rematch higher scoring networks first to prevent requests first matching a lower
4514 // scoring network and then a higher scoring network, which could produce multiple
4515 // callbacks and inadvertently unlinger networks.
4516 Arrays.sort(nais);
4517 for (NetworkAgentInfo nai : nais) {
4518 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004519 // Only reap the last time through the loop. Reaping before all rematching
4520 // is complete could incorrectly teardown a network that hasn't yet been
4521 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004522 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004523 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004524 }
4525 }
4526 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004527
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004528 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004529 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004530 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004531 // For now only update icons for default connection.
4532 // TODO: Update WiFi and cellular icons separately. b/17237507
4533 if (!isDefaultNetwork(nai)) return;
4534
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004535 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004536 // Don't repeat publish.
4537 if (newInetCondition == mDefaultInetConditionPublished) return;
4538
4539 mDefaultInetConditionPublished = newInetCondition;
4540 sendInetConditionBroadcast(nai.networkInfo);
4541 }
4542
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004543 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4544 if (mLockdownTracker != null) {
4545 if (nai != null && nai.isVPN()) {
4546 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4547 } else {
4548 mLockdownTracker.onNetworkInfoChanged();
4549 }
4550 }
4551 }
4552
Robert Greenwalt7b816022014-04-18 15:25:25 -07004553 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4554 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004555 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004556 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004557 synchronized (networkAgent) {
4558 oldInfo = networkAgent.networkInfo;
4559 networkAgent.networkInfo = newInfo;
4560 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004561 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004562
4563 if (oldInfo != null && oldInfo.getState() == state) {
4564 if (VDBG) log("ignoring duplicate network state non-change");
4565 return;
4566 }
4567 if (DBG) {
4568 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4569 (oldInfo == null ? "null" : oldInfo.getState()) +
4570 " to " + state);
4571 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004572
Paul Jenseneec75412014-08-04 12:21:19 -04004573 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004574 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004575 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004576 if (networkAgent.isVPN()) {
4577 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004578 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4579 (networkAgent.networkMisc == null ||
4580 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004581 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004582 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4583 networkAgent.networkCapabilities.hasCapability(
4584 NET_CAPABILITY_NOT_RESTRICTED) ?
4585 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004586 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004587 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004588 loge("Error creating network " + networkAgent.network.netId + ": "
4589 + e.getMessage());
4590 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004591 }
Paul Jenseneec75412014-08-04 12:21:19 -04004592 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004593 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004594 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004595
Paul Jensenca8f16a2014-05-09 12:47:55 -04004596 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004597 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004598
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004599 if (networkAgent.isVPN()) {
4600 // Temporarily disable the default proxy (not global).
4601 synchronized (mProxyLock) {
4602 if (!mDefaultProxyDisabled) {
4603 mDefaultProxyDisabled = true;
4604 if (mGlobalProxy == null && mDefaultProxy != null) {
4605 sendProxyBroadcast(null);
4606 }
4607 }
4608 }
4609 // TODO: support proxy per network.
4610 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004611
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004612 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4613 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4614 // capabilities, so it only needs to be done once on initial connect, not every time the
4615 // network's capabilities change. Note that we do this before rematching the network,
4616 // so we could decide to tear it down immediately afterwards. That's fine though - on
4617 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4618 // doing.
4619 updateSignalStrengthThresholds(networkAgent);
4620
Paul Jensen2161a8e2014-09-11 11:00:39 -04004621 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004622 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004623
4624 // This has to happen after matching the requests, because callbacks are just requests.
4625 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004626 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004627 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004628 if (networkAgent.isVPN()) {
4629 synchronized (mProxyLock) {
4630 if (mDefaultProxyDisabled) {
4631 mDefaultProxyDisabled = false;
4632 if (mGlobalProxy == null && mDefaultProxy != null) {
4633 sendProxyBroadcast(mDefaultProxy);
4634 }
4635 }
4636 }
4637 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004638 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4639 state == NetworkInfo.State.SUSPENDED) {
4640 // going into or coming out of SUSPEND: rescore and notify
4641 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004642 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004643 }
4644 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4645 ConnectivityManager.CALLBACK_SUSPENDED :
4646 ConnectivityManager.CALLBACK_RESUMED));
4647 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004648 }
4649 }
4650
Robert Greenwaltac96c522014-06-03 16:43:57 -07004651 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4652 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004653 if (score < 0) {
4654 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4655 "). Bumping score to min of 0");
4656 score = 0;
4657 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004658
Paul Jensen2161a8e2014-09-11 11:00:39 -04004659 final int oldScore = nai.getCurrentScore();
4660 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004661
Paul Jensen85cf78e2015-06-25 13:25:07 -04004662 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004663
Paul Jensenc8b9a742014-09-30 15:37:41 -04004664 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004665 }
4666
Robert Greenwalt9258c642014-03-26 16:47:06 -07004667 // notify only this one new request of the current state
4668 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4669 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4670 // TODO - read state from monitor to decide what to send.
4671// if (nai.networkMonitor.isLingering()) {
4672// notifyType = NetworkCallbacks.LOSING;
4673// } else if (nai.networkMonitor.isEvaluating()) {
4674// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4675// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004676 if (nri.mPendingIntent == null) {
4677 callCallbackForRequest(nri, nai, notifyType);
4678 } else {
4679 sendPendingIntentForRequest(nri, nai, notifyType);
4680 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004681 }
4682
Robert Greenwalt8d482522015-06-24 13:23:42 -07004683 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004684 // The NetworkInfo we actually send out has no bearing on the real
4685 // state of affairs. For example, if the default connection is mobile,
4686 // and a request for HIPRI has just gone away, we need to pretend that
4687 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4688 // the state to DISCONNECTED, even though the network is of type MOBILE
4689 // and is still connected.
4690 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4691 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004692 if (state != DetailedState.DISCONNECTED) {
4693 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004694 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004695 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004696 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004697 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4698 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4699 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4700 if (info.isFailover()) {
4701 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4702 nai.networkInfo.setFailover(false);
4703 }
4704 if (info.getReason() != null) {
4705 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4706 }
4707 if (info.getExtraInfo() != null) {
4708 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4709 }
4710 NetworkAgentInfo newDefaultAgent = null;
4711 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004712 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004713 if (newDefaultAgent != null) {
4714 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4715 newDefaultAgent.networkInfo);
4716 } else {
4717 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4718 }
4719 }
4720 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4721 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004722 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004723 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004724 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004725 }
4726 }
4727 }
4728
Robert Greenwalt7b816022014-04-18 15:25:25 -07004729 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004730 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004731 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004732 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4733 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4734 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004735 if (nri.mPendingIntent == null) {
4736 callCallbackForRequest(nri, networkAgent, notifyType);
4737 } else {
4738 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4739 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004740 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004741 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004742
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004743 private String notifyTypeToName(int notifyType) {
4744 switch (notifyType) {
4745 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4746 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4747 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4748 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4749 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4750 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4751 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4752 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4753 }
4754 return "UNKNOWN";
4755 }
4756
Jeff Sharkey69736342014-12-08 14:50:12 -08004757 /**
4758 * Notify other system services that set of active ifaces has changed.
4759 */
4760 private void notifyIfacesChanged() {
4761 try {
4762 mStatsService.forceUpdateIfaces();
4763 } catch (Exception ignored) {
4764 }
4765 }
4766
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004767 @Override
4768 public boolean addVpnAddress(String address, int prefixLength) {
4769 throwIfLockdownEnabled();
4770 int user = UserHandle.getUserId(Binder.getCallingUid());
4771 synchronized (mVpns) {
4772 return mVpns.get(user).addAddress(address, prefixLength);
4773 }
4774 }
4775
4776 @Override
4777 public boolean removeVpnAddress(String address, int prefixLength) {
4778 throwIfLockdownEnabled();
4779 int user = UserHandle.getUserId(Binder.getCallingUid());
4780 synchronized (mVpns) {
4781 return mVpns.get(user).removeAddress(address, prefixLength);
4782 }
4783 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004784
4785 @Override
4786 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4787 throwIfLockdownEnabled();
4788 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004789 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004790 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004791 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004792 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004793 if (success) {
4794 notifyIfacesChanged();
4795 }
4796 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004797 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004798
4799 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004800 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4801 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4802 enforceKeepalivePermission();
4803 mKeepaliveTracker.startNattKeepalive(
4804 getNetworkAgentInfoForNetwork(network),
4805 intervalSeconds, messenger, binder,
4806 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4807 }
4808
4809 @Override
4810 public void stopKeepalive(Network network, int slot) {
4811 mHandler.sendMessage(mHandler.obtainMessage(
4812 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
4813 }
4814
4815 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07004816 public void factoryReset() {
4817 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004818
4819 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4820 return;
4821 }
4822
Robin Lee3b3dd942015-05-12 18:14:58 +01004823 final int userId = UserHandle.getCallingUserId();
4824
Stuart Scottf1fb3972015-04-02 18:00:02 -07004825 // Turn airplane mode off
4826 setAirplaneMode(false);
4827
Stuart Scotte3e314d2015-04-20 14:07:45 -07004828 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4829 // Untether
4830 for (String tether : getTetheredIfaces()) {
4831 untether(tether);
4832 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004833 }
4834
Stuart Scotte3e314d2015-04-20 14:07:45 -07004835 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4836 // Turn VPN off
4837 VpnConfig vpnConfig = getVpnConfig(userId);
4838 if (vpnConfig != null) {
4839 if (vpnConfig.legacy) {
4840 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4841 } else {
4842 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4843 // in the future without user intervention.
4844 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004845
Stuart Scotte3e314d2015-04-20 14:07:45 -07004846 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4847 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004848 }
4849 }
4850 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004851
4852 @VisibleForTesting
4853 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
4854 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
4855 return new NetworkMonitor(context, handler, nai, defaultRequest);
4856 }
4857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004858}