blob: 6190a5ab357e1300df8cde602700f15179308899 [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
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900362 /** Handler thread used for both of the handlers below. */
363 @VisibleForTesting
364 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700365 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700366 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700367 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700368 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700369
Mike Lockwood0f79b542009-08-14 14:18:49 -0400370 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800371 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400372
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700373 private PowerManager.WakeLock mNetTransitionWakeLock;
374 private String mNetTransitionWakeLockCausedBy = "";
375 private int mNetTransitionWakeLockSerialNumber;
376 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800377 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700378
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700379 private InetAddress mDefaultDns;
380
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700381 // used in DBG mode to track inet condition reports
382 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
383 private ArrayList mInetLog;
384
Robert Greenwalt434203a2010-10-11 16:00:27 -0700385 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400386 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700387 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700388 private boolean mDefaultProxyDisabled = false;
389
Robert Greenwalt434203a2010-10-11 16:00:27 -0700390 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400391 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700392
Jason Monk602b2322013-07-03 17:04:33 -0400393 private PacManager mPacManager = null;
394
Erik Klineda4bfa82015-04-30 12:58:40 +0900395 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700396
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400397 private UserManager mUserManager;
398
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700399 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700400 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700401
Robert Greenwalt50393202011-06-21 17:26:14 -0700402 // the set of network types that can only be enabled by system/sig apps
403 List mProtectedNetworks;
404
John Spurlockbf991a82013-06-24 14:20:23 -0400405 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700406
Wink Savilleab9321d2013-06-29 21:10:57 -0700407 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400408
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900409 private KeepaliveTracker mKeepaliveTracker;
410
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700411 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
412 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700413 private final static int MAX_NET_ID = 65535;
414 private int mNextNetId = MIN_NET_ID;
415
Robert Greenwalt34524f02014-05-18 16:22:10 -0700416 // sequence number of NetworkRequests
417 private int mNextNetworkRequestId = 1;
418
Erik Kline7523eb32015-07-09 18:24:03 +0900419 // NetworkRequest activity String log entries.
420 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
421 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
422
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700423 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
424 private static final int MAX_VALIDATION_LOGS = 10;
425 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
426 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
427
428 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
429 synchronized(mValidationLogs) {
430 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
431 mValidationLogs.removeLast();
432 }
433 mValidationLogs.addFirst(new Pair(network, log));
434 }
435 }
436
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700437 /**
438 * Implements support for the legacy "one network per network type" model.
439 *
440 * We used to have a static array of NetworkStateTrackers, one for each
441 * network type, but that doesn't work any more now that we can have,
442 * for example, more that one wifi network. This class stores all the
443 * NetworkAgentInfo objects that support a given type, but the legacy
444 * API will only see the first one.
445 *
446 * It serves two main purposes:
447 *
448 * 1. Provide information about "the network for a given type" (since this
449 * API only supports one).
450 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
451 * the first network for a given type changes, or if the default network
452 * changes.
453 */
454 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900455
456 private static final boolean DBG = true;
457 private static final boolean VDBG = false;
458 private static final String TAG = "CSLegacyTypeTracker";
459
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700460 /**
461 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
462 * Each list holds references to all NetworkAgentInfos that are used to
463 * satisfy requests for that network type.
464 *
465 * This array is built out at startup such that an unsupported network
466 * doesn't get an ArrayList instance, making this a tristate:
467 * unsupported, supported but not active and active.
468 *
469 * The actual lists are populated when we scan the network types that
470 * are supported on this device.
471 */
472 private ArrayList<NetworkAgentInfo> mTypeLists[];
473
474 public LegacyTypeTracker() {
475 mTypeLists = (ArrayList<NetworkAgentInfo>[])
476 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
477 }
478
479 public void addSupportedType(int type) {
480 if (mTypeLists[type] != null) {
481 throw new IllegalStateException(
482 "legacy list for type " + type + "already initialized");
483 }
484 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
485 }
486
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700487 public boolean isTypeSupported(int type) {
488 return isNetworkTypeValid(type) && mTypeLists[type] != null;
489 }
490
491 public NetworkAgentInfo getNetworkForType(int type) {
492 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
493 return mTypeLists[type].get(0);
494 } else {
495 return null;
496 }
497 }
498
Robert Greenwalt8d482522015-06-24 13:23:42 -0700499 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900500 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900501 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700502 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900503 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900504 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900505 }
506 }
507
508 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700509 public void add(int type, NetworkAgentInfo nai) {
510 if (!isTypeSupported(type)) {
511 return; // Invalid network type.
512 }
513 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
514
515 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
516 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700517 return;
518 }
519
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900520 list.add(nai);
521
522 // 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 +0900523 final boolean isDefaultNetwork = isDefaultNetwork(nai);
524 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700525 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
526 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700527 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700528 }
529
Lorenzo Colittia793a672014-07-31 23:20:17 +0900530 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900531 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900532 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
533 if (list == null || list.isEmpty()) {
534 return;
535 }
536
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900537 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900538
539 if (!list.remove(nai)) {
540 return;
541 }
542
Robert Greenwalt8d482522015-06-24 13:23:42 -0700543 final DetailedState state = DetailedState.DISCONNECTED;
544
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900545 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700546 maybeLogBroadcast(nai, state, type, wasDefault);
547 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900548 }
549
550 if (!list.isEmpty() && wasFirstNetwork) {
551 if (DBG) log("Other network available for type " + type +
552 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900553 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700554 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
555 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900556 }
557 }
558
559 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900560 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
561 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700562 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900563 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700564 }
565 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700566
Robert Greenwalt8d482522015-06-24 13:23:42 -0700567 // send out another legacy broadcast - currently only used for suspend/unsuspend
568 // toggle
569 public void update(NetworkAgentInfo nai) {
570 final boolean isDefault = isDefaultNetwork(nai);
571 final DetailedState state = nai.networkInfo.getDetailedState();
572 for (int type = 0; type < mTypeLists.length; type++) {
573 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700574 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700575 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700576 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 maybeLogBroadcast(nai, state, type, isDefault);
578 sendLegacyNetworkBroadcast(nai, state, type);
579 }
580 }
581 }
582
Lorenzo Colittia793a672014-07-31 23:20:17 +0900583 private String naiToString(NetworkAgentInfo nai) {
584 String name = (nai != null) ? nai.name() : "null";
585 String state = (nai.networkInfo != null) ?
586 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
587 "???/???";
588 return name + " " + state;
589 }
590
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700591 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900592 pw.println("mLegacyTypeTracker:");
593 pw.increaseIndent();
594 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700595 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900596 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700597 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900598 pw.println();
599 pw.println("Current state:");
600 pw.increaseIndent();
601 for (int type = 0; type < mTypeLists.length; type++) {
602 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
603 for (NetworkAgentInfo nai : mTypeLists[type]) {
604 pw.println(type + " " + naiToString(nai));
605 }
606 }
607 pw.decreaseIndent();
608 pw.decreaseIndent();
609 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700610 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900611
612 // This class needs its own log method because it has a different TAG.
613 private void log(String s) {
614 Slog.d(TAG, s);
615 }
616
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700617 }
618 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
619
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900620 @VisibleForTesting
621 protected HandlerThread createHandlerThread() {
622 return new HandlerThread("ConnectivityServiceThread");
623 }
624
Jeff Sharkey899223b2012-08-04 15:24:58 -0700625 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700626 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800627 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800628
Erik Klineda4bfa82015-04-30 12:58:40 +0900629 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900630 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
631 new Binder(), NetworkRequestInfo.REQUEST);
632 mNetworkRequests.put(mDefaultRequest, defaultNRI);
633 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900634
635 mDefaultMobileDataRequest = createInternetRequestForTransport(
636 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700637
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900638 mHandlerThread = createHandlerThread();
639 mHandlerThread.start();
640 mHandler = new InternalHandler(mHandlerThread.getLooper());
641 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700642
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800643 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800644 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
645 String id = Settings.Secure.getString(context.getContentResolver(),
646 Settings.Secure.ANDROID_ID);
647 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700648 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800649 SystemProperties.set("net.hostname", name);
650 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800651 }
652
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700653 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700654 String dns = Settings.Global.getString(context.getContentResolver(),
655 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700656 if (dns == null || dns.length() == 0) {
657 dns = context.getResources().getString(
658 com.android.internal.R.string.config_default_dns_server);
659 }
660 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800661 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
662 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800663 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700664 }
665
Jeremy Joslin79294842014-12-03 17:15:28 -0800666 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
667 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
668
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700669 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700670 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800671 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700672 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700673 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700674 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700675
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700676 try {
677 mPolicyManager.registerListener(mPolicyListener);
678 } catch (RemoteException e) {
679 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700680 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700681 }
682
683 final PowerManager powerManager = (PowerManager) context.getSystemService(
684 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700685 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
686 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
687 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800688 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700689
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700690 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700691
Wink Saville51f456f2013-04-23 14:26:51 -0700692 // TODO: What is the "correct" way to do determine if this is a wifi only device?
693 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
694 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700695 String[] naStrings = context.getResources().getStringArray(
696 com.android.internal.R.array.networkAttributes);
697 for (String naString : naStrings) {
698 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700699 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700700 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700701 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800702 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700703 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700704 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700705 }
Wink Saville51f456f2013-04-23 14:26:51 -0700706 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
707 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
708 n.type);
709 continue;
710 }
Wink Saville975c8482011-04-07 14:23:45 -0700711 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800712 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700713 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700714 continue;
715 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700716 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700717
Wink Saville975c8482011-04-07 14:23:45 -0700718 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700719 mNetworksDefined++;
720 } catch(Exception e) {
721 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700722 }
723 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700724
725 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
726 if (mNetConfigs[TYPE_VPN] == null) {
727 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
728 // don't need to add TYPE_VPN to mNetConfigs.
729 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
730 mNetworksDefined++; // used only in the log() statement below.
731 }
732
Wink Saville5e56bc52013-07-29 15:00:57 -0700733 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700734
Robert Greenwalt50393202011-06-21 17:26:14 -0700735 mProtectedNetworks = new ArrayList<Integer>();
736 int[] protectedNetworks = context.getResources().getIntArray(
737 com.android.internal.R.array.config_protectedNetworks);
738 for (int p : protectedNetworks) {
739 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
740 mProtectedNetworks.add(p);
741 } else {
742 if (DBG) loge("Ignoring protectedNetwork " + p);
743 }
744 }
745
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700746 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
747 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700748
Robert Greenwaltfab501672014-07-23 11:44:01 -0700749 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800750
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700751 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
752
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700753 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700754 IntentFilter intentFilter = new IntentFilter();
755 intentFilter.addAction(Intent.ACTION_USER_STARTING);
756 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
757 mContext.registerReceiverAsUser(
758 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900759
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700760 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700761 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700762 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700763 } catch (RemoteException e) {
764 loge("Error registering observer :" + e);
765 }
766
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700767 if (DBG) {
768 mInetLog = new ArrayList();
769 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700770
Erik Klineda4bfa82015-04-30 12:58:40 +0900771 mSettingsObserver = new SettingsObserver(mContext, mHandler);
772 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800773
John Spurlockbf991a82013-06-24 14:20:23 -0400774 mDataConnectionStats = new DataConnectionStats(mContext);
775 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400776
Jason Monkdecd2952013-10-10 14:02:51 -0400777 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700778
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400779 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900780
781 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700783
Erik Klineda4bfa82015-04-30 12:58:40 +0900784 private NetworkRequest createInternetRequestForTransport(int transportType) {
785 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900786 netCap.addCapability(NET_CAPABILITY_INTERNET);
787 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900788 if (transportType > -1) {
789 netCap.addTransportType(transportType);
790 }
791 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
792 }
793
794 private void handleMobileDataAlwaysOn() {
795 final boolean enable = (Settings.Global.getInt(
796 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
797 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
798 if (enable == isEnabled) {
799 return; // Nothing to do.
800 }
801
802 if (enable) {
803 handleRegisterNetworkRequest(new NetworkRequestInfo(
804 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
805 } else {
806 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
807 }
808 }
809
810 private void registerSettingsCallbacks() {
811 // Watch for global HTTP proxy changes.
812 mSettingsObserver.observe(
813 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
814 EVENT_APPLY_GLOBAL_HTTP_PROXY);
815
816 // Watch for whether or not to keep mobile data always on.
817 mSettingsObserver.observe(
818 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
819 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
820 }
821
Robert Greenwalt34524f02014-05-18 16:22:10 -0700822 private synchronized int nextNetworkRequestId() {
823 return mNextNetworkRequestId++;
824 }
825
Paul Jensen67b0b072015-06-10 11:22:17 -0400826 @VisibleForTesting
827 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400828 synchronized (mNetworkForNetId) {
829 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
830 int netId = mNextNetId;
831 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
832 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500833 if (!mNetIdInUse.get(netId)) {
834 mNetIdInUse.put(netId, true);
835 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400836 }
837 }
838 }
839 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700840 }
841
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800842 private NetworkState getFilteredNetworkState(int networkType, int uid) {
843 NetworkInfo info = null;
844 LinkProperties lp = null;
845 NetworkCapabilities nc = null;
846 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800847 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800848
849 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
850 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
851 if (nai != null) {
852 synchronized (nai) {
853 info = new NetworkInfo(nai.networkInfo);
854 lp = new LinkProperties(nai.linkProperties);
855 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400856 // Network objects are outwardly immutable so there is no point to duplicating.
857 // Duplicating also precludes sharing socket factories and connection pools.
858 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800859 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800860 }
861 info.setType(networkType);
862 } else {
863 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
864 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
865 info.setIsAvailable(true);
866 lp = new LinkProperties();
867 nc = new NetworkCapabilities();
868 network = null;
869 }
870 info = getFilteredNetworkInfo(info, lp, uid);
871 }
872
Jeff Sharkey32566012014-12-02 18:30:14 -0800873 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400874 }
875
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800876 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
877 if (network == null) {
878 return null;
879 }
880 synchronized (mNetworkForNetId) {
881 return mNetworkForNetId.get(network.netId);
882 }
883 };
884
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900885 private Network[] getVpnUnderlyingNetworks(int uid) {
886 if (!mLockdownEnabled) {
887 int user = UserHandle.getUserId(uid);
888 synchronized (mVpns) {
889 Vpn vpn = mVpns.get(user);
890 if (vpn != null && vpn.appliesToUid(uid)) {
891 return vpn.getUnderlyingNetworks();
892 }
893 }
894 }
895 return null;
896 }
897
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800898 private NetworkState getUnfilteredActiveNetworkState(int uid) {
899 NetworkInfo info = null;
900 LinkProperties lp = null;
901 NetworkCapabilities nc = null;
902 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800903 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800904
Paul Jensen85cf78e2015-06-25 13:25:07 -0400905 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800906
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900907 final Network[] networks = getVpnUnderlyingNetworks(uid);
908 if (networks != null) {
909 // getUnderlyingNetworks() returns:
910 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
911 // empty array => the VPN explicitly said "no default network".
912 // non-empty array => the VPN specified one or more default networks; we use the
913 // first one.
914 if (networks.length > 0) {
915 nai = getNetworkAgentInfoForNetwork(networks[0]);
916 } else {
917 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800918 }
919 }
920
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800921 if (nai != null) {
922 synchronized (nai) {
923 info = new NetworkInfo(nai.networkInfo);
924 lp = new LinkProperties(nai.linkProperties);
925 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400926 // Network objects are outwardly immutable so there is no point to duplicating.
927 // Duplicating also precludes sharing socket factories and connection pools.
928 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800929 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800930 }
931 }
932
Jeff Sharkey32566012014-12-02 18:30:14 -0800933 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400934 }
935
936 /**
937 * Check if UID should be blocked from using the network with the given LinkProperties.
938 */
939 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700940 final boolean networkCostly;
941 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700942
Robert Greenwalt12e67352014-05-13 21:41:06 -0700943 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700944 synchronized (mRulesLock) {
945 networkCostly = mMeteredIfaces.contains(iface);
946 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700947 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700948
Amith Yamasani15e472352015-04-24 19:06:07 -0700949 if ((uidRules & RULE_REJECT_ALL) != 0
950 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700951 return true;
952 }
953
954 // no restrictive rules; network is visible
955 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700956 }
957
958 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700959 * Return a filtered {@link NetworkInfo}, potentially marked
960 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800961 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700962 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800963 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
964 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400965 // network is blocked; clone and override state
966 info = new NetworkInfo(info);
967 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900968 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900969 log("returning Blocked NetworkInfo for ifname=" +
970 lp.getInterfaceName() + ", uid=" + uid);
971 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700972 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800973 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700974 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900975 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700976 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700977 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700978 }
979
980 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 * Return NetworkInfo for the active (i.e., connected) network interface.
982 * It is assumed that at most one network is active at a time. If more
983 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700984 * @return the info for the active network, or {@code null} if none is
985 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700987 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700989 enforceAccessPermission();
990 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800991 NetworkState state = getUnfilteredActiveNetworkState(uid);
992 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
994
Paul Jensen31a94f42015-02-13 14:18:39 -0500995 @Override
996 public Network getActiveNetwork() {
997 enforceAccessPermission();
998 final int uid = Binder.getCallingUid();
999 final int user = UserHandle.getUserId(uid);
1000 int vpnNetId = NETID_UNSET;
1001 synchronized (mVpns) {
1002 final Vpn vpn = mVpns.get(user);
1003 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1004 }
1005 NetworkAgentInfo nai;
1006 if (vpnNetId != NETID_UNSET) {
1007 synchronized (mNetworkForNetId) {
1008 nai = mNetworkForNetId.get(vpnNetId);
1009 }
1010 if (nai != null) return nai.network;
1011 }
1012 nai = getDefaultNetwork();
1013 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1014 return nai != null ? nai.network : null;
1015 }
1016
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001017 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1018 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001019 final int uid = Binder.getCallingUid();
1020 NetworkState state = getUnfilteredActiveNetworkState(uid);
1021 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001022 }
1023
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001024 @Override
1025 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1026 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001027 NetworkState state = getUnfilteredActiveNetworkState(uid);
1028 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001029 }
1030
1031 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 public NetworkInfo getNetworkInfo(int networkType) {
1033 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001034 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001035 if (getVpnUnderlyingNetworks(uid) != null) {
1036 // A VPN is active, so we may need to return one of its underlying networks. This
1037 // information is not available in LegacyTypeTracker, so we have to get it from
1038 // getUnfilteredActiveNetworkState.
1039 NetworkState state = getUnfilteredActiveNetworkState(uid);
1040 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1041 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1042 }
1043 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001044 NetworkState state = getFilteredNetworkState(networkType, uid);
1045 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 }
1047
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001048 @Override
1049 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1050 enforceAccessPermission();
1051 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001052 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001053 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1054 if (nai != null) {
1055 synchronized (nai) {
1056 info = new NetworkInfo(nai.networkInfo);
1057 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001058 }
1059 }
1060 return info;
1061 }
1062
1063 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 public NetworkInfo[] getAllNetworkInfo() {
1065 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001066 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001067 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1068 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001069 NetworkInfo info = getNetworkInfo(networkType);
1070 if (info != null) {
1071 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001074 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001077 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001078 public Network getNetworkForType(int networkType) {
1079 enforceAccessPermission();
1080 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001081 NetworkState state = getFilteredNetworkState(networkType, uid);
1082 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1083 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001084 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001085 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001086 }
1087
1088 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001089 public Network[] getAllNetworks() {
1090 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001091 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001092 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001093 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001094 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001095 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001096 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001097 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001098 }
1099
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001100 @Override
1101 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1102 // The basic principle is: if an app's traffic could possibly go over a
1103 // network, without the app doing anything multinetwork-specific,
1104 // (hence, by "default"), then include that network's capabilities in
1105 // the array.
1106 //
1107 // In the normal case, app traffic only goes over the system's default
1108 // network connection, so that's the only network returned.
1109 //
1110 // With a VPN in force, some app traffic may go into the VPN, and thus
1111 // over whatever underlying networks the VPN specifies, while other app
1112 // traffic may go over the system default network (e.g.: a split-tunnel
1113 // VPN, or an app disallowed by the VPN), so the set of networks
1114 // returned includes the VPN's underlying networks and the system
1115 // default.
1116 enforceAccessPermission();
1117
1118 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1119
1120 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001121 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001122 if (nc != null) {
1123 result.put(nai.network, nc);
1124 }
1125
1126 if (!mLockdownEnabled) {
1127 synchronized (mVpns) {
1128 Vpn vpn = mVpns.get(userId);
1129 if (vpn != null) {
1130 Network[] networks = vpn.getUnderlyingNetworks();
1131 if (networks != null) {
1132 for (Network network : networks) {
1133 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001134 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001135 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001136 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001137 }
1138 }
1139 }
1140 }
1141 }
1142 }
1143
1144 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1145 out = result.values().toArray(out);
1146 return out;
1147 }
1148
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001149 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001150 public boolean isNetworkSupported(int networkType) {
1151 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001152 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001153 }
1154
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001155 /**
1156 * Return LinkProperties for the active (i.e., connected) default
1157 * network interface. It is assumed that at most one default network
1158 * is active at a time. If more than one is active, it is indeterminate
1159 * which will be returned.
1160 * @return the ip properties for the active network, or {@code null} if
1161 * none is active
1162 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001163 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001164 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001165 enforceAccessPermission();
1166 final int uid = Binder.getCallingUid();
1167 NetworkState state = getUnfilteredActiveNetworkState(uid);
1168 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001169 }
1170
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001171 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001172 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001173 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001174 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1175 if (nai != null) {
1176 synchronized (nai) {
1177 return new LinkProperties(nai.linkProperties);
1178 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001179 }
1180 return null;
1181 }
1182
Robert Greenwalt12e67352014-05-13 21:41:06 -07001183 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001184 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001185 public LinkProperties getLinkProperties(Network network) {
1186 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001188 if (nai != null) {
1189 synchronized (nai) {
1190 return new LinkProperties(nai.linkProperties);
1191 }
1192 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001193 return null;
1194 }
1195
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001196 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001197 if (nai != null) {
1198 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001199 if (nai.networkCapabilities != null) {
1200 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001201 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001202 }
1203 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001204 return null;
1205 }
1206
1207 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001208 public NetworkCapabilities getNetworkCapabilities(Network network) {
1209 enforceAccessPermission();
1210 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1211 }
1212
1213 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001214 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001215 // Require internal since we're handing out IMSI details
1216 enforceConnectivityInternalPermission();
1217
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001218 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001219 for (Network network : getAllNetworks()) {
1220 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1221 if (nai != null) {
1222 synchronized (nai) {
1223 final String subscriberId = (nai.networkMisc != null)
1224 ? nai.networkMisc.subscriberId : null;
1225 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1226 nai.networkCapabilities, network, subscriberId, null));
1227 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001228 }
1229 }
1230 return result.toArray(new NetworkState[result.size()]);
1231 }
1232
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001233 @Override
1234 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1235 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001237 final long token = Binder.clearCallingIdentity();
1238 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1240 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001241 try {
1242 return mPolicyManager.getNetworkQuotaInfo(state);
1243 } catch (RemoteException e) {
1244 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001245 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001246 return null;
1247 } finally {
1248 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001249 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001250 }
1251
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001252 @Override
1253 public boolean isActiveNetworkMetered() {
1254 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001255 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001256 final long token = Binder.clearCallingIdentity();
1257 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001258 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001259 } finally {
1260 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001261 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001262 }
1263
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001264 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1265 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1266 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001267 try {
1268 return mPolicyManager.isNetworkMetered(state);
1269 } catch (RemoteException e) {
1270 }
1271 }
1272 return false;
1273 }
1274
Jeff Sharkey216c1812012-08-05 14:29:23 -07001275 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1276 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001277 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001278 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001279 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001280 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001281 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001282
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001283 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 * Ensure that a network route exists to deliver traffic to the specified
1285 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001286 * @param networkType the type of the network over which traffic to the
1287 * specified host is to be routed
1288 * @param hostAddress the IP address of the host to which the route is
1289 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 * @return {@code true} on success, {@code false} on failure
1291 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001292 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001294 if (mProtectedNetworks.contains(networkType)) {
1295 enforceConnectivityInternalPermission();
1296 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001297
Chad Brubakerc0234532014-02-14 13:24:29 -08001298 InetAddress addr;
1299 try {
1300 addr = InetAddress.getByAddress(hostAddress);
1301 } catch (UnknownHostException e) {
1302 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1303 return false;
1304 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001307 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 return false;
1309 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001310
1311 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1312 if (nai == null) {
1313 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1314 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1315 } else {
1316 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1317 }
1318 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001319 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001320
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001321 DetailedState netState;
1322 synchronized (nai) {
1323 netState = nai.networkInfo.getDetailedState();
1324 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001325
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001326 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001327 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001328 log("requestRouteToHostAddress on down network "
1329 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001330 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001331 }
1332 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001334
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001335 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001336 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001337 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001338 LinkProperties lp;
1339 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001340 synchronized (nai) {
1341 lp = nai.linkProperties;
1342 netId = nai.network.netId;
1343 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001344 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001345 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1346 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001347 } finally {
1348 Binder.restoreCallingIdentity(token);
1349 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001350 }
1351
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001352 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001353 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001354 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001355 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001356 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001357 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001358 if (bestRoute.getGateway().equals(addr)) {
1359 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001360 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001361 } else {
1362 // if we will connect to this through another route, add a direct route
1363 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001364 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001365 }
1366 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001367 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001368 try {
1369 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1370 } catch (Exception e) {
1371 // never crash - catch them all
1372 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001373 return false;
1374 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001375 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
1377
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001378 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1379 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001380 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001381 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001382 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001383 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001384 }
1385
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001386 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001387 // skip update when we've already applied rules
1388 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1389 if (oldRules == uidRules) return;
1390
1391 mUidRules.put(uid, uidRules);
1392 }
1393
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001394 // TODO: notify UID when it has requested targeted updates
1395 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001396
1397 @Override
1398 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001399 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001400 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001401 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001402 }
1403
1404 synchronized (mRulesLock) {
1405 mMeteredIfaces.clear();
1406 for (String iface : meteredIfaces) {
1407 mMeteredIfaces.add(iface);
1408 }
1409 }
1410 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001411
1412 @Override
1413 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1414 // caller is NPMS, since we only register with them
1415 if (LOGD_RULES) {
1416 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1417 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001418 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001419 };
1420
Robin Lee3b3dd942015-05-12 18:14:58 +01001421 /**
1422 * Require that the caller is either in the same user or has appropriate permission to interact
1423 * across users.
1424 *
1425 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1426 */
1427 private void enforceCrossUserPermission(int userId) {
1428 if (userId == UserHandle.getCallingUserId()) {
1429 // Not a cross-user call.
1430 return;
1431 }
1432 mContext.enforceCallingOrSelfPermission(
1433 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1434 "ConnectivityService");
1435 }
1436
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001437 private void enforceInternetPermission() {
1438 mContext.enforceCallingOrSelfPermission(
1439 android.Manifest.permission.INTERNET,
1440 "ConnectivityService");
1441 }
1442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001444 mContext.enforceCallingOrSelfPermission(
1445 android.Manifest.permission.ACCESS_NETWORK_STATE,
1446 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 }
1448
1449 private void enforceChangePermission() {
Billy Laua7238a32015-08-01 12:45:02 +01001450 int uid = Binder.getCallingUid();
1451 Settings.checkAndNoteChangeNetworkStateOperation(mContext, uid, Settings
1452 .getPackageNameForUid(mContext, uid), true);
1453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 }
1455
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001456 private void enforceTetherAccessPermission() {
1457 mContext.enforceCallingOrSelfPermission(
1458 android.Manifest.permission.ACCESS_NETWORK_STATE,
1459 "ConnectivityService");
1460 }
1461
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001462 private void enforceConnectivityInternalPermission() {
1463 mContext.enforceCallingOrSelfPermission(
1464 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1465 "ConnectivityService");
1466 }
1467
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001468 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001469 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001470 }
1471
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001472 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001473 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001474 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001475 }
1476
1477 private void sendInetConditionBroadcast(NetworkInfo info) {
1478 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1479 }
1480
Wink Saville628b0852011-08-04 15:01:58 -07001481 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001482 if (mLockdownTracker != null) {
1483 info = mLockdownTracker.augmentNetworkInfo(info);
1484 }
1485
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001486 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001487 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001488 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 if (info.isFailover()) {
1490 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1491 info.setFailover(false);
1492 }
1493 if (info.getReason() != null) {
1494 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1495 }
1496 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001497 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1498 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001500 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001501 return intent;
1502 }
1503
1504 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1505 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1506 }
1507
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001508 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001509 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1510 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1511 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001512 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001513 final long ident = Binder.clearCallingIdentity();
1514 try {
1515 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1516 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1517 } finally {
1518 Binder.restoreCallingIdentity(ident);
1519 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001520 }
1521
Mike Lockwood0f79b542009-08-14 14:18:49 -04001522 private void sendStickyBroadcast(Intent intent) {
1523 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001524 if (!mSystemReady) {
1525 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001526 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001527 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001528 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001529 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001530 }
1531
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001532 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001533 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001534 final NetworkInfo ni = intent.getParcelableExtra(
1535 ConnectivityManager.EXTRA_NETWORK_INFO);
1536 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1537 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1538 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1539 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001540 final IBatteryStats bs = BatteryStatsService.getService();
1541 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001542 bs.noteConnectivityChanged(intent.getIntExtra(
1543 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1544 ni != null ? ni.getState().toString() : "?");
1545 } catch (RemoteException e) {
1546 }
1547 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001548 try {
1549 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1550 } finally {
1551 Binder.restoreCallingIdentity(ident);
1552 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001553 }
1554 }
1555
1556 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001557 loadGlobalProxy();
1558
Mike Lockwood0f79b542009-08-14 14:18:49 -04001559 synchronized(this) {
1560 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001561 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001562 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001563 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001564 }
1565 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001566 // load the global proxy at startup
1567 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001568
1569 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1570 // for user to unlock device.
1571 if (!updateLockdownVpn()) {
1572 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1573 mContext.registerReceiver(mUserPresentReceiver, filter);
1574 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001575
Erik Klineda4bfa82015-04-30 12:58:40 +09001576 // Configure whether mobile data is always on.
1577 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1578
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001579 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001580
1581 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001584 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1585 @Override
1586 public void onReceive(Context context, Intent intent) {
1587 // Try creating lockdown tracker, since user present usually means
1588 // unlocked keystore.
1589 if (updateLockdownVpn()) {
1590 mContext.unregisterReceiver(this);
1591 }
1592 }
1593 };
1594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001596 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001597 *
1598 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001599 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001600 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001601 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1602 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001603
1604 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001605 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001606
Robert Greenwalt7b816022014-04-18 15:25:25 -07001607 if (networkAgent.networkCapabilities.hasTransport(
1608 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001609 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1610 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001611 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001612 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001613 } else if (networkAgent.networkCapabilities.hasTransport(
1614 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001615 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1616 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001617 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001618 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001619 } else {
1620 // do not track any other networks
1621 timeout = 0;
1622 }
1623
Robert Greenwalt7b816022014-04-18 15:25:25 -07001624 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001625 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001626 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001627 } catch (Exception e) {
1628 // You shall not crash!
1629 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001630 }
1631 }
1632 }
1633
1634 /**
1635 * Remove data activity tracking when network disconnects.
1636 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001637 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1638 final String iface = networkAgent.linkProperties.getInterfaceName();
1639 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001640
Robert Greenwalt7b816022014-04-18 15:25:25 -07001641 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1642 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001643 try {
1644 // the call fails silently if no idletimer setup for this interface
1645 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001646 } catch (Exception e) {
1647 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001648 }
1649 }
1650 }
1651
1652 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001653 * Reads the network specific MTU size from reources.
1654 * and set it on it's iface.
1655 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001656 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1657 final String iface = newLp.getInterfaceName();
1658 final int mtu = newLp.getMtu();
1659 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1660 if (VDBG) log("identical MTU - not setting");
1661 return;
1662 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001663
Robert Greenwalt43074032014-08-15 17:53:05 -07001664 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001665 loge("Unexpected mtu value: " + mtu + ", " + iface);
1666 return;
1667 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001668
w1997615afd812014-08-05 15:18:11 -07001669 // Cannot set MTU without interface name
1670 if (TextUtils.isEmpty(iface)) {
1671 loge("Setting MTU size with null iface.");
1672 return;
1673 }
1674
Robert Greenwalt7b816022014-04-18 15:25:25 -07001675 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001676 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001677 mNetd.setMtu(iface, mtu);
1678 } catch (Exception e) {
1679 Slog.e(TAG, "exception in setMtu()" + e);
1680 }
1681 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001682
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001683 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001684 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1685
1686 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001687 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001688 protected int getDefaultTcpRwnd() {
1689 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1690 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001691
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001692 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1693 if (isDefaultNetwork(nai) == false) {
1694 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001695 }
1696
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001697 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1698 String[] values = null;
1699 if (tcpBufferSizes != null) {
1700 values = tcpBufferSizes.split(",");
1701 }
1702
1703 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001704 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001705 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1706 values = tcpBufferSizes.split(",");
1707 }
1708
1709 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1710
1711 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001712 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001713
1714 final String prefix = "/sys/kernel/ipv4/tcp_";
1715 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1716 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1717 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1718 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1719 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1720 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1721 mCurrentTcpBufferSizes = tcpBufferSizes;
1722 } catch (IOException e) {
1723 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001724 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001725
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001726 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001727 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001728 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1729 if (rwndValue != 0) {
1730 SystemProperties.set(sysctlKey, rwndValue.toString());
1731 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001732 }
1733
Mattias Falk8b47b362011-08-23 14:15:13 +02001734 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001735 /*
1736 * Tell the VMs to toss their DNS caches
1737 */
1738 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1739 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001740 /*
1741 * Connectivity events can happen before boot has completed ...
1742 */
1743 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001744 final long ident = Binder.clearCallingIdentity();
1745 try {
1746 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1747 } finally {
1748 Binder.restoreCallingIdentity(ident);
1749 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001750 }
1751
Robert Greenwalt562cc542014-05-15 18:07:26 -07001752 @Override
1753 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001754 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1755 NETWORK_RESTORE_DELAY_PROP_NAME);
1756 if(restoreDefaultNetworkDelayStr != null &&
1757 restoreDefaultNetworkDelayStr.length() != 0) {
1758 try {
1759 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1760 } catch (NumberFormatException e) {
1761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001763 // if the system property isn't set, use the value for the apn type
1764 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1765
1766 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1767 (mNetConfigs[networkType] != null)) {
1768 ret = mNetConfigs[networkType].restoreTime;
1769 }
1770 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 }
1772
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001773 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001774 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001775 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001776 }
1777 return false;
1778 }
1779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001781 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1782 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001783 if (mContext.checkCallingOrSelfPermission(
1784 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001786 pw.println("Permission Denial: can't dump ConnectivityService " +
1787 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1788 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 return;
1790 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001791
Erik Kline379747a2015-06-05 17:47:34 +09001792 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001793 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001794 final long DIAG_TIME_MS = 5000;
1795 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1796 // Start gathering diagnostic information.
1797 netDiags.add(new NetworkDiagnostics(
1798 nai.network,
Lorenzo Colitti87cfc702015-07-27 16:35:33 +09001799 new LinkProperties(nai.linkProperties), // Must be a copy.
Erik Kline379747a2015-06-05 17:47:34 +09001800 DIAG_TIME_MS));
1801 }
1802
1803 for (NetworkDiagnostics netDiag : netDiags) {
1804 pw.println();
1805 netDiag.waitForMeasurements();
1806 netDiag.dump(pw);
1807 }
1808
1809 return;
1810 }
1811
Lorenzo Colittie3805462015-06-03 11:18:24 +09001812 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001813 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001814 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001815 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001816 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001817 pw.println();
1818
Paul Jensen85cf78e2015-06-25 13:25:07 -04001819 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001820 pw.print("Active default network: ");
1821 if (defaultNai == null) {
1822 pw.println("none");
1823 } else {
1824 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001826 pw.println();
1827
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001828 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001829 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001830 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1831 pw.println(nai.toString());
1832 pw.increaseIndent();
1833 pw.println("Requests:");
1834 pw.increaseIndent();
1835 for (int i = 0; i < nai.networkRequests.size(); i++) {
1836 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001837 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001838 pw.decreaseIndent();
1839 pw.println("Lingered:");
1840 pw.increaseIndent();
1841 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1842 pw.decreaseIndent();
1843 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001844 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001845 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001846 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001847
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001848 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001849 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001850 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1851 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001852 }
1853 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001854 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001855
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001856 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001857
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001858 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001859 pw.print("mNetTransitionWakeLock: currently " +
1860 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1861 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1862 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1863 } else {
1864 pw.println(", last requested never");
1865 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001866 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001867
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001868 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001869 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001870
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001871 pw.println();
1872 mKeepaliveTracker.dump(pw);
1873
Lorenzo Colittie3805462015-06-03 11:18:24 +09001874 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001875 pw.println();
1876 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001877 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001878 for(int i = 0; i < mInetLog.size(); i++) {
1879 pw.println(mInetLog.get(i));
1880 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001881 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001882 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001883
1884 if (argsContain(args, "--short") == false) {
1885 pw.println();
1886 synchronized (mValidationLogs) {
1887 pw.println("mValidationLogs (most recent first):");
1888 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1889 pw.println(p.first);
1890 pw.increaseIndent();
1891 p.second.dump(fd, pw, args);
1892 pw.decreaseIndent();
1893 }
1894 }
Erik Kline7523eb32015-07-09 18:24:03 +09001895
1896 pw.println();
1897 pw.println("mNetworkRequestInfoLogs (most recent first):");
1898 pw.increaseIndent();
1899 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1900 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001904 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001905 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001906 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001907 if (officialNai != null && officialNai.equals(nai)) return true;
1908 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001909 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001910 " - " + nai);
1911 }
1912 return false;
1913 }
1914
Paul Jensenc8b9a742014-09-30 15:37:41 -04001915 private boolean isRequest(NetworkRequest request) {
1916 return mNetworkRequests.get(request).isRequest;
1917 }
1918
Robert Greenwalt42acef32009-08-12 16:08:25 -07001919 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001920 private class NetworkStateTrackerHandler extends Handler {
1921 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001922 super(looper);
1923 }
1924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 @Override
1926 public void handleMessage(Message msg) {
1927 NetworkInfo info;
1928 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001929 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001930 handleAsyncChannelHalfConnect(msg);
1931 break;
1932 }
1933 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1934 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1935 if (nai != null) nai.asyncChannel.disconnect();
1936 break;
1937 }
1938 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1939 handleAsyncChannelDisconnected(msg);
1940 break;
1941 }
1942 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1943 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1944 if (nai == null) {
1945 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1946 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001947 final NetworkCapabilities networkCapabilities =
1948 (NetworkCapabilities)msg.obj;
1949 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1950 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001951 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Paul Jensen1c7ba022015-06-16 14:27:36 -04001952 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001953 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1954 networkCapabilities)) {
1955 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1956 + nai.networkCapabilities + " -> " + networkCapabilities);
1957 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001958 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001959 }
1960 break;
1961 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001962 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1963 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1964 if (nai == null) {
1965 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1966 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001967 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001968 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001969 "; created=" + nai.created);
1970 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001971 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001972 synchronized (nai) {
1973 nai.linkProperties = (LinkProperties)msg.obj;
1974 }
Paul Jenseneec75412014-08-04 12:21:19 -04001975 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001976 }
1977 break;
1978 }
1979 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1980 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1981 if (nai == null) {
1982 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1983 break;
1984 }
1985 info = (NetworkInfo) msg.obj;
1986 updateNetworkInfo(nai, info);
1987 break;
1988 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001989 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1990 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1991 if (nai == null) {
1992 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1993 break;
1994 }
1995 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001996 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001997 break;
1998 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001999 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
2000 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2001 if (nai == null) {
2002 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
2003 break;
2004 }
2005 try {
2006 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002007 } catch (Exception e) {
2008 // Never crash!
2009 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002010 }
2011 break;
2012 }
2013 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2014 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2015 if (nai == null) {
2016 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
2017 break;
2018 }
2019 try {
2020 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002021 } catch (Exception e) {
2022 // Never crash!
2023 loge("Exception in removeVpnUidRanges: " + e);
2024 }
2025 break;
2026 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002027 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2028 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2029 if (nai == null) {
2030 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
2031 break;
2032 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002033 if (nai.created && !nai.networkMisc.explicitlySelected) {
2034 loge("ERROR: created network explicitly selected.");
2035 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002036 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002037 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002038 break;
2039 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002040 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2041 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2042 if (nai == null) {
2043 loge("EVENT_PACKET_KEEPALIVE from unknown NetworkAgent");
2044 break;
2045 }
2046 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2047 break;
2048 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002049 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002050 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002051 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2052 final boolean valid =
2053 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002054 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2055 if (valid != nai.lastValidated) {
2056 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002057 nai.lastValidated = valid;
2058 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002059 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002060 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2061 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002062 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002063 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002064 // Let the NetworkAgent know the state of its network
2065 nai.asyncChannel.sendMessage(
2066 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2067 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2068 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002069 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002070 break;
2071 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002072 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002073 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002074 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2075 handleLingerComplete(nai);
2076 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002077 break;
2078 }
Paul Jensen869868be2014-05-15 10:33:05 -04002079 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002080 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002081 final boolean visible = (msg.arg1 != 0);
2082 final NetworkAgentInfo nai;
2083 synchronized (mNetworkForNetId) {
2084 nai = mNetworkForNetId.get(netId);
2085 }
2086 // If captive portal status has changed, update capabilities.
2087 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2088 nai.lastCaptivePortalDetected = visible;
2089 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002090 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002091 }
2092 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002093 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002094 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002095 if (nai == null) {
2096 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2097 break;
2098 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002099 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002100 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2101 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002102 }
Paul Jensen869868be2014-05-15 10:33:05 -04002103 break;
2104 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002105 }
2106 }
2107 }
2108
Paul Jensen85cf78e2015-06-25 13:25:07 -04002109 private void linger(NetworkAgentInfo nai) {
2110 nai.lingering = true;
2111 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2112 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2113 }
2114
Paul Jensen0cc17322014-11-25 15:26:53 -05002115 // Cancel any lingering so the linger timeout doesn't teardown a network.
2116 // This should be called when a network begins satisfying a NetworkRequest.
2117 // Note: depending on what state the NetworkMonitor is in (e.g.,
2118 // if it's awaiting captive portal login, or if validation failed), this
2119 // may trigger a re-evaluation of the network.
2120 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002121 nai.networkLingered.clear();
2122 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002123 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002124 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002125 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2126 }
2127
Robert Greenwalt7b816022014-04-18 15:25:25 -07002128 private void handleAsyncChannelHalfConnect(Message msg) {
2129 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002130 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002131 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2132 if (VDBG) log("NetworkFactory connected");
2133 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002134 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002135 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002136 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002137 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002138 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 }
2140 } else {
2141 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002142 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 }
2144 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2145 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2146 if (VDBG) log("NetworkAgent connected");
2147 // A network agent has requested a connection. Establish the connection.
2148 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2149 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2150 } else {
2151 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002152 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002153 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002154 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002155 synchronized (mNetworkForNetId) {
2156 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002157 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002158 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002159 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002160 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002161 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002162 }
2163 }
2164 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002165
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 private void handleAsyncChannelDisconnected(Message msg) {
2167 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2168 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002169 if (DBG) {
2170 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2171 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002172 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002173 // TODO - if we move the logic to the network agent (have them disconnect
2174 // because they lost all their requests or because their score isn't good)
2175 // then they would disconnect organically, report their new state and then
2176 // disconnect the channel.
2177 if (nai.networkInfo.isConnected()) {
2178 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2179 null, null);
2180 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002181 final boolean wasDefault = isDefaultNetwork(nai);
2182 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002183 mDefaultInetConditionPublished = 0;
2184 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002185 notifyIfacesChanged();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002186 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2187 // by other networks that are already connected. Perhaps that can be done by
2188 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2189 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002190 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002191 mKeepaliveTracker.handleStopAllKeepalives(nai,
2192 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002193 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002194 mNetworkAgentInfos.remove(msg.replyTo);
2195 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002196 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002197 // Remove the NetworkAgent, but don't mark the netId as
2198 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002199 mNetworkForNetId.remove(nai.network.netId);
2200 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002201 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002202 for (int i = 0; i < nai.networkRequests.size(); i++) {
2203 NetworkRequest request = nai.networkRequests.valueAt(i);
2204 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2205 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2206 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002207 sendUpdatedScoreToFactories(request, 0);
2208 }
2209 }
2210 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2211 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002212 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002213 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002214 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002215 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002216 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002217 if (nai.created) {
2218 // Tell netd to clean up the configuration for this network
2219 // (routing rules, DNS, etc).
2220 // This may be slow as it requires a lot of netd shelling out to ip and
2221 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2222 // after we've rematched networks with requests which should make a potential
2223 // fallback network the default or requested a new network from the
2224 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2225 // long time.
2226 try {
2227 mNetd.removeNetwork(nai.network.netId);
2228 } catch (Exception e) {
2229 loge("Exception removing network: " + e);
2230 }
2231 }
2232 synchronized (mNetworkForNetId) {
2233 mNetIdInUse.delete(nai.network.netId);
2234 }
2235 } else {
2236 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2237 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002238 }
2239 }
2240
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002241 // If this method proves to be too slow then we can maintain a separate
2242 // pendingIntent => NetworkRequestInfo map.
2243 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2244 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2245 Intent intent = pendingIntent.getIntent();
2246 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2247 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2248 if (existingPendingIntent != null &&
2249 existingPendingIntent.getIntent().filterEquals(intent)) {
2250 return entry.getValue();
2251 }
2252 }
2253 return null;
2254 }
2255
2256 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2257 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2258
2259 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2260 if (existingRequest != null) { // remove the existing request.
2261 if (DBG) log("Replacing " + existingRequest.request + " with "
2262 + nri.request + " because their intents matched.");
2263 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2264 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002265 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002266 }
2267
Erik Klineda4bfa82015-04-30 12:58:40 +09002268 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002269 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002270 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002271 if (!nri.isRequest) {
2272 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002273 if (nri.request.networkCapabilities.hasSignalStrength() &&
2274 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2275 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002276 }
2277 }
2278 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002279 rematchAllNetworksAndRequests(null, 0);
2280 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2281 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002282 }
2283 }
2284
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002285 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2286 int callingUid) {
2287 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2288 if (nri != null) {
2289 handleReleaseNetworkRequest(nri.request, callingUid);
2290 }
2291 }
2292
Paul Jensen99364842014-12-09 11:43:45 -05002293 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002294 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2295 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002296 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002297 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002298 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2299 // If this Network is already the highest scoring Network for a request, or if
2300 // there is hope for it to become one if it validated, then it is needed.
2301 if (nri.isRequest && nai.satisfies(nri.request) &&
2302 (nai.networkRequests.get(nri.request.requestId) != null ||
2303 // Note that this catches two important cases:
2304 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2305 // is currently satisfying the request. This is desirable when
2306 // cellular ends up validating but WiFi does not.
2307 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002308 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002309 // WiFi ends up validating and out scoring cellular.
2310 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2311 nai.getCurrentScoreAsValidated())) {
2312 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002313 }
2314 }
Paul Jensene0988542015-06-25 15:30:08 -04002315 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002316 }
2317
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002318 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2319 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002320 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002321 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002322 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2323 return;
2324 }
2325 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002326 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002327 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002328 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002329 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002330 // Find all networks that are satisfying this request and remove the request
2331 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002332 // TODO - it's my understanding that for a request there is only a single
2333 // network satisfying it, so this loop is wasteful
2334 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002335 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2336 if (nai.networkRequests.get(nri.request.requestId) != null) {
2337 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002338 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002339 log(" Removing from current network " + nai.name() +
2340 ", leaving " + nai.networkRequests.size() +
2341 " requests.");
2342 }
Paul Jensen99364842014-12-09 11:43:45 -05002343 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002344 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002345 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002346 } else {
2347 // suspect there should only be one pass through here
2348 // but if any were kept do the check below
2349 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002350 }
2351 }
2352 }
2353
Robert Greenwalt51481852015-01-08 14:43:31 -08002354 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2355 if (nai != null) {
2356 mNetworkForRequestId.remove(nri.request.requestId);
2357 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002358 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002359 // that a network connected to serve it, even though the network was already
2360 // connected. Now that this request has gone away, we might have to pretend
2361 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002362 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002363 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2364 boolean doRemove = true;
2365 if (wasKept) {
2366 // check if any of the remaining requests for this network are for the
2367 // same legacy type - if so, don't remove the nai
2368 for (int i = 0; i < nai.networkRequests.size(); i++) {
2369 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2370 if (otherRequest.legacyType == nri.request.legacyType &&
2371 isRequest(otherRequest)) {
2372 if (DBG) log(" still have other legacy request - leaving");
2373 doRemove = false;
2374 }
2375 }
2376 }
2377
2378 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002379 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002380 }
2381 }
2382
Robert Greenwalta67be032014-05-16 15:49:14 -07002383 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002384 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2385 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002386 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002387 } else {
2388 // listens don't have a singular affectedNetwork. Check all networks to see
2389 // if this listen request applies and remove it.
2390 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2391 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002392 if (nri.request.networkCapabilities.hasSignalStrength() &&
2393 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2394 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002395 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002396 }
2397 }
2398 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2399 }
2400 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002401
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002402 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2403 enforceConnectivityInternalPermission();
2404 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2405 accept ? 1 : 0, always ? 1: 0, network));
2406 }
2407
2408 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2409 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2410 " accept=" + accept + " always=" + always);
2411
2412 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2413 if (nai == null) {
2414 // Nothing to do.
2415 return;
2416 }
2417
2418 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002419 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002420 return;
2421 }
2422
2423 if (!nai.networkMisc.explicitlySelected) {
2424 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2425 }
2426
2427 if (accept != nai.networkMisc.acceptUnvalidated) {
2428 int oldScore = nai.getCurrentScore();
2429 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002430 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002431 sendUpdatedScoreToFactories(nai);
2432 }
2433
2434 if (always) {
2435 nai.asyncChannel.sendMessage(
2436 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2437 }
2438
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002439 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002440 // Tell the NetworkAgent to not automatically reconnect to the network.
2441 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2442 // Teardown the nework.
2443 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002444 }
2445
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002446 }
2447
2448 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002449 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002450 mHandler.sendMessageDelayed(
2451 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2452 PROMPT_UNVALIDATED_DELAY_MS);
2453 }
2454
2455 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002456 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002457 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2458
2459 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2460 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002461 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002462 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002463 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2464 return;
2465 }
2466
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002467 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002468 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002469 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2470 intent.setClassName("com.android.settings",
2471 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002472
2473 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2474 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2475 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002476 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002477 }
2478
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002479 private class InternalHandler extends Handler {
2480 public InternalHandler(Looper looper) {
2481 super(looper);
2482 }
2483
2484 @Override
2485 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002486 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002487 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002488 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002489 String causedBy = null;
2490 synchronized (ConnectivityService.this) {
2491 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2492 mNetTransitionWakeLock.isHeld()) {
2493 mNetTransitionWakeLock.release();
2494 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002495 } else {
2496 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002497 }
2498 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002499 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2500 log("Failed to find a new network - expiring NetTransition Wakelock");
2501 } else {
2502 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2503 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002504 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002505 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002506 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002507 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002508 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002509 break;
2510 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002511 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002512 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002513 sendStickyBroadcast(intent);
2514 break;
2515 }
Jason Monkdecd2952013-10-10 14:02:51 -04002516 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002517 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002518 break;
2519 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002520 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002521 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2522 break;
2523 }
2524 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2525 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002526 break;
2527 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002528 case EVENT_REGISTER_NETWORK_AGENT: {
2529 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2530 break;
2531 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002532 case EVENT_REGISTER_NETWORK_REQUEST:
2533 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002534 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002535 break;
2536 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002537 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2538 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002539 handleRegisterNetworkRequestWithIntent(msg);
2540 break;
2541 }
2542 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2543 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2544 break;
2545 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002546 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002547 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002548 break;
2549 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002550 case EVENT_SET_ACCEPT_UNVALIDATED: {
2551 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2552 break;
2553 }
2554 case EVENT_PROMPT_UNVALIDATED: {
2555 handlePromptUnvalidated((Network) msg.obj);
2556 break;
2557 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002558 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2559 handleMobileDataAlwaysOn();
2560 break;
2561 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002562 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2563 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2564 mKeepaliveTracker.handleStartKeepalive(msg);
2565 break;
2566 }
2567 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2568 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2569 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2570 int slot = msg.arg1;
2571 int reason = msg.arg2;
2572 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2573 break;
2574 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002575 case EVENT_SYSTEM_READY: {
2576 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2577 nai.networkMonitor.systemReady = true;
2578 }
2579 break;
2580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 }
2582 }
2583 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002584
2585 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002586 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002587 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002588 if (isTetheringSupported()) {
2589 return mTethering.tether(iface);
2590 } else {
2591 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2592 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002593 }
2594
2595 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002596 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002597 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002598
2599 if (isTetheringSupported()) {
2600 return mTethering.untether(iface);
2601 } else {
2602 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2603 }
2604 }
2605
2606 // javadoc from interface
2607 public int getLastTetherError(String iface) {
2608 enforceTetherAccessPermission();
2609
2610 if (isTetheringSupported()) {
2611 return mTethering.getLastTetherError(iface);
2612 } else {
2613 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2614 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002615 }
2616
2617 // TODO - proper iface API for selection by property, inspection, etc
2618 public String[] getTetherableUsbRegexs() {
2619 enforceTetherAccessPermission();
2620 if (isTetheringSupported()) {
2621 return mTethering.getTetherableUsbRegexs();
2622 } else {
2623 return new String[0];
2624 }
2625 }
2626
2627 public String[] getTetherableWifiRegexs() {
2628 enforceTetherAccessPermission();
2629 if (isTetheringSupported()) {
2630 return mTethering.getTetherableWifiRegexs();
2631 } else {
2632 return new String[0];
2633 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002634 }
2635
Danica Chang6fdd0c62010-08-11 14:54:43 -07002636 public String[] getTetherableBluetoothRegexs() {
2637 enforceTetherAccessPermission();
2638 if (isTetheringSupported()) {
2639 return mTethering.getTetherableBluetoothRegexs();
2640 } else {
2641 return new String[0];
2642 }
2643 }
2644
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002645 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002646 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002647 if (isTetheringSupported()) {
2648 return mTethering.setUsbTethering(enable);
2649 } else {
2650 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2651 }
2652 }
2653
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002654 // TODO - move iface listing, queries, etc to new module
2655 // javadoc from interface
2656 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002657 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002658 return mTethering.getTetherableIfaces();
2659 }
2660
2661 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002662 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002663 return mTethering.getTetheredIfaces();
2664 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002665
Robert Greenwalt5a735062010-03-02 17:25:02 -08002666 public String[] getTetheringErroredIfaces() {
2667 enforceTetherAccessPermission();
2668 return mTethering.getErroredIfaces();
2669 }
2670
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002671 public String[] getTetheredDhcpRanges() {
2672 enforceConnectivityInternalPermission();
2673 return mTethering.getTetheredDhcpRanges();
2674 }
2675
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002676 // if ro.tether.denied = true we default to no tethering
2677 // gservices could set the secure setting to 1 though to enable it on a build where it
2678 // had previously been turned off.
2679 public boolean isTetheringSupported() {
2680 enforceTetherAccessPermission();
2681 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002682 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002683 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2684 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002685 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2686 mTethering.getTetherableWifiRegexs().length != 0 ||
2687 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2688 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002689 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002690
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002691 // Called when we lose the default network and have no replacement yet.
2692 // This will automatically be cleared after X seconds or a new default network
2693 // becomes CONNECTED, whichever happens first. The timer is started by the
2694 // first caller and not restarted by subsequent callers.
2695 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002696 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002697 synchronized (this) {
2698 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002699 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002700 mNetTransitionWakeLock.acquire();
2701 mNetTransitionWakeLockCausedBy = forWhom;
2702 }
2703 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002704 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002705 mNetTransitionWakeLockTimeout);
2706 return;
2707 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002708
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002709 // 100 percent is full good, 0 is full bad.
2710 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002711 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002712 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002713 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002714 }
2715
Paul Jensenbfd17b72015-04-07 12:43:13 -04002716 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002717 enforceAccessPermission();
2718 enforceInternetPermission();
2719
Paul Jensenbfd17b72015-04-07 12:43:13 -04002720 NetworkAgentInfo nai;
2721 if (network == null) {
2722 nai = getDefaultNetwork();
2723 } else {
2724 nai = getNetworkAgentInfoForNetwork(network);
2725 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002726 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2727 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2728 return;
2729 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002730 // Revalidate if the app report does not match our current validated state.
2731 if (hasConnectivity == nai.lastValidated) return;
2732 final int uid = Binder.getCallingUid();
2733 if (DBG) {
2734 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2735 ") by " + uid);
2736 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002737 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002738 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2739 // which isn't meant to work on uncreated networks.
2740 if (!nai.created) return;
2741
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002742 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002743
2744 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2745 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002746 }
2747
Paul Jensencee9b512015-05-06 07:32:40 -04002748 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002749 // this information is already available as a world read/writable jvm property
2750 // so this API change wouldn't have a benifit. It also breaks the passing
2751 // of proxy info to all the JVMs.
2752 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002753 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002754 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002755 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2756 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002757 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002758 }
2759
Paul Jensencee9b512015-05-06 07:32:40 -04002760 public ProxyInfo getProxyForNetwork(Network network) {
2761 if (network == null) return getDefaultProxy();
2762 final ProxyInfo globalProxy = getGlobalProxy();
2763 if (globalProxy != null) return globalProxy;
2764 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2765 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2766 // caller may not have.
2767 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2768 if (nai == null) return null;
2769 synchronized (nai) {
2770 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2771 if (proxyInfo == null) return null;
2772 return new ProxyInfo(proxyInfo);
2773 }
2774 }
2775
Paul Jensene0bef712014-12-10 15:12:18 -05002776 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2777 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2778 // proxy is null then there is no proxy in place).
2779 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2780 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2781 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2782 proxy = null;
2783 }
2784 return proxy;
2785 }
2786
2787 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2788 // better for determining if a new proxy broadcast is necessary:
2789 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2790 // avoid unnecessary broadcasts.
2791 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2792 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2793 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2794 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2795 // all set.
2796 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2797 a = canonicalizeProxyInfo(a);
2798 b = canonicalizeProxyInfo(b);
2799 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2800 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2801 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2802 }
2803
Jason Monk207900c2014-04-25 15:00:09 -04002804 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002805 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002806
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002807 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002808 if (proxyProperties == mGlobalProxy) return;
2809 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2810 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2811
2812 String host = "";
2813 int port = 0;
2814 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002815 String pacFileUrl = "";
2816 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002817 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002818 if (!proxyProperties.isValid()) {
2819 if (DBG)
2820 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2821 return;
2822 }
Jason Monk207900c2014-04-25 15:00:09 -04002823 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002824 host = mGlobalProxy.getHost();
2825 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002826 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002827 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002828 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002829 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002830 } else {
2831 mGlobalProxy = null;
2832 }
2833 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002834 final long token = Binder.clearCallingIdentity();
2835 try {
2836 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2837 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2838 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2839 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002840 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002841 } finally {
2842 Binder.restoreCallingIdentity(token);
2843 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002844
Jason Monkcf0f97a2014-10-02 15:39:38 -04002845 if (mGlobalProxy == null) {
2846 proxyProperties = mDefaultProxy;
2847 }
2848 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002849 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002850 }
2851
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002852 private void loadGlobalProxy() {
2853 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002854 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2855 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2856 String exclList = Settings.Global.getString(res,
2857 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002858 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2859 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002860 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002861 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002862 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002863 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002864 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002865 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002866 if (!proxyProperties.isValid()) {
2867 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2868 return;
2869 }
2870
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002871 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002872 mGlobalProxy = proxyProperties;
2873 }
2874 }
2875 }
2876
Jason Monk207900c2014-04-25 15:00:09 -04002877 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002878 // this information is already available as a world read/writable jvm property
2879 // so this API change wouldn't have a benifit. It also breaks the passing
2880 // of proxy info to all the JVMs.
2881 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002882 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002883 return mGlobalProxy;
2884 }
2885 }
2886
Jason Monk207900c2014-04-25 15:00:09 -04002887 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002888 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002889 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002890 proxy = null;
2891 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002892 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002893 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002894 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002895 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002896 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2897 return;
2898 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002899
2900 // This call could be coming from the PacManager, containing the port of the local
2901 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2902 // global (to get the correct local port), and send a broadcast.
2903 // TODO: Switch PacManager to have its own message to send back rather than
2904 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002905 if ((mGlobalProxy != null) && (proxy != null)
2906 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002907 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2908 mGlobalProxy = proxy;
2909 sendProxyBroadcast(mGlobalProxy);
2910 return;
2911 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002912 mDefaultProxy = proxy;
2913
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002914 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002915 if (!mDefaultProxyDisabled) {
2916 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002917 }
2918 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002919 }
2920
Paul Jensene0bef712014-12-10 15:12:18 -05002921 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2922 // This method gets called when any network changes proxy, but the broadcast only ever contains
2923 // the default proxy (even if it hasn't changed).
2924 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2925 // world where an app might be bound to a non-default network.
2926 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2927 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2928 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2929
2930 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2931 sendProxyBroadcast(getDefaultProxy());
2932 }
2933 }
2934
Robert Greenwalt434203a2010-10-11 16:00:27 -07002935 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002936 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2937 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002938 if (!TextUtils.isEmpty(proxy)) {
2939 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002940 if (data.length == 0) {
2941 return;
2942 }
2943
Robert Greenwalt434203a2010-10-11 16:00:27 -07002944 String proxyHost = data[0];
2945 int proxyPort = 8080;
2946 if (data.length > 1) {
2947 try {
2948 proxyPort = Integer.parseInt(data[1]);
2949 } catch (NumberFormatException e) {
2950 return;
2951 }
2952 }
Jason Monk207900c2014-04-25 15:00:09 -04002953 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002954 setGlobalProxy(p);
2955 }
2956 }
2957
Jason Monk207900c2014-04-25 15:00:09 -04002958 private void sendProxyBroadcast(ProxyInfo proxy) {
2959 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002960 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002961 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002962 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002963 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2964 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002965 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002966 final long ident = Binder.clearCallingIdentity();
2967 try {
2968 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2969 } finally {
2970 Binder.restoreCallingIdentity(ident);
2971 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002972 }
2973
2974 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002975 final private HashMap<Uri, Integer> mUriEventMap;
2976 final private Context mContext;
2977 final private Handler mHandler;
2978
2979 SettingsObserver(Context context, Handler handler) {
2980 super(null);
2981 mUriEventMap = new HashMap<Uri, Integer>();
2982 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002983 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002984 }
2985
Erik Klineda4bfa82015-04-30 12:58:40 +09002986 void observe(Uri uri, int what) {
2987 mUriEventMap.put(uri, what);
2988 final ContentResolver resolver = mContext.getContentResolver();
2989 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002990 }
2991
2992 @Override
2993 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002994 Slog.wtf(TAG, "Should never be reached.");
2995 }
2996
2997 @Override
2998 public void onChange(boolean selfChange, Uri uri) {
2999 final Integer what = mUriEventMap.get(uri);
3000 if (what != null) {
3001 mHandler.obtainMessage(what.intValue()).sendToTarget();
3002 } else {
3003 loge("No matching event to send for URI=" + uri);
3004 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003005 }
3006 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003007
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003008 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003009 Slog.d(TAG, s);
3010 }
3011
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003012 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003013 Slog.e(TAG, s);
3014 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003015
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003016 private static <T> T checkNotNull(T value, String message) {
3017 if (value == null) {
3018 throw new NullPointerException(message);
3019 }
3020 return value;
3021 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003022
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003023 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003024 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003025 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3026 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3027 *
3028 * @param oldPackage Package name of the application which currently controls VPN, which will
3029 * be replaced. If there is no such application, this should should either be
3030 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3031 * @param newPackage Package name of the application which should gain control of VPN, or
3032 * {@code null} to disable.
3033 * @param userId User for whom to prepare the new VPN.
3034 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003035 * @hide
3036 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003037 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003038 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3039 int userId) {
3040 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003041 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003042
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003043 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003044 Vpn vpn = mVpns.get(userId);
3045 if (vpn != null) {
3046 return vpn.prepare(oldPackage, newPackage);
3047 } else {
3048 return false;
3049 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003050 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003051 }
3052
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003053 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003054 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3055 * This method is used by system-privileged apps.
3056 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3057 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3058 *
3059 * @param packageName The package for which authorization state should change.
3060 * @param userId User for whom {@code packageName} is installed.
3061 * @param authorized {@code true} if this app should be able to start a VPN connection without
3062 * explicit user approval, {@code false} if not.
3063 *
Jeff Davidson05542602014-08-11 14:07:27 -07003064 * @hide
3065 */
3066 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003067 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3068 enforceCrossUserPermission(userId);
3069
Jeff Davidson05542602014-08-11 14:07:27 -07003070 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003071 Vpn vpn = mVpns.get(userId);
3072 if (vpn != null) {
3073 vpn.setPackageAuthorization(packageName, authorized);
3074 }
Jeff Davidson05542602014-08-11 14:07:27 -07003075 }
3076 }
3077
3078 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003079 * Configure a TUN interface and return its file descriptor. Parameters
3080 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003081 * and not available in ConnectivityManager. Permissions are checked in
3082 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003083 * @hide
3084 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003085 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003086 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003087 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003088 int user = UserHandle.getUserId(Binder.getCallingUid());
3089 synchronized(mVpns) {
3090 return mVpns.get(user).establish(config);
3091 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003092 }
3093
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003094 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003095 * Start legacy VPN, controlling native daemons as needed. Creates a
3096 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003097 */
3098 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003099 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003100 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003101 final LinkProperties egress = getActiveLinkProperties();
3102 if (egress == null) {
3103 throw new IllegalStateException("Missing active network connection");
3104 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003105 int user = UserHandle.getUserId(Binder.getCallingUid());
3106 synchronized(mVpns) {
3107 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3108 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003109 }
3110
3111 /**
3112 * Return the information of the ongoing legacy VPN. This method is used
3113 * by VpnSettings and not available in ConnectivityManager. Permissions
3114 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003115 */
3116 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003117 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3118 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003119 if (mLockdownEnabled) {
3120 return null;
3121 }
3122
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003123 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003124 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003125 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003126 }
3127
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003128 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003129 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3130 * and not available in ConnectivityManager.
3131 */
3132 @Override
3133 public VpnInfo[] getAllVpnInfo() {
3134 enforceConnectivityInternalPermission();
3135 if (mLockdownEnabled) {
3136 return new VpnInfo[0];
3137 }
3138
3139 synchronized(mVpns) {
3140 List<VpnInfo> infoList = new ArrayList<>();
3141 for (int i = 0; i < mVpns.size(); i++) {
3142 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3143 if (info != null) {
3144 infoList.add(info);
3145 }
3146 }
3147 return infoList.toArray(new VpnInfo[infoList.size()]);
3148 }
3149 }
3150
3151 /**
3152 * @return VPN information for accounting, or null if we can't retrieve all required
3153 * information, e.g primary underlying iface.
3154 */
3155 @Nullable
3156 private VpnInfo createVpnInfo(Vpn vpn) {
3157 VpnInfo info = vpn.getVpnInfo();
3158 if (info == null) {
3159 return null;
3160 }
3161 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3162 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3163 // the underlyingNetworks list.
3164 if (underlyingNetworks == null) {
3165 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3166 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3167 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3168 }
3169 } else if (underlyingNetworks.length > 0) {
3170 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3171 if (linkProperties != null) {
3172 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3173 }
3174 }
3175 return info.primaryUnderlyingIface == null ? null : info;
3176 }
3177
3178 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003179 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3180 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003181 * Permissions are checked in Vpn class.
3182 * @hide
3183 */
3184 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003185 public VpnConfig getVpnConfig(int userId) {
3186 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003187 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003188 Vpn vpn = mVpns.get(userId);
3189 if (vpn != null) {
3190 return vpn.getVpnConfig();
3191 } else {
3192 return null;
3193 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003194 }
3195 }
3196
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003197 @Override
3198 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003199 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3200 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3201 return false;
3202 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003203
3204 // Tear down existing lockdown if profile was removed
3205 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3206 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003207 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003208 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3209 return false;
3210 }
3211
3212 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3213 final VpnProfile profile = VpnProfile.decode(
3214 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003215 int user = UserHandle.getUserId(Binder.getCallingUid());
3216 synchronized(mVpns) {
3217 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3218 profile));
3219 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003220 } else {
3221 setLockdownTracker(null);
3222 }
3223
3224 return true;
3225 }
3226
3227 /**
3228 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3229 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3230 */
3231 private void setLockdownTracker(LockdownVpnTracker tracker) {
3232 // Shutdown any existing tracker
3233 final LockdownVpnTracker existing = mLockdownTracker;
3234 mLockdownTracker = null;
3235 if (existing != null) {
3236 existing.shutdown();
3237 }
3238
3239 try {
3240 if (tracker != null) {
3241 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003242 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003243 mLockdownTracker = tracker;
3244 mLockdownTracker.init();
3245 } else {
3246 mNetd.setFirewallEnabled(false);
3247 }
3248 } catch (RemoteException e) {
3249 // ignored; NMS lives inside system_server
3250 }
3251 }
3252
3253 private void throwIfLockdownEnabled() {
3254 if (mLockdownEnabled) {
3255 throw new IllegalStateException("Unavailable in lockdown mode");
3256 }
3257 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003258
Wink Savilleab9321d2013-06-29 21:10:57 -07003259 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003260 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003261 // TODO: Remove? Any reason to trigger a provisioning check?
3262 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003263 }
3264
3265 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003266 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003267
Paul Jensen89e0f092014-09-15 15:59:36 -04003268 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003269 if (DBG) {
3270 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003271 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003272 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003273 Intent intent = new Intent(action);
3274 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003275 // Concatenate the range of types onto the range of NetIDs.
3276 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003277 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003278 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003279 }
3280
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003281 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003282 * Show or hide network provisioning notifications.
3283 *
3284 * We use notifications for two purposes: to notify that a network requires sign in
3285 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3286 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3287 * particular network we can display the notification type that was most recently requested.
3288 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3289 * might first display NO_INTERNET, and then when the captive portal check completes, display
3290 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003291 *
3292 * @param id an identifier that uniquely identifies this notification. This must match
3293 * between show and hide calls. We use the NetID value but for legacy callers
3294 * we concatenate the range of types with the range of NetIDs.
3295 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003296 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003297 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3298 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003299 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003300 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3301 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003302 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003303 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003304
3305 Resources r = Resources.getSystem();
3306 NotificationManager notificationManager = (NotificationManager) mContext
3307 .getSystemService(Context.NOTIFICATION_SERVICE);
3308
3309 if (visible) {
3310 CharSequence title;
3311 CharSequence details;
3312 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003313 if (notifyType == NotificationType.NO_INTERNET &&
3314 networkType == ConnectivityManager.TYPE_WIFI) {
3315 title = r.getString(R.string.wifi_no_internet, 0);
3316 details = r.getString(R.string.wifi_no_internet_detailed);
3317 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3318 } else if (notifyType == NotificationType.SIGN_IN) {
3319 switch (networkType) {
3320 case ConnectivityManager.TYPE_WIFI:
3321 title = r.getString(R.string.wifi_available_sign_in, 0);
3322 details = r.getString(R.string.network_available_sign_in_detailed,
3323 extraInfo);
3324 icon = R.drawable.stat_notify_wifi_in_range;
3325 break;
3326 case ConnectivityManager.TYPE_MOBILE:
3327 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3328 title = r.getString(R.string.network_available_sign_in, 0);
3329 // TODO: Change this to pull from NetworkInfo once a printable
3330 // name has been added to it
3331 details = mTelephonyManager.getNetworkOperatorName();
3332 icon = R.drawable.stat_notify_rssi_in_range;
3333 break;
3334 default:
3335 title = r.getString(R.string.network_available_sign_in, 0);
3336 details = r.getString(R.string.network_available_sign_in_detailed,
3337 extraInfo);
3338 icon = R.drawable.stat_notify_rssi_in_range;
3339 break;
3340 }
3341 } else {
3342 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3343 + getNetworkTypeName(networkType));
3344 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003345 }
3346
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003347 Notification notification = new Notification.Builder(mContext)
3348 .setWhen(0)
3349 .setSmallIcon(icon)
3350 .setAutoCancel(true)
3351 .setTicker(title)
3352 .setColor(mContext.getColor(
3353 com.android.internal.R.color.system_notification_accent_color))
3354 .setContentTitle(title)
3355 .setContentText(details)
3356 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003357 .setLocalOnly(true)
3358 .setPriority(highPriority ?
3359 Notification.PRIORITY_HIGH :
3360 Notification.PRIORITY_DEFAULT)
3361 .setDefaults(Notification.DEFAULT_ALL)
3362 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003363 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003364
Wink Saville948282b2013-08-29 08:55:16 -07003365 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003366 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003367 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003368 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003369 npe.printStackTrace();
3370 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003371 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003372 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003373 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003374 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003375 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003376 npe.printStackTrace();
3377 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003378 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003379 }
3380
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003381 /** Location to an updatable file listing carrier provisioning urls.
3382 * An example:
3383 *
3384 * <?xml version="1.0" encoding="utf-8"?>
3385 * <provisioningUrls>
3386 * <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 -07003387 * </provisioningUrls>
3388 */
3389 private static final String PROVISIONING_URL_PATH =
3390 "/data/misc/radio/provisioning_urls.xml";
3391 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003392
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003393 /** XML tag for root element. */
3394 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3395 /** XML tag for individual url */
3396 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003397 /** XML attribute for mcc */
3398 private static final String ATTR_MCC = "mcc";
3399 /** XML attribute for mnc */
3400 private static final String ATTR_MNC = "mnc";
3401
Paul Jensen434dde82015-06-11 09:43:30 -04003402 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003403 FileReader fileReader = null;
3404 XmlPullParser parser = null;
3405 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003406
3407 try {
3408 fileReader = new FileReader(mProvisioningUrlFile);
3409 parser = Xml.newPullParser();
3410 parser.setInput(fileReader);
3411 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3412
3413 while (true) {
3414 XmlUtils.nextElement(parser);
3415
3416 String element = parser.getName();
3417 if (element == null) break;
3418
Paul Jensen434dde82015-06-11 09:43:30 -04003419 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003420 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3421 try {
3422 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3423 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3424 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3425 parser.next();
3426 if (parser.getEventType() == XmlPullParser.TEXT) {
3427 return parser.getText();
3428 }
3429 }
3430 }
3431 } catch (NumberFormatException e) {
3432 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3433 }
3434 }
3435 }
3436 return null;
3437 } catch (FileNotFoundException e) {
3438 loge("Carrier Provisioning Urls file not found");
3439 } catch (XmlPullParserException e) {
3440 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3441 } catch (IOException e) {
3442 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3443 } finally {
3444 if (fileReader != null) {
3445 try {
3446 fileReader.close();
3447 } catch (IOException e) {}
3448 }
3449 }
3450 return null;
3451 }
3452
Wink Saville42d4f082013-07-20 20:31:59 -07003453 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003454 public String getMobileProvisioningUrl() {
3455 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003456 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003457 if (TextUtils.isEmpty(url)) {
3458 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003459 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003460 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003461 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003462 }
Wink Saville8cf35602013-07-10 23:00:07 -07003463 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003464 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003465 String phoneNumber = mTelephonyManager.getLine1Number();
3466 if (TextUtils.isEmpty(phoneNumber)) {
3467 phoneNumber = "0000000000";
3468 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003469 url = String.format(url,
3470 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3471 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003472 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003473 }
3474
Wink Savilleab9321d2013-06-29 21:10:57 -07003475 return url;
3476 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003477
Wink Saville948282b2013-08-29 08:55:16 -07003478 @Override
3479 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003480 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003481 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003482 final long ident = Binder.clearCallingIdentity();
3483 try {
3484 setProvNotificationVisible(visible, networkType, action);
3485 } finally {
3486 Binder.restoreCallingIdentity(ident);
3487 }
Wink Saville948282b2013-08-29 08:55:16 -07003488 }
Wink Saville7788c612013-08-29 14:57:08 -07003489
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003490 @Override
3491 public void setAirplaneMode(boolean enable) {
3492 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003493 final long ident = Binder.clearCallingIdentity();
3494 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003495 final ContentResolver cr = mContext.getContentResolver();
3496 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3497 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3498 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003499 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003500 } finally {
3501 Binder.restoreCallingIdentity(ident);
3502 }
3503 }
3504
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003505 private void onUserStart(int userId) {
3506 synchronized(mVpns) {
3507 Vpn userVpn = mVpns.get(userId);
3508 if (userVpn != null) {
3509 loge("Starting user already has a VPN");
3510 return;
3511 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003512 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003513 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003514 }
3515 }
3516
3517 private void onUserStop(int userId) {
3518 synchronized(mVpns) {
3519 Vpn userVpn = mVpns.get(userId);
3520 if (userVpn == null) {
3521 loge("Stopping user has no VPN");
3522 return;
3523 }
3524 mVpns.delete(userId);
3525 }
3526 }
3527
3528 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3529 @Override
3530 public void onReceive(Context context, Intent intent) {
3531 final String action = intent.getAction();
3532 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3533 if (userId == UserHandle.USER_NULL) return;
3534
3535 if (Intent.ACTION_USER_STARTING.equals(action)) {
3536 onUserStart(userId);
3537 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3538 onUserStop(userId);
3539 }
3540 }
3541 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003542
Robert Greenwalta67be032014-05-16 15:49:14 -07003543 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3544 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003545 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3546 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003547
Robert Greenwalta67be032014-05-16 15:49:14 -07003548 private static class NetworkFactoryInfo {
3549 public final String name;
3550 public final Messenger messenger;
3551 public final AsyncChannel asyncChannel;
3552
3553 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3554 this.name = name;
3555 this.messenger = messenger;
3556 this.asyncChannel = asyncChannel;
3557 }
3558 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003559
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003560 /**
3561 * Tracks info about the requester.
3562 * Also used to notice when the calling process dies so we can self-expire
3563 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003564 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3565 static final boolean REQUEST = true;
3566 static final boolean LISTEN = false;
3567
3568 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003569 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003570 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003571 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003572 final int mPid;
3573 final int mUid;
3574 final Messenger messenger;
3575 final boolean isRequest;
3576
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003577 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3578 request = r;
3579 mPendingIntent = pi;
3580 messenger = null;
3581 mBinder = null;
3582 mPid = getCallingPid();
3583 mUid = getCallingUid();
3584 this.isRequest = isRequest;
3585 }
3586
Robert Greenwalt9258c642014-03-26 16:47:06 -07003587 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3588 super();
3589 messenger = m;
3590 request = r;
3591 mBinder = binder;
3592 mPid = getCallingPid();
3593 mUid = getCallingUid();
3594 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003595 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003596
3597 try {
3598 mBinder.linkToDeath(this, 0);
3599 } catch (RemoteException e) {
3600 binderDied();
3601 }
3602 }
3603
3604 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003605 if (mBinder != null) {
3606 mBinder.unlinkToDeath(this, 0);
3607 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003608 }
3609
3610 public void binderDied() {
3611 log("ConnectivityService NetworkRequestInfo binderDied(" +
3612 request + ", " + mBinder + ")");
3613 releaseNetworkRequest(request);
3614 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003615
3616 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003617 return (isRequest ? "Request" : "Listen") +
3618 " from uid/pid:" + mUid + "/" + mPid +
3619 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003620 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003621 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003622 }
3623
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003624 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3625 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3626 if (badCapability != null) {
3627 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003628 }
3629 }
3630
Erik Kline9d598e12015-07-13 16:37:51 +09003631 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003632 final SortedSet<Integer> thresholds = new TreeSet();
3633 synchronized (nai) {
3634 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3635 if (nri.request.networkCapabilities.hasSignalStrength() &&
3636 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3637 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3638 }
3639 }
3640 }
Erik Kline9d598e12015-07-13 16:37:51 +09003641 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003642 }
3643
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003644 private void updateSignalStrengthThresholds(
3645 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3646 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003647 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003648 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3649
3650 // TODO: Switch to VDBG.
3651 if (DBG) {
3652 String detail;
3653 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3654 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3655 } else {
3656 detail = reason;
3657 }
3658 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3659 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3660 }
3661
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003662 nai.asyncChannel.sendMessage(
3663 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003664 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003665 }
3666
Robert Greenwalt9258c642014-03-26 16:47:06 -07003667 @Override
3668 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003669 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003670 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003671 enforceNetworkRequestPermissions(networkCapabilities);
3672 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003673 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003674
Robert Greenwalt6078b502014-06-11 16:05:07 -07003675 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003676 throw new IllegalArgumentException("Bad timeout specified");
3677 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003678
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003679 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3680 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003681 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3682 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003683 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003684
3685 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003686 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003687 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003688 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003689 }
3690 return networkRequest;
3691 }
3692
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003693 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003694 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003695 enforceConnectivityInternalPermission();
3696 } else {
3697 enforceChangePermission();
3698 }
3699 }
3700
fenglub15e72b2015-03-20 11:29:56 -07003701 @Override
fengludb571472015-04-21 17:12:05 -07003702 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003703 enforceAccessPermission();
3704 NetworkAgentInfo nai = null;
3705 if (network == null) {
3706 return false;
3707 }
3708 synchronized (mNetworkForNetId) {
3709 nai = mNetworkForNetId.get(network.netId);
3710 }
3711 if (nai != null) {
3712 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3713 return true;
3714 }
3715 return false;
3716 }
3717
3718
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003719 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3720 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003721 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003722 final int uidRules;
3723 final int uid = Binder.getCallingUid();
3724 synchronized(mRulesLock) {
3725 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3726 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003727 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003728 // we could silently fail or we can filter the available nets to only give
3729 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003730 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003731 }
3732 }
3733 }
3734
Robert Greenwalt9258c642014-03-26 16:47:06 -07003735 @Override
3736 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3737 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003738 checkNotNull(operation, "PendingIntent cannot be null.");
3739 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3740 enforceNetworkRequestPermissions(networkCapabilities);
3741 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003742 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003743
3744 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3745 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003746 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3747 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003748 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003749 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3750 nri));
3751 return networkRequest;
3752 }
3753
Jeremy Joslin79294842014-12-03 17:15:28 -08003754 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3755 mHandler.sendMessageDelayed(
3756 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3757 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3758 }
3759
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003760 @Override
3761 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003762 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003763 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3764 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003765 }
3766
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003767 // In order to implement the compatibility measure for pre-M apps that call
3768 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3769 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3770 // This ensures it has permission to do so.
3771 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3772 if (nc == null) {
3773 return false;
3774 }
3775 int[] transportTypes = nc.getTransportTypes();
3776 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3777 return false;
3778 }
3779 try {
3780 mContext.enforceCallingOrSelfPermission(
3781 android.Manifest.permission.ACCESS_WIFI_STATE,
3782 "ConnectivityService");
3783 } catch (SecurityException e) {
3784 return false;
3785 }
3786 return true;
3787 }
3788
Robert Greenwalt9258c642014-03-26 16:47:06 -07003789 @Override
3790 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3791 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003792 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3793 enforceAccessPermission();
3794 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003795
Erik Kline7523eb32015-07-09 18:24:03 +09003796 NetworkRequest networkRequest = new NetworkRequest(
3797 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003798 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3799 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003800 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003801
3802 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3803 return networkRequest;
3804 }
3805
3806 @Override
3807 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3808 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003809 checkNotNull(operation, "PendingIntent cannot be null.");
3810 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3811 enforceAccessPermission();
3812 }
3813
Erik Kline7523eb32015-07-09 18:24:03 +09003814 NetworkRequest networkRequest = new NetworkRequest(
3815 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003816 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3817 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003818 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003819
3820 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003821 }
3822
3823 @Override
3824 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003825 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3826 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003827 }
3828
3829 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003830 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003831 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003832 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3833 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003834 }
3835
Robert Greenwalta67be032014-05-16 15:49:14 -07003836 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003837 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003838 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3839 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3840 }
3841
3842 @Override
3843 public void unregisterNetworkFactory(Messenger messenger) {
3844 enforceConnectivityInternalPermission();
3845 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3846 }
3847
3848 private void handleUnregisterNetworkFactory(Messenger messenger) {
3849 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3850 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003851 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003852 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003853 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003854 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003855 }
3856
Robert Greenwalt7b816022014-04-18 15:25:25 -07003857 /**
3858 * NetworkAgentInfo supporting a request by requestId.
3859 * These have already been vetted (their Capabilities satisfy the request)
3860 * and the are the highest scored network available.
3861 * the are keyed off the Requests requestId.
3862 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003863 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003864 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3865 new SparseArray<NetworkAgentInfo>();
3866
Paul Jensen31a94f42015-02-13 14:18:39 -05003867 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3868 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003869 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3870 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003871 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3872 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3873 // there may not be a strict 1:1 correlation between the two.
3874 @GuardedBy("mNetworkForNetId")
3875 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003876
Robert Greenwalt7b816022014-04-18 15:25:25 -07003877 // NetworkAgentInfo keyed off its connecting messenger
3878 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003879 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003880 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3881 new HashMap<Messenger, NetworkAgentInfo>();
3882
Paul Jensen2c311d62014-11-17 12:34:51 -05003883 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003884 private final NetworkRequest mDefaultRequest;
3885
Erik Klineda4bfa82015-04-30 12:58:40 +09003886 // Request used to optionally keep mobile data active even when higher
3887 // priority networks like Wi-Fi are active.
3888 private final NetworkRequest mDefaultMobileDataRequest;
3889
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003890 private NetworkAgentInfo getDefaultNetwork() {
3891 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3892 }
3893
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003894 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003895 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003896 }
3897
Paul Jensen31a94f42015-02-13 14:18:39 -05003898 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003899 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003900 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003901 enforceConnectivityInternalPermission();
3902
Paul Jensen2c311d62014-11-17 12:34:51 -05003903 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3904 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04003905 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003906 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3907 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04003908 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003909 synchronized (this) {
3910 nai.networkMonitor.systemReady = mSystemReady;
3911 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003912 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003913 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003914 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003915 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003916 }
3917
3918 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3919 if (VDBG) log("Got NetworkAgent Messenger");
3920 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003921 synchronized (mNetworkForNetId) {
3922 mNetworkForNetId.put(na.network.netId, na);
3923 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003924 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3925 NetworkInfo networkInfo = na.networkInfo;
3926 na.networkInfo = null;
3927 updateNetworkInfo(na, networkInfo);
3928 }
3929
3930 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3931 LinkProperties newLp = networkAgent.linkProperties;
3932 int netId = networkAgent.network.netId;
3933
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003934 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3935 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003936 if (networkAgent.clatd != null) {
3937 networkAgent.clatd.fixupLinkProperties(oldLp);
3938 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003939
Paul Jensen992f2522014-04-28 10:33:11 -04003940 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003941 updateMtu(newLp, oldLp);
3942 // TODO - figure out what to do for clat
3943// for (LinkProperties lp : newLp.getStackedLinks()) {
3944// updateMtu(lp, null);
3945// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003946 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003947
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003948 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3949 // In L, we used it only when the network had Internet access but provided no DNS servers.
3950 // For now, just disable it, and if disabling it doesn't break things, remove it.
3951 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3952 // NET_CAPABILITY_INTERNET);
3953 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003954 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003955 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3956
Paul Jensen3b759822014-05-13 11:44:01 -04003957 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003958 if (isDefaultNetwork(networkAgent)) {
3959 handleApplyDefaultProxy(newLp.getHttpProxy());
3960 } else {
3961 updateProxy(newLp, oldLp, networkAgent);
3962 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003963 // TODO - move this check to cover the whole function
3964 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003965 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003966 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3967 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003968
3969 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04003970 }
3971
Lorenzo Colitti95439462014-10-09 13:44:48 +09003972 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3973 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3974 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003975
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003976 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003977 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3978 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003979 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003980 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003981 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003982 }
Paul Jensen992f2522014-04-28 10:33:11 -04003983
3984 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3985 CompareResult<String> interfaceDiff = new CompareResult<String>();
3986 if (oldLp != null) {
3987 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3988 } else if (newLp != null) {
3989 interfaceDiff.added = newLp.getAllInterfaceNames();
3990 }
3991 for (String iface : interfaceDiff.added) {
3992 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003993 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003994 mNetd.addInterfaceToNetwork(iface, netId);
3995 } catch (Exception e) {
3996 loge("Exception adding interface: " + e);
3997 }
3998 }
3999 for (String iface : interfaceDiff.removed) {
4000 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004001 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004002 mNetd.removeInterfaceFromNetwork(iface, netId);
4003 } catch (Exception e) {
4004 loge("Exception removing interface: " + e);
4005 }
4006 }
4007 }
4008
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004009 /**
4010 * Have netd update routes from oldLp to newLp.
4011 * @return true if routes changed between oldLp and newLp
4012 */
4013 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004014 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4015 if (oldLp != null) {
4016 routeDiff = oldLp.compareAllRoutes(newLp);
4017 } else if (newLp != null) {
4018 routeDiff.added = newLp.getAllRoutes();
4019 }
4020
4021 // add routes before removing old in case it helps with continuous connectivity
4022
4023 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4024 for (RouteInfo route : routeDiff.added) {
4025 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004026 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004027 try {
4028 mNetd.addRoute(netId, route);
4029 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004030 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4031 loge("Exception in addRoute for non-gateway: " + e);
4032 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004033 }
4034 }
4035 for (RouteInfo route : routeDiff.added) {
4036 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004037 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004038 try {
4039 mNetd.addRoute(netId, route);
4040 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004041 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4042 loge("Exception in addRoute for gateway: " + e);
4043 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004044 }
4045 }
4046
4047 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004048 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004049 try {
4050 mNetd.removeRoute(netId, route);
4051 } catch (Exception e) {
4052 loge("Exception in removeRoute: " + e);
4053 }
4054 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004055 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004056 }
Erik Kline41368502015-06-17 13:19:54 +09004057
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004058 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4059 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004060 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09004061 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004062 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004063 dnses = new ArrayList();
4064 dnses.add(mDefaultDns);
4065 if (DBG) {
4066 loge("no dns provided for netId " + netId + ", so using defaults");
4067 }
4068 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004069 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004070 try {
4071 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4072 newLp.getDomains());
4073 } catch (Exception e) {
4074 loge("Exception in setDnsServersForNetwork: " + e);
4075 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04004076 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004077 if (defaultNai != null && defaultNai.network.netId == netId) {
4078 setDefaultDnsSystemProperties(dnses);
4079 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004080 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004081 } else if (flush) {
4082 try {
4083 mNetd.flushNetworkDnsCache(netId);
4084 } catch (Exception e) {
4085 loge("Exception in flushNetworkDnsCache: " + e);
4086 }
4087 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004088 }
4089 }
4090
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004091 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4092 int last = 0;
4093 for (InetAddress dns : dnses) {
4094 ++last;
4095 String key = "net.dns" + last;
4096 String value = dns.getHostAddress();
4097 SystemProperties.set(key, value);
4098 }
4099 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4100 String key = "net.dns" + i;
4101 SystemProperties.set(key, "");
4102 }
4103 mNumDnsEntries = last;
4104 }
4105
Paul Jensen3d194ea2015-06-16 14:27:36 -04004106 /**
4107 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4108 * augmented with any stateful capabilities implied from {@code networkAgent}
4109 * (e.g., validated status and captive portal status).
4110 *
Paul Jensene0988542015-06-25 15:30:08 -04004111 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004112 * @param networkCapabilities the new network capabilities.
4113 */
Paul Jensene0988542015-06-25 15:30:08 -04004114 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004115 // Don't modify caller's NetworkCapabilities.
4116 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004117 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004118 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4119 } else {
4120 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4121 }
Paul Jensene0988542015-06-25 15:30:08 -04004122 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004123 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4124 } else {
4125 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4126 }
Paul Jensene0988542015-06-25 15:30:08 -04004127 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4128 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004129 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4130 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4131 try {
4132 mNetd.setNetworkPermission(nai.network.netId,
4133 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4134 null : NetworkManagementService.PERMISSION_SYSTEM);
4135 } catch (RemoteException e) {
4136 loge("Exception in setNetworkPermission: " + e);
4137 }
4138 }
Paul Jensene0988542015-06-25 15:30:08 -04004139 synchronized (nai) {
4140 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004141 }
Paul Jensene0988542015-06-25 15:30:08 -04004142 rematchAllNetworksAndRequests(nai, oldScore);
4143 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004144 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004145 }
4146
Paul Jensenc8b9a742014-09-30 15:37:41 -04004147 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4148 for (int i = 0; i < nai.networkRequests.size(); i++) {
4149 NetworkRequest nr = nai.networkRequests.valueAt(i);
4150 // Don't send listening requests to factories. b/17393458
4151 if (!isRequest(nr)) continue;
4152 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4153 }
4154 }
4155
Robert Greenwalt7b816022014-04-18 15:25:25 -07004156 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4157 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004158 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004159 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4160 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004161 }
4162 }
4163
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004164 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4165 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004166 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004167 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004168 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4169 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004170 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004171 sendIntent(nri.mPendingIntent, intent);
4172 }
4173 // else not handled
4174 }
4175
4176 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4177 mPendingIntentWakeLock.acquire();
4178 try {
4179 if (DBG) log("Sending " + pendingIntent);
4180 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4181 } catch (PendingIntent.CanceledException e) {
4182 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4183 mPendingIntentWakeLock.release();
4184 releasePendingNetworkRequest(pendingIntent);
4185 }
4186 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4187 }
4188
4189 @Override
4190 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4191 String resultData, Bundle resultExtras) {
4192 if (DBG) log("Finished sending " + pendingIntent);
4193 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004194 // Release with a delay so the receiving client has an opportunity to put in its
4195 // own request.
4196 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004197 }
4198
Robert Greenwalt9258c642014-03-26 16:47:06 -07004199 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004200 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004201 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004202 Bundle bundle = new Bundle();
4203 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4204 new NetworkRequest(nri.request));
4205 Message msg = Message.obtain();
4206 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4207 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4208 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4209 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004210 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004211 case ConnectivityManager.CALLBACK_LOSING: {
4212 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4213 break;
4214 }
4215 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4216 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4217 new NetworkCapabilities(networkAgent.networkCapabilities));
4218 break;
4219 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004220 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004221 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4222 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004223 break;
4224 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004225 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004226 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004227 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004228 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004229 if (VDBG) {
4230 log("sending notification " + notifyTypeToName(notificationType) +
4231 " for " + nri.request);
4232 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004233 nri.messenger.send(msg);
4234 } catch (RemoteException e) {
4235 // may occur naturally in the race of binder death.
4236 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4237 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004238 }
4239
Paul Jensenc8b9a742014-09-30 15:37:41 -04004240 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4241 for (int i = 0; i < nai.networkRequests.size(); i++) {
4242 NetworkRequest nr = nai.networkRequests.valueAt(i);
4243 // Ignore listening requests.
4244 if (!isRequest(nr)) continue;
4245 loge("Dead network still had at least " + nr);
4246 break;
4247 }
4248 nai.asyncChannel.disconnect();
4249 }
4250
Robert Greenwalt7b816022014-04-18 15:25:25 -07004251 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4252 if (oldNetwork == null) {
4253 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4254 return;
4255 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004256 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4257 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004258 }
4259
Paul Jensen27b02b72014-07-14 12:03:33 -04004260 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004261 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004262 setupDataActivityTracking(newNetwork);
4263 try {
4264 mNetd.setDefaultNetId(newNetwork.network.netId);
4265 } catch (Exception e) {
4266 loge("Exception setting default network :" + e);
4267 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004268 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004269 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004270 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004271 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004272 }
4273
Paul Jensen2161a8e2014-09-11 11:00:39 -04004274 // Handles a network appearing or improving its score.
4275 //
4276 // - Evaluates all current NetworkRequests that can be
4277 // satisfied by newNetwork, and reassigns to newNetwork
4278 // any such requests for which newNetwork is the best.
4279 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004280 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004281 // needed. A network is needed if it is the best network for
4282 // one or more NetworkRequests, or if it is a VPN.
4283 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004284 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004285 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004286 //
4287 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4288 // networks that have no chance (i.e. even if validated)
4289 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004290 //
4291 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4292 // it does not remove NetworkRequests that other Networks could better satisfy.
4293 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4294 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4295 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004296 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004297 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004298 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4299 // performed to tear down unvalidated networks that have no chance (i.e. even if
4300 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004301 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004302 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004303 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004304 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004305 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004306 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004307 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004308 // Find and migrate to this Network any NetworkRequests for
4309 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004310 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004311 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004312 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004313 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004314 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4315 final boolean satisfies = newNetwork.satisfies(nri.request);
4316 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004317 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004318 log("Network " + newNetwork.name() + " was already satisfying" +
4319 " request " + nri.request.requestId + ". No change.");
4320 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004321 keep = true;
4322 continue;
4323 }
4324
4325 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004326 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004327 if (satisfies) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004328 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004329 // This is not a request, it's a callback listener.
4330 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004331 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004332 continue;
4333 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004334
Robert Greenwalt7b816022014-04-18 15:25:25 -07004335 // next check if it's better than any current network we're using for
4336 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004337 if (VDBG) {
4338 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004339 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4340 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004341 }
4342 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004343 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004344 if (DBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004345 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004346 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004347 currentNetwork.networkRequests.remove(nri.request.requestId);
4348 currentNetwork.networkLingered.add(nri.request);
4349 affectedNetworks.add(currentNetwork);
4350 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004351 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004352 }
Paul Jensen573a0352015-01-08 10:49:34 -05004353 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004354 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004355 if (!newNetwork.addRequest(nri.request)) {
4356 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4357 }
4358 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004359 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004360 // Tell NetworkFactories about the new score, so they can stop
4361 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004362 // TODO - this could get expensive if we have alot of requests for this
4363 // network. Think about if there is a way to reduce this. Push
4364 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004365 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004366 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004367 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004368 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004369 }
4370 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004371 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4372 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4373 // mark it as no longer satisfying "nri". Because networks are processed by
4374 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4375 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4376 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4377 // This means this code doesn't have to handle the case where "currentNetwork" no
4378 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4379 if (DBG) {
4380 log("Network " + newNetwork.name() + " stopped satisfying" +
4381 " request " + nri.request.requestId);
4382 }
4383 newNetwork.networkRequests.remove(nri.request.requestId);
4384 if (currentNetwork == newNetwork) {
4385 mNetworkForRequestId.remove(nri.request.requestId);
4386 sendUpdatedScoreToFactories(nri.request, 0);
4387 } else {
4388 if (nri.isRequest == true) {
4389 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4390 newNetwork.name() +
4391 " without updating mNetworkForRequestId or factories!");
4392 }
4393 }
4394 // TODO: technically, sending CALLBACK_LOST here is
4395 // incorrect if nri is a request (not a listen) and there
4396 // is a replacement network currently connected that can
4397 // satisfy it. However, the only capability that can both
4398 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4399 // so this code is only incorrect for a network that loses
4400 // the TRUSTED capability, which is a rare case.
4401 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004402 }
4403 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004404 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004405 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004406 if (nai.lingering) {
4407 // Already lingered. Nothing to do. This can only happen if "nai" is in
4408 // "affectedNetworks" twice. The reasoning being that to get added to
4409 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4410 // (i.e. not lingered) so it could have only been lingered by this loop.
4411 // unneeded(nai) will be false and we'll call unlinger() below which would
4412 // be bad, so handle it here.
4413 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004414 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004415 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004416 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004417 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004418 }
4419 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004420 if (isNewDefault) {
4421 // Notify system services that this network is up.
4422 makeDefault(newNetwork);
4423 synchronized (ConnectivityService.this) {
4424 // have a new default network, release the transition wakelock in
4425 // a second if it's held. The second pause is to allow apps
4426 // to reconnect over the new network
4427 if (mNetTransitionWakeLock.isHeld()) {
4428 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4429 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4430 mNetTransitionWakeLockSerialNumber, 0),
4431 1000);
4432 }
4433 }
4434 }
4435
4436 // do this after the default net is switched, but
4437 // before LegacyTypeTracker sends legacy broadcasts
4438 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4439
4440 if (isNewDefault) {
4441 // Maintain the illusion: since the legacy API only
4442 // understands one network at a time, we must pretend
4443 // that the current default network disconnected before
4444 // the new one connected.
4445 if (oldDefaultNetwork != null) {
4446 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4447 oldDefaultNetwork, true);
4448 }
4449 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4450 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4451 notifyLockdownVpn(newNetwork);
4452 }
4453
Robert Greenwalt7b816022014-04-18 15:25:25 -07004454 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004455 // Notify battery stats service about this network, both the normal
4456 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004457 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004458 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004459 final IBatteryStats bs = BatteryStatsService.getService();
4460 final int type = newNetwork.networkInfo.getType();
4461
4462 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4463 bs.noteNetworkInterfaceType(baseIface, type);
4464 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4465 final String stackedIface = stacked.getInterfaceName();
4466 bs.noteNetworkInterfaceType(stackedIface, type);
4467 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4468 }
4469 } catch (RemoteException ignored) {
4470 }
4471
Robert Greenwalt152ed372014-12-17 17:19:53 -08004472 // This has to happen after the notifyNetworkCallbacks as that tickles each
4473 // ConnectivityManager instance so that legacy requests correctly bind dns
4474 // requests to this network. The legacy users are listening for this bcast
4475 // and will generally do a dns request so they can ensureRouteToHost and if
4476 // they do that before the callbacks happen they'll use the default network.
4477 //
4478 // TODO: Is there still a race here? We send the broadcast
4479 // after sending the callback, but if the app can receive the
4480 // broadcast before the callback, it might still break.
4481 //
4482 // This *does* introduce a race where if the user uses the new api
4483 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4484 // they may get old info. Reverse this after the old startUsing api is removed.
4485 // This is on top of the multiple intent sequencing referenced in the todo above.
4486 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4487 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4488 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4489 // legacy type tracker filters out repeat adds
4490 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4491 }
4492 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004493
4494 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4495 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4496 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4497 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4498 if (newNetwork.isVPN()) {
4499 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4500 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004501 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004502 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4503 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004504 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004505 if (DBG) log("Reaping " + nai.name());
4506 teardownUnneededNetwork(nai);
4507 }
4508 }
4509 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004510 }
4511
Paul Jensen1c7ba022015-06-16 14:27:36 -04004512 /**
4513 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4514 * being disconnected.
4515 * @param changed If only one Network's score or capabilities have been modified since the last
4516 * time this function was called, pass this Network in this argument, otherwise pass
4517 * null.
4518 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4519 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4520 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4521 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4522 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004523 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004524 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004525 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4526 // to avoid the slowness. It is not simply enough to process just "changed", for
4527 // example in the case where "changed"'s score decreases and another network should begin
4528 // satifying a NetworkRequest that "changed" currently satisfies.
4529
4530 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4531 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4532 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004533 if (changed != null && oldScore < changed.getCurrentScore()) {
4534 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004535 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004536 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4537 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4538 // Rematch higher scoring networks first to prevent requests first matching a lower
4539 // scoring network and then a higher scoring network, which could produce multiple
4540 // callbacks and inadvertently unlinger networks.
4541 Arrays.sort(nais);
4542 for (NetworkAgentInfo nai : nais) {
4543 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004544 // Only reap the last time through the loop. Reaping before all rematching
4545 // is complete could incorrectly teardown a network that hasn't yet been
4546 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004547 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004548 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004549 }
4550 }
4551 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004552
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004553 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004554 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004555 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004556 // For now only update icons for default connection.
4557 // TODO: Update WiFi and cellular icons separately. b/17237507
4558 if (!isDefaultNetwork(nai)) return;
4559
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004560 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004561 // Don't repeat publish.
4562 if (newInetCondition == mDefaultInetConditionPublished) return;
4563
4564 mDefaultInetConditionPublished = newInetCondition;
4565 sendInetConditionBroadcast(nai.networkInfo);
4566 }
4567
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004568 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4569 if (mLockdownTracker != null) {
4570 if (nai != null && nai.isVPN()) {
4571 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4572 } else {
4573 mLockdownTracker.onNetworkInfoChanged();
4574 }
4575 }
4576 }
4577
Robert Greenwalt7b816022014-04-18 15:25:25 -07004578 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4579 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004580 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004581 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004582 synchronized (networkAgent) {
4583 oldInfo = networkAgent.networkInfo;
4584 networkAgent.networkInfo = newInfo;
4585 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004586 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004587
4588 if (oldInfo != null && oldInfo.getState() == state) {
4589 if (VDBG) log("ignoring duplicate network state non-change");
4590 return;
4591 }
4592 if (DBG) {
4593 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4594 (oldInfo == null ? "null" : oldInfo.getState()) +
4595 " to " + state);
4596 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004597
Paul Jenseneec75412014-08-04 12:21:19 -04004598 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004599 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004600 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004601 if (networkAgent.isVPN()) {
4602 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004603 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4604 (networkAgent.networkMisc == null ||
4605 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004606 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004607 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4608 networkAgent.networkCapabilities.hasCapability(
4609 NET_CAPABILITY_NOT_RESTRICTED) ?
4610 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004611 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004612 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004613 loge("Error creating network " + networkAgent.network.netId + ": "
4614 + e.getMessage());
4615 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004616 }
Paul Jenseneec75412014-08-04 12:21:19 -04004617 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004618 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004619 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004620
Paul Jensenca8f16a2014-05-09 12:47:55 -04004621 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004622 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004623
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004624 if (networkAgent.isVPN()) {
4625 // Temporarily disable the default proxy (not global).
4626 synchronized (mProxyLock) {
4627 if (!mDefaultProxyDisabled) {
4628 mDefaultProxyDisabled = true;
4629 if (mGlobalProxy == null && mDefaultProxy != null) {
4630 sendProxyBroadcast(null);
4631 }
4632 }
4633 }
4634 // TODO: support proxy per network.
4635 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004636
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004637 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4638 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4639 // capabilities, so it only needs to be done once on initial connect, not every time the
4640 // network's capabilities change. Note that we do this before rematching the network,
4641 // so we could decide to tear it down immediately afterwards. That's fine though - on
4642 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4643 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004644 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004645
Paul Jensen2161a8e2014-09-11 11:00:39 -04004646 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004647 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004648
4649 // This has to happen after matching the requests, because callbacks are just requests.
4650 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004651 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004652 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004653 if (networkAgent.isVPN()) {
4654 synchronized (mProxyLock) {
4655 if (mDefaultProxyDisabled) {
4656 mDefaultProxyDisabled = false;
4657 if (mGlobalProxy == null && mDefaultProxy != null) {
4658 sendProxyBroadcast(mDefaultProxy);
4659 }
4660 }
4661 }
4662 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004663 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4664 state == NetworkInfo.State.SUSPENDED) {
4665 // going into or coming out of SUSPEND: rescore and notify
4666 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004667 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004668 }
4669 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4670 ConnectivityManager.CALLBACK_SUSPENDED :
4671 ConnectivityManager.CALLBACK_RESUMED));
4672 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004673 }
4674 }
4675
Robert Greenwaltac96c522014-06-03 16:43:57 -07004676 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4677 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004678 if (score < 0) {
4679 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4680 "). Bumping score to min of 0");
4681 score = 0;
4682 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004683
Paul Jensen2161a8e2014-09-11 11:00:39 -04004684 final int oldScore = nai.getCurrentScore();
4685 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004686
Paul Jensen85cf78e2015-06-25 13:25:07 -04004687 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004688
Paul Jensenc8b9a742014-09-30 15:37:41 -04004689 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004690 }
4691
Robert Greenwalt9258c642014-03-26 16:47:06 -07004692 // notify only this one new request of the current state
4693 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4694 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4695 // TODO - read state from monitor to decide what to send.
4696// if (nai.networkMonitor.isLingering()) {
4697// notifyType = NetworkCallbacks.LOSING;
4698// } else if (nai.networkMonitor.isEvaluating()) {
4699// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4700// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004701 if (nri.mPendingIntent == null) {
4702 callCallbackForRequest(nri, nai, notifyType);
4703 } else {
4704 sendPendingIntentForRequest(nri, nai, notifyType);
4705 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004706 }
4707
Robert Greenwalt8d482522015-06-24 13:23:42 -07004708 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004709 // The NetworkInfo we actually send out has no bearing on the real
4710 // state of affairs. For example, if the default connection is mobile,
4711 // and a request for HIPRI has just gone away, we need to pretend that
4712 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4713 // the state to DISCONNECTED, even though the network is of type MOBILE
4714 // and is still connected.
4715 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4716 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004717 if (state != DetailedState.DISCONNECTED) {
4718 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004719 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004720 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004721 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004722 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4723 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4724 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4725 if (info.isFailover()) {
4726 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4727 nai.networkInfo.setFailover(false);
4728 }
4729 if (info.getReason() != null) {
4730 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4731 }
4732 if (info.getExtraInfo() != null) {
4733 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4734 }
4735 NetworkAgentInfo newDefaultAgent = null;
4736 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004737 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004738 if (newDefaultAgent != null) {
4739 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4740 newDefaultAgent.networkInfo);
4741 } else {
4742 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4743 }
4744 }
4745 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4746 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004747 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004748 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004749 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004750 }
4751 }
4752 }
4753
Robert Greenwalt7b816022014-04-18 15:25:25 -07004754 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004755 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004756 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004757 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4758 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4759 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004760 if (nri.mPendingIntent == null) {
4761 callCallbackForRequest(nri, networkAgent, notifyType);
4762 } else {
4763 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4764 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004765 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004766 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004767
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004768 private String notifyTypeToName(int notifyType) {
4769 switch (notifyType) {
4770 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4771 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4772 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4773 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4774 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4775 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4776 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4777 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4778 }
4779 return "UNKNOWN";
4780 }
4781
Jeff Sharkey69736342014-12-08 14:50:12 -08004782 /**
4783 * Notify other system services that set of active ifaces has changed.
4784 */
4785 private void notifyIfacesChanged() {
4786 try {
4787 mStatsService.forceUpdateIfaces();
4788 } catch (Exception ignored) {
4789 }
4790 }
4791
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004792 @Override
4793 public boolean addVpnAddress(String address, int prefixLength) {
4794 throwIfLockdownEnabled();
4795 int user = UserHandle.getUserId(Binder.getCallingUid());
4796 synchronized (mVpns) {
4797 return mVpns.get(user).addAddress(address, prefixLength);
4798 }
4799 }
4800
4801 @Override
4802 public boolean removeVpnAddress(String address, int prefixLength) {
4803 throwIfLockdownEnabled();
4804 int user = UserHandle.getUserId(Binder.getCallingUid());
4805 synchronized (mVpns) {
4806 return mVpns.get(user).removeAddress(address, prefixLength);
4807 }
4808 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004809
4810 @Override
4811 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4812 throwIfLockdownEnabled();
4813 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004814 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004815 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004816 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004817 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004818 if (success) {
4819 notifyIfacesChanged();
4820 }
4821 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004822 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004823
4824 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004825 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4826 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4827 enforceKeepalivePermission();
4828 mKeepaliveTracker.startNattKeepalive(
4829 getNetworkAgentInfoForNetwork(network),
4830 intervalSeconds, messenger, binder,
4831 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4832 }
4833
4834 @Override
4835 public void stopKeepalive(Network network, int slot) {
4836 mHandler.sendMessage(mHandler.obtainMessage(
4837 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
4838 }
4839
4840 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07004841 public void factoryReset() {
4842 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004843
4844 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4845 return;
4846 }
4847
Robin Lee3b3dd942015-05-12 18:14:58 +01004848 final int userId = UserHandle.getCallingUserId();
4849
Stuart Scottf1fb3972015-04-02 18:00:02 -07004850 // Turn airplane mode off
4851 setAirplaneMode(false);
4852
Stuart Scotte3e314d2015-04-20 14:07:45 -07004853 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4854 // Untether
4855 for (String tether : getTetheredIfaces()) {
4856 untether(tether);
4857 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004858 }
4859
Stuart Scotte3e314d2015-04-20 14:07:45 -07004860 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4861 // Turn VPN off
4862 VpnConfig vpnConfig = getVpnConfig(userId);
4863 if (vpnConfig != null) {
4864 if (vpnConfig.legacy) {
4865 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4866 } else {
4867 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4868 // in the future without user intervention.
4869 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004870
Stuart Scotte3e314d2015-04-20 14:07:45 -07004871 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4872 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004873 }
4874 }
4875 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004876
4877 @VisibleForTesting
4878 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
4879 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
4880 return new NetworkMonitor(context, handler, nai, defaultRequest);
4881 }
4882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883}