blob: 8ca5ac1aae7adc38681080259f973053644bd2a0 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070036import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
43import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070046import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090047import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090050import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070058import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070059import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070064import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040070import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040073import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070075import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040076import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070078import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070079import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070080import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Looper;
82import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070083import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070084import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070085import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070086import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070088import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070090import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040091import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070093import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070094import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070095import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070097import android.util.LocalLog;
98import android.util.LocalLog.ReadOnlyLocalLog;
99import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800100import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700101import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500102import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700103import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700104import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Wink Savilleab9321d2013-06-29 21:10:57 -0700106import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400107import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400108import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700109import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700110import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700111import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700112import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800113import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700114import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700115import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700116import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700117import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700118import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700119import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400120import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900121import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900122import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900123import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700124import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400125import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400126import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700127import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800128import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700129import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700130import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700131import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700132import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700133import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700134
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700135import org.xmlpull.v1.XmlPullParser;
136import org.xmlpull.v1.XmlPullParserException;
137
138import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700140import java.io.FileNotFoundException;
141import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700142import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700144import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700145import java.net.InetAddress;
146import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700147import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700148import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700149import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700150import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700151import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700152import java.util.HashSet;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900153import java.util.SortedSet;
154import java.util.TreeSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500155import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700156import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700157import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700158import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700159import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
161/**
162 * @hide
163 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800164public class ConnectivityService extends IConnectivityManager.Stub
165 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700166 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700168 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700169 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
Jake Hamby786e71a2014-02-06 14:43:50 -0800171 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700172
Jeff Sharkey899223b2012-08-04 15:24:58 -0700173 // TODO: create better separation between radio types and network types
174
Robert Greenwalt42acef32009-08-12 16:08:25 -0700175 // how long to wait before switching back to a radio's default network
176 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
177 // system property that can override the above value
178 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
179 "android.telephony.apn-restore";
180
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900181 // How long to wait before putting up a "This network doesn't have an Internet connection,
182 // connect anyway?" dialog after the user selects a network that doesn't validate.
183 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
184
Jeremy Joslin79294842014-12-03 17:15:28 -0800185 // How long to delay to removal of a pending intent based request.
186 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
187 private final int mReleasePendingIntentDelayMs;
188
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800189 private Tethering mTethering;
190
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700191 private final PermissionMonitor mPermissionMonitor;
192
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700193 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700194
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700195 @GuardedBy("mVpns")
196 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700197
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700198 private boolean mLockdownEnabled;
199 private LockdownVpnTracker mLockdownTracker;
200
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700201 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
202 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700203 /** Currently active network rules by UID. */
204 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700205 /** Set of ifaces that are costly. */
206 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700207
Erik Klineda4bfa82015-04-30 12:58:40 +0900208 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700210 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700211 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800213 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
215 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700216 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700218 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800219 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700220 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700221
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700222 private String mCurrentTcpBufferSizes;
223
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700224 private static final int ENABLED = 1;
225 private static final int DISABLED = 0;
226
Paul Jensenb10e37f2014-11-25 12:33:08 -0500227 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400228 // Tear down networks that have no chance (e.g. even if validated) of becoming
229 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500230 // all networks have been rematched against all NetworkRequests.
231 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400232 // Don't reap networks. This should be passed when some networks have not yet been
233 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500234 DONT_REAP
235 };
236
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700238 * used internally to change our mobile data enabled flag
239 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700240 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241
242 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700243 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700244 * from one net to another. Clear happens when we get a new
245 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
246 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700247 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700248 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700249
Robert Greenwalt434203a2010-10-11 16:00:27 -0700250 /**
251 * used internally to reload global proxy settings
252 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700253 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700254
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700255 /**
Wink Saville628b0852011-08-04 15:01:58 -0700256 * used internally to send a sticky broadcast delayed.
257 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700258 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700259
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700260 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400261 * PAC manager has received new port.
262 */
263 private static final int EVENT_PROXY_HAS_CHANGED = 16;
264
Robert Greenwalte049c232014-04-11 15:53:27 -0700265 /**
266 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700267 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700268 */
269 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
270
Robert Greenwalt7b816022014-04-18 15:25:25 -0700271 /**
272 * used internally when registering NetworkAgents
273 * obj = Messenger
274 */
275 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
276
Robert Greenwalt9258c642014-03-26 16:47:06 -0700277 /**
278 * used to add a network request
279 * includes a NetworkRequestInfo
280 */
281 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
282
283 /**
284 * indicates a timeout period is over - check if we had a network yet or not
285 * and if not, call the timeout calback (but leave the request live until they
286 * cancel it.
287 * includes a NetworkRequestInfo
288 */
289 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
290
291 /**
292 * used to add a network listener - no request
293 * includes a NetworkRequestInfo
294 */
295 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
296
297 /**
298 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400299 * arg1 = UID of caller
300 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700301 */
302 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
303
Robert Greenwalta67be032014-05-16 15:49:14 -0700304 /**
305 * used internally when registering NetworkFactories
306 * obj = Messenger
307 */
308 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
309
Robert Greenwalt27711812014-06-25 16:45:57 -0700310 /**
311 * used internally to expire a wakelock when transitioning
312 * from one net to another. Expire happens when we fail to find
313 * a new network (typically after 1 minute) -
314 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
315 * a replacement network.
316 */
317 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
318
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700319 /**
320 * Used internally to indicate the system is ready.
321 */
322 private static final int EVENT_SYSTEM_READY = 25;
323
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800324 /**
325 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400326 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800327 */
328 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
329
330 /**
331 * used to remove a pending intent and its associated network request.
332 * arg1 = UID of caller
333 * obj = PendingIntent
334 */
335 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
336
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900337 /**
338 * used to specify whether a network should be used even if unvalidated.
339 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
340 * arg2 = whether to remember this choice in the future (1 or 0)
341 * obj = network
342 */
343 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
344
345 /**
346 * used to ask the user to confirm a connection to an unvalidated network.
347 * obj = network
348 */
349 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700350
Erik Klineda4bfa82015-04-30 12:58:40 +0900351 /**
352 * used internally to (re)configure mobile data always-on settings.
353 */
354 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
355
Paul Jensen694f2b82015-06-17 14:15:39 -0400356 /**
357 * used to add a network listener with a pending intent
358 * obj = NetworkRequestInfo
359 */
360 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
361
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700362 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700363 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700364 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700365 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700366
Mike Lockwood0f79b542009-08-14 14:18:49 -0400367 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800368 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400369
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700370 private PowerManager.WakeLock mNetTransitionWakeLock;
371 private String mNetTransitionWakeLockCausedBy = "";
372 private int mNetTransitionWakeLockSerialNumber;
373 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800374 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700375
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700376 private InetAddress mDefaultDns;
377
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700378 // used in DBG mode to track inet condition reports
379 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
380 private ArrayList mInetLog;
381
Robert Greenwalt434203a2010-10-11 16:00:27 -0700382 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400383 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700384 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700385 private boolean mDefaultProxyDisabled = false;
386
Robert Greenwalt434203a2010-10-11 16:00:27 -0700387 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400388 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700389
Jason Monk602b2322013-07-03 17:04:33 -0400390 private PacManager mPacManager = null;
391
Erik Klineda4bfa82015-04-30 12:58:40 +0900392 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700393
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400394 private UserManager mUserManager;
395
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700396 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700397 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700398
Robert Greenwalt50393202011-06-21 17:26:14 -0700399 // the set of network types that can only be enabled by system/sig apps
400 List mProtectedNetworks;
401
John Spurlockbf991a82013-06-24 14:20:23 -0400402 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700403
Wink Savilleab9321d2013-06-29 21:10:57 -0700404 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400405
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900406 private KeepaliveTracker mKeepaliveTracker;
407
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700408 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
409 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700410 private final static int MAX_NET_ID = 65535;
411 private int mNextNetId = MIN_NET_ID;
412
Robert Greenwalt34524f02014-05-18 16:22:10 -0700413 // sequence number of NetworkRequests
414 private int mNextNetworkRequestId = 1;
415
Erik Kline7523eb32015-07-09 18:24:03 +0900416 // NetworkRequest activity String log entries.
417 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
418 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
419
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700420 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
421 private static final int MAX_VALIDATION_LOGS = 10;
422 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
423 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
424
425 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
426 synchronized(mValidationLogs) {
427 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
428 mValidationLogs.removeLast();
429 }
430 mValidationLogs.addFirst(new Pair(network, log));
431 }
432 }
433
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700434 /**
435 * Implements support for the legacy "one network per network type" model.
436 *
437 * We used to have a static array of NetworkStateTrackers, one for each
438 * network type, but that doesn't work any more now that we can have,
439 * for example, more that one wifi network. This class stores all the
440 * NetworkAgentInfo objects that support a given type, but the legacy
441 * API will only see the first one.
442 *
443 * It serves two main purposes:
444 *
445 * 1. Provide information about "the network for a given type" (since this
446 * API only supports one).
447 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
448 * the first network for a given type changes, or if the default network
449 * changes.
450 */
451 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900452
453 private static final boolean DBG = true;
454 private static final boolean VDBG = false;
455 private static final String TAG = "CSLegacyTypeTracker";
456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 /**
458 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
459 * Each list holds references to all NetworkAgentInfos that are used to
460 * satisfy requests for that network type.
461 *
462 * This array is built out at startup such that an unsupported network
463 * doesn't get an ArrayList instance, making this a tristate:
464 * unsupported, supported but not active and active.
465 *
466 * The actual lists are populated when we scan the network types that
467 * are supported on this device.
468 */
469 private ArrayList<NetworkAgentInfo> mTypeLists[];
470
471 public LegacyTypeTracker() {
472 mTypeLists = (ArrayList<NetworkAgentInfo>[])
473 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
474 }
475
476 public void addSupportedType(int type) {
477 if (mTypeLists[type] != null) {
478 throw new IllegalStateException(
479 "legacy list for type " + type + "already initialized");
480 }
481 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
482 }
483
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700484 public boolean isTypeSupported(int type) {
485 return isNetworkTypeValid(type) && mTypeLists[type] != null;
486 }
487
488 public NetworkAgentInfo getNetworkForType(int type) {
489 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
490 return mTypeLists[type].get(0);
491 } else {
492 return null;
493 }
494 }
495
Robert Greenwalt8d482522015-06-24 13:23:42 -0700496 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900497 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700499 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900500 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900501 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900502 }
503 }
504
505 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700506 public void add(int type, NetworkAgentInfo nai) {
507 if (!isTypeSupported(type)) {
508 return; // Invalid network type.
509 }
510 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
511
512 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
513 if (list.contains(nai)) {
514 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
515 return;
516 }
517
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900518 list.add(nai);
519
520 // 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 +0900521 final boolean isDefaultNetwork = isDefaultNetwork(nai);
522 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700523 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
524 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700525 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700526 }
527
Lorenzo Colittia793a672014-07-31 23:20:17 +0900528 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900529 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900530 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
531 if (list == null || list.isEmpty()) {
532 return;
533 }
534
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900535 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900536
537 if (!list.remove(nai)) {
538 return;
539 }
540
Robert Greenwalt8d482522015-06-24 13:23:42 -0700541 final DetailedState state = DetailedState.DISCONNECTED;
542
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900543 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700544 maybeLogBroadcast(nai, state, type, wasDefault);
545 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900546 }
547
548 if (!list.isEmpty() && wasFirstNetwork) {
549 if (DBG) log("Other network available for type " + type +
550 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900551 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700552 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
553 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900554 }
555 }
556
557 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900558 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
559 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900561 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700562 }
563 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700564
Robert Greenwalt8d482522015-06-24 13:23:42 -0700565 // send out another legacy broadcast - currently only used for suspend/unsuspend
566 // toggle
567 public void update(NetworkAgentInfo nai) {
568 final boolean isDefault = isDefaultNetwork(nai);
569 final DetailedState state = nai.networkInfo.getDetailedState();
570 for (int type = 0; type < mTypeLists.length; type++) {
571 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700572 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700573 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700574 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700575 maybeLogBroadcast(nai, state, type, isDefault);
576 sendLegacyNetworkBroadcast(nai, state, type);
577 }
578 }
579 }
580
Lorenzo Colittia793a672014-07-31 23:20:17 +0900581 private String naiToString(NetworkAgentInfo nai) {
582 String name = (nai != null) ? nai.name() : "null";
583 String state = (nai.networkInfo != null) ?
584 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
585 "???/???";
586 return name + " " + state;
587 }
588
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700589 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900590 pw.println("mLegacyTypeTracker:");
591 pw.increaseIndent();
592 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700593 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900594 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700595 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900596 pw.println();
597 pw.println("Current state:");
598 pw.increaseIndent();
599 for (int type = 0; type < mTypeLists.length; type++) {
600 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
601 for (NetworkAgentInfo nai : mTypeLists[type]) {
602 pw.println(type + " " + naiToString(nai));
603 }
604 }
605 pw.decreaseIndent();
606 pw.decreaseIndent();
607 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700608 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900609
610 // This class needs its own log method because it has a different TAG.
611 private void log(String s) {
612 Slog.d(TAG, s);
613 }
614
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700615 }
616 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
617
Jeff Sharkey899223b2012-08-04 15:24:58 -0700618 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700619 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800620 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800621
Erik Klineda4bfa82015-04-30 12:58:40 +0900622 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900623 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
624 new Binder(), NetworkRequestInfo.REQUEST);
625 mNetworkRequests.put(mDefaultRequest, defaultNRI);
626 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900627
628 mDefaultMobileDataRequest = createInternetRequestForTransport(
629 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700630
Wink Savillebb08caf2010-09-02 19:23:52 -0700631 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
632 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700633 mHandler = new InternalHandler(handlerThread.getLooper());
634 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700635
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800636 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800637 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
638 String id = Settings.Secure.getString(context.getContentResolver(),
639 Settings.Secure.ANDROID_ID);
640 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700641 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800642 SystemProperties.set("net.hostname", name);
643 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800644 }
645
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700646 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700647 String dns = Settings.Global.getString(context.getContentResolver(),
648 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700649 if (dns == null || dns.length() == 0) {
650 dns = context.getResources().getString(
651 com.android.internal.R.string.config_default_dns_server);
652 }
653 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800654 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
655 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800656 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700657 }
658
Jeremy Joslin79294842014-12-03 17:15:28 -0800659 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
660 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
661
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700662 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700663 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800664 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700665 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700666 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700667 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700668
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700669 try {
670 mPolicyManager.registerListener(mPolicyListener);
671 } catch (RemoteException e) {
672 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700673 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700674 }
675
676 final PowerManager powerManager = (PowerManager) context.getSystemService(
677 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700678 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
679 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
680 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800681 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700682
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700683 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700684
Wink Saville51f456f2013-04-23 14:26:51 -0700685 // TODO: What is the "correct" way to do determine if this is a wifi only device?
686 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
687 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700688 String[] naStrings = context.getResources().getStringArray(
689 com.android.internal.R.array.networkAttributes);
690 for (String naString : naStrings) {
691 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700692 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700693 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700694 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800695 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700696 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700697 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700698 }
Wink Saville51f456f2013-04-23 14:26:51 -0700699 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
700 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
701 n.type);
702 continue;
703 }
Wink Saville975c8482011-04-07 14:23:45 -0700704 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800705 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700706 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700707 continue;
708 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700709 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700710
Wink Saville975c8482011-04-07 14:23:45 -0700711 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700712 mNetworksDefined++;
713 } catch(Exception e) {
714 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700715 }
716 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700717
718 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
719 if (mNetConfigs[TYPE_VPN] == null) {
720 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
721 // don't need to add TYPE_VPN to mNetConfigs.
722 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
723 mNetworksDefined++; // used only in the log() statement below.
724 }
725
Wink Saville5e56bc52013-07-29 15:00:57 -0700726 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700727
Robert Greenwalt50393202011-06-21 17:26:14 -0700728 mProtectedNetworks = new ArrayList<Integer>();
729 int[] protectedNetworks = context.getResources().getIntArray(
730 com.android.internal.R.array.config_protectedNetworks);
731 for (int p : protectedNetworks) {
732 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
733 mProtectedNetworks.add(p);
734 } else {
735 if (DBG) loge("Ignoring protectedNetwork " + p);
736 }
737 }
738
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700739 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
740 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700741
Robert Greenwaltfab501672014-07-23 11:44:01 -0700742 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800743
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700744 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
745
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700746 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700747 IntentFilter intentFilter = new IntentFilter();
748 intentFilter.addAction(Intent.ACTION_USER_STARTING);
749 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
750 mContext.registerReceiverAsUser(
751 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900752
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700753 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700754 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700755 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700756 } catch (RemoteException e) {
757 loge("Error registering observer :" + e);
758 }
759
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700760 if (DBG) {
761 mInetLog = new ArrayList();
762 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700763
Erik Klineda4bfa82015-04-30 12:58:40 +0900764 mSettingsObserver = new SettingsObserver(mContext, mHandler);
765 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800766
John Spurlockbf991a82013-06-24 14:20:23 -0400767 mDataConnectionStats = new DataConnectionStats(mContext);
768 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400769
Jason Monkdecd2952013-10-10 14:02:51 -0400770 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700771
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400772 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900773
774 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700776
Erik Klineda4bfa82015-04-30 12:58:40 +0900777 private NetworkRequest createInternetRequestForTransport(int transportType) {
778 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900779 netCap.addCapability(NET_CAPABILITY_INTERNET);
780 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900781 if (transportType > -1) {
782 netCap.addTransportType(transportType);
783 }
784 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
785 }
786
787 private void handleMobileDataAlwaysOn() {
788 final boolean enable = (Settings.Global.getInt(
789 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
790 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
791 if (enable == isEnabled) {
792 return; // Nothing to do.
793 }
794
795 if (enable) {
796 handleRegisterNetworkRequest(new NetworkRequestInfo(
797 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
798 } else {
799 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
800 }
801 }
802
803 private void registerSettingsCallbacks() {
804 // Watch for global HTTP proxy changes.
805 mSettingsObserver.observe(
806 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
807 EVENT_APPLY_GLOBAL_HTTP_PROXY);
808
809 // Watch for whether or not to keep mobile data always on.
810 mSettingsObserver.observe(
811 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
812 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
813 }
814
Robert Greenwalt34524f02014-05-18 16:22:10 -0700815 private synchronized int nextNetworkRequestId() {
816 return mNextNetworkRequestId++;
817 }
818
Paul Jensen67b0b072015-06-10 11:22:17 -0400819 @VisibleForTesting
820 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400821 synchronized (mNetworkForNetId) {
822 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
823 int netId = mNextNetId;
824 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
825 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500826 if (!mNetIdInUse.get(netId)) {
827 mNetIdInUse.put(netId, true);
828 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400829 }
830 }
831 }
832 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700833 }
834
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800835 private NetworkState getFilteredNetworkState(int networkType, int uid) {
836 NetworkInfo info = null;
837 LinkProperties lp = null;
838 NetworkCapabilities nc = null;
839 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800840 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800841
842 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
843 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
844 if (nai != null) {
845 synchronized (nai) {
846 info = new NetworkInfo(nai.networkInfo);
847 lp = new LinkProperties(nai.linkProperties);
848 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400849 // Network objects are outwardly immutable so there is no point to duplicating.
850 // Duplicating also precludes sharing socket factories and connection pools.
851 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800852 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800853 }
854 info.setType(networkType);
855 } else {
856 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
857 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
858 info.setIsAvailable(true);
859 lp = new LinkProperties();
860 nc = new NetworkCapabilities();
861 network = null;
862 }
863 info = getFilteredNetworkInfo(info, lp, uid);
864 }
865
Jeff Sharkey32566012014-12-02 18:30:14 -0800866 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400867 }
868
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800869 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
870 if (network == null) {
871 return null;
872 }
873 synchronized (mNetworkForNetId) {
874 return mNetworkForNetId.get(network.netId);
875 }
876 };
877
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900878 private Network[] getVpnUnderlyingNetworks(int uid) {
879 if (!mLockdownEnabled) {
880 int user = UserHandle.getUserId(uid);
881 synchronized (mVpns) {
882 Vpn vpn = mVpns.get(user);
883 if (vpn != null && vpn.appliesToUid(uid)) {
884 return vpn.getUnderlyingNetworks();
885 }
886 }
887 }
888 return null;
889 }
890
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800891 private NetworkState getUnfilteredActiveNetworkState(int uid) {
892 NetworkInfo info = null;
893 LinkProperties lp = null;
894 NetworkCapabilities nc = null;
895 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800896 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800897
Paul Jensen85cf78e2015-06-25 13:25:07 -0400898 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800899
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900900 final Network[] networks = getVpnUnderlyingNetworks(uid);
901 if (networks != null) {
902 // getUnderlyingNetworks() returns:
903 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
904 // empty array => the VPN explicitly said "no default network".
905 // non-empty array => the VPN specified one or more default networks; we use the
906 // first one.
907 if (networks.length > 0) {
908 nai = getNetworkAgentInfoForNetwork(networks[0]);
909 } else {
910 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800911 }
912 }
913
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800914 if (nai != null) {
915 synchronized (nai) {
916 info = new NetworkInfo(nai.networkInfo);
917 lp = new LinkProperties(nai.linkProperties);
918 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400919 // Network objects are outwardly immutable so there is no point to duplicating.
920 // Duplicating also precludes sharing socket factories and connection pools.
921 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800922 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800923 }
924 }
925
Jeff Sharkey32566012014-12-02 18:30:14 -0800926 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400927 }
928
929 /**
930 * Check if UID should be blocked from using the network with the given LinkProperties.
931 */
932 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700933 final boolean networkCostly;
934 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700935
Robert Greenwalt12e67352014-05-13 21:41:06 -0700936 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700937 synchronized (mRulesLock) {
938 networkCostly = mMeteredIfaces.contains(iface);
939 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700940 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700941
Amith Yamasani15e472352015-04-24 19:06:07 -0700942 if ((uidRules & RULE_REJECT_ALL) != 0
943 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700944 return true;
945 }
946
947 // no restrictive rules; network is visible
948 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700949 }
950
951 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700952 * Return a filtered {@link NetworkInfo}, potentially marked
953 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800954 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700955 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800956 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
957 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400958 // network is blocked; clone and override state
959 info = new NetworkInfo(info);
960 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900961 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900962 log("returning Blocked NetworkInfo for ifname=" +
963 lp.getInterfaceName() + ", uid=" + uid);
964 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700965 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800966 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700967 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900968 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700969 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700970 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700971 }
972
973 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 * Return NetworkInfo for the active (i.e., connected) network interface.
975 * It is assumed that at most one network is active at a time. If more
976 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700977 * @return the info for the active network, or {@code null} if none is
978 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700980 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700982 enforceAccessPermission();
983 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800984 NetworkState state = getUnfilteredActiveNetworkState(uid);
985 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
987
Paul Jensen31a94f42015-02-13 14:18:39 -0500988 @Override
989 public Network getActiveNetwork() {
990 enforceAccessPermission();
991 final int uid = Binder.getCallingUid();
992 final int user = UserHandle.getUserId(uid);
993 int vpnNetId = NETID_UNSET;
994 synchronized (mVpns) {
995 final Vpn vpn = mVpns.get(user);
996 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
997 }
998 NetworkAgentInfo nai;
999 if (vpnNetId != NETID_UNSET) {
1000 synchronized (mNetworkForNetId) {
1001 nai = mNetworkForNetId.get(vpnNetId);
1002 }
1003 if (nai != null) return nai.network;
1004 }
1005 nai = getDefaultNetwork();
1006 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1007 return nai != null ? nai.network : null;
1008 }
1009
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001010 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1011 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001012 final int uid = Binder.getCallingUid();
1013 NetworkState state = getUnfilteredActiveNetworkState(uid);
1014 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001015 }
1016
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001017 @Override
1018 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1019 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001020 NetworkState state = getUnfilteredActiveNetworkState(uid);
1021 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001022 }
1023
1024 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 public NetworkInfo getNetworkInfo(int networkType) {
1026 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001027 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001028 if (getVpnUnderlyingNetworks(uid) != null) {
1029 // A VPN is active, so we may need to return one of its underlying networks. This
1030 // information is not available in LegacyTypeTracker, so we have to get it from
1031 // getUnfilteredActiveNetworkState.
1032 NetworkState state = getUnfilteredActiveNetworkState(uid);
1033 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1034 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1035 }
1036 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001037 NetworkState state = getFilteredNetworkState(networkType, uid);
1038 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
1040
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001041 @Override
1042 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1043 enforceAccessPermission();
1044 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001045 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001046 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1047 if (nai != null) {
1048 synchronized (nai) {
1049 info = new NetworkInfo(nai.networkInfo);
1050 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001051 }
1052 }
1053 return info;
1054 }
1055
1056 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 public NetworkInfo[] getAllNetworkInfo() {
1058 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001059 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001060 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1061 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001062 NetworkInfo info = getNetworkInfo(networkType);
1063 if (info != null) {
1064 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001067 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001070 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001071 public Network getNetworkForType(int networkType) {
1072 enforceAccessPermission();
1073 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001074 NetworkState state = getFilteredNetworkState(networkType, uid);
1075 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1076 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001077 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001078 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001079 }
1080
1081 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001082 public Network[] getAllNetworks() {
1083 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001084 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001085 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001086 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001087 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001088 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001089 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001090 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001091 }
1092
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001093 @Override
1094 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1095 // The basic principle is: if an app's traffic could possibly go over a
1096 // network, without the app doing anything multinetwork-specific,
1097 // (hence, by "default"), then include that network's capabilities in
1098 // the array.
1099 //
1100 // In the normal case, app traffic only goes over the system's default
1101 // network connection, so that's the only network returned.
1102 //
1103 // With a VPN in force, some app traffic may go into the VPN, and thus
1104 // over whatever underlying networks the VPN specifies, while other app
1105 // traffic may go over the system default network (e.g.: a split-tunnel
1106 // VPN, or an app disallowed by the VPN), so the set of networks
1107 // returned includes the VPN's underlying networks and the system
1108 // default.
1109 enforceAccessPermission();
1110
1111 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1112
1113 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001114 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001115 if (nc != null) {
1116 result.put(nai.network, nc);
1117 }
1118
1119 if (!mLockdownEnabled) {
1120 synchronized (mVpns) {
1121 Vpn vpn = mVpns.get(userId);
1122 if (vpn != null) {
1123 Network[] networks = vpn.getUnderlyingNetworks();
1124 if (networks != null) {
1125 for (Network network : networks) {
1126 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001127 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001128 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001129 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001130 }
1131 }
1132 }
1133 }
1134 }
1135 }
1136
1137 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1138 out = result.values().toArray(out);
1139 return out;
1140 }
1141
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001142 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001143 public boolean isNetworkSupported(int networkType) {
1144 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001145 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001146 }
1147
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001148 /**
1149 * Return LinkProperties for the active (i.e., connected) default
1150 * network interface. It is assumed that at most one default network
1151 * is active at a time. If more than one is active, it is indeterminate
1152 * which will be returned.
1153 * @return the ip properties for the active network, or {@code null} if
1154 * none is active
1155 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001156 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001157 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001158 enforceAccessPermission();
1159 final int uid = Binder.getCallingUid();
1160 NetworkState state = getUnfilteredActiveNetworkState(uid);
1161 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001162 }
1163
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001164 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001165 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001166 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001167 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1168 if (nai != null) {
1169 synchronized (nai) {
1170 return new LinkProperties(nai.linkProperties);
1171 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001172 }
1173 return null;
1174 }
1175
Robert Greenwalt12e67352014-05-13 21:41:06 -07001176 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001177 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001178 public LinkProperties getLinkProperties(Network network) {
1179 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001180 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001181 if (nai != null) {
1182 synchronized (nai) {
1183 return new LinkProperties(nai.linkProperties);
1184 }
1185 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001186 return null;
1187 }
1188
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001189 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001190 if (nai != null) {
1191 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001192 if (nai.networkCapabilities != null) {
1193 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001194 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001195 }
1196 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001197 return null;
1198 }
1199
1200 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001201 public NetworkCapabilities getNetworkCapabilities(Network network) {
1202 enforceAccessPermission();
1203 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1204 }
1205
1206 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001207 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001208 // Require internal since we're handing out IMSI details
1209 enforceConnectivityInternalPermission();
1210
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001211 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001212 for (Network network : getAllNetworks()) {
1213 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1214 if (nai != null) {
1215 synchronized (nai) {
1216 final String subscriberId = (nai.networkMisc != null)
1217 ? nai.networkMisc.subscriberId : null;
1218 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1219 nai.networkCapabilities, network, subscriberId, null));
1220 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001221 }
1222 }
1223 return result.toArray(new NetworkState[result.size()]);
1224 }
1225
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001226 @Override
1227 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1228 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001229 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001230 final long token = Binder.clearCallingIdentity();
1231 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001232 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1233 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001234 try {
1235 return mPolicyManager.getNetworkQuotaInfo(state);
1236 } catch (RemoteException e) {
1237 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001238 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001239 return null;
1240 } finally {
1241 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001242 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001243 }
1244
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001245 @Override
1246 public boolean isActiveNetworkMetered() {
1247 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001248 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001249 final long token = Binder.clearCallingIdentity();
1250 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001251 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001252 } finally {
1253 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001254 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001255 }
1256
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001257 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1258 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1259 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001260 try {
1261 return mPolicyManager.isNetworkMetered(state);
1262 } catch (RemoteException e) {
1263 }
1264 }
1265 return false;
1266 }
1267
Jeff Sharkey216c1812012-08-05 14:29:23 -07001268 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1269 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001270 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001271 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001272 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001273 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001274 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001275
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001276 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 * Ensure that a network route exists to deliver traffic to the specified
1278 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001279 * @param networkType the type of the network over which traffic to the
1280 * specified host is to be routed
1281 * @param hostAddress the IP address of the host to which the route is
1282 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 * @return {@code true} on success, {@code false} on failure
1284 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001285 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001287 if (mProtectedNetworks.contains(networkType)) {
1288 enforceConnectivityInternalPermission();
1289 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001290
Chad Brubakerc0234532014-02-14 13:24:29 -08001291 InetAddress addr;
1292 try {
1293 addr = InetAddress.getByAddress(hostAddress);
1294 } catch (UnknownHostException e) {
1295 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1296 return false;
1297 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001300 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 return false;
1302 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001303
1304 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1305 if (nai == null) {
1306 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1307 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1308 } else {
1309 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1310 }
1311 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001312 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001313
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001314 DetailedState netState;
1315 synchronized (nai) {
1316 netState = nai.networkInfo.getDetailedState();
1317 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001318
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001319 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001320 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001321 log("requestRouteToHostAddress on down network "
1322 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001323 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001324 }
1325 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001327
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001328 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001329 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001330 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001331 LinkProperties lp;
1332 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001333 synchronized (nai) {
1334 lp = nai.linkProperties;
1335 netId = nai.network.netId;
1336 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001337 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001338 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1339 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001340 } finally {
1341 Binder.restoreCallingIdentity(token);
1342 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001343 }
1344
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001345 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001346 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001347 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001348 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001349 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001350 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001351 if (bestRoute.getGateway().equals(addr)) {
1352 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001353 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001354 } else {
1355 // if we will connect to this through another route, add a direct route
1356 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001357 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001358 }
1359 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001360 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001361 try {
1362 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1363 } catch (Exception e) {
1364 // never crash - catch them all
1365 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001366 return false;
1367 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001368 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 }
1370
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001371 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1372 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001373 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001374 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001375 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001376 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001377 }
1378
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001379 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001380 // skip update when we've already applied rules
1381 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1382 if (oldRules == uidRules) return;
1383
1384 mUidRules.put(uid, uidRules);
1385 }
1386
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001387 // TODO: notify UID when it has requested targeted updates
1388 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001389
1390 @Override
1391 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001392 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001393 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001394 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001395 }
1396
1397 synchronized (mRulesLock) {
1398 mMeteredIfaces.clear();
1399 for (String iface : meteredIfaces) {
1400 mMeteredIfaces.add(iface);
1401 }
1402 }
1403 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001404
1405 @Override
1406 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1407 // caller is NPMS, since we only register with them
1408 if (LOGD_RULES) {
1409 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1410 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001411 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001412 };
1413
Robin Lee3b3dd942015-05-12 18:14:58 +01001414 /**
1415 * Require that the caller is either in the same user or has appropriate permission to interact
1416 * across users.
1417 *
1418 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1419 */
1420 private void enforceCrossUserPermission(int userId) {
1421 if (userId == UserHandle.getCallingUserId()) {
1422 // Not a cross-user call.
1423 return;
1424 }
1425 mContext.enforceCallingOrSelfPermission(
1426 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1427 "ConnectivityService");
1428 }
1429
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001430 private void enforceInternetPermission() {
1431 mContext.enforceCallingOrSelfPermission(
1432 android.Manifest.permission.INTERNET,
1433 "ConnectivityService");
1434 }
1435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001437 mContext.enforceCallingOrSelfPermission(
1438 android.Manifest.permission.ACCESS_NETWORK_STATE,
1439 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441
1442 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001443 mContext.enforceCallingOrSelfPermission(
1444 android.Manifest.permission.CHANGE_NETWORK_STATE,
1445 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 }
1447
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001448 private void enforceTetherAccessPermission() {
1449 mContext.enforceCallingOrSelfPermission(
1450 android.Manifest.permission.ACCESS_NETWORK_STATE,
1451 "ConnectivityService");
1452 }
1453
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001454 private void enforceConnectivityInternalPermission() {
1455 mContext.enforceCallingOrSelfPermission(
1456 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1457 "ConnectivityService");
1458 }
1459
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001460 private void enforceKeepalivePermission() {
1461 mContext.enforceCallingPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
1462 }
1463
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001464 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001465 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001466 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001467 }
1468
1469 private void sendInetConditionBroadcast(NetworkInfo info) {
1470 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1471 }
1472
Wink Saville628b0852011-08-04 15:01:58 -07001473 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001474 if (mLockdownTracker != null) {
1475 info = mLockdownTracker.augmentNetworkInfo(info);
1476 }
1477
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001478 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001479 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001480 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 if (info.isFailover()) {
1482 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1483 info.setFailover(false);
1484 }
1485 if (info.getReason() != null) {
1486 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1487 }
1488 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001489 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1490 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001492 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001493 return intent;
1494 }
1495
1496 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1497 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1498 }
1499
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001500 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001501 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1502 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1503 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001504 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001505 final long ident = Binder.clearCallingIdentity();
1506 try {
1507 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1508 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1509 } finally {
1510 Binder.restoreCallingIdentity(ident);
1511 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001512 }
1513
Mike Lockwood0f79b542009-08-14 14:18:49 -04001514 private void sendStickyBroadcast(Intent intent) {
1515 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001516 if (!mSystemReady) {
1517 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001518 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001519 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001520 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001521 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001522 }
1523
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001524 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001525 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1526 final IBatteryStats bs = BatteryStatsService.getService();
1527 try {
1528 NetworkInfo ni = intent.getParcelableExtra(
1529 ConnectivityManager.EXTRA_NETWORK_INFO);
1530 bs.noteConnectivityChanged(intent.getIntExtra(
1531 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1532 ni != null ? ni.getState().toString() : "?");
1533 } catch (RemoteException e) {
1534 }
1535 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001536 try {
1537 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1538 } finally {
1539 Binder.restoreCallingIdentity(ident);
1540 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001541 }
1542 }
1543
1544 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001545 loadGlobalProxy();
1546
Mike Lockwood0f79b542009-08-14 14:18:49 -04001547 synchronized(this) {
1548 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001549 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001550 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001551 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001552 }
1553 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001554 // load the global proxy at startup
1555 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001556
1557 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1558 // for user to unlock device.
1559 if (!updateLockdownVpn()) {
1560 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1561 mContext.registerReceiver(mUserPresentReceiver, filter);
1562 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001563
Erik Klineda4bfa82015-04-30 12:58:40 +09001564 // Configure whether mobile data is always on.
1565 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1566
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001567 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001568
1569 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 }
1571
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001572 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1573 @Override
1574 public void onReceive(Context context, Intent intent) {
1575 // Try creating lockdown tracker, since user present usually means
1576 // unlocked keystore.
1577 if (updateLockdownVpn()) {
1578 mContext.unregisterReceiver(this);
1579 }
1580 }
1581 };
1582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001584 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001585 *
1586 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001587 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001588 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001589 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1590 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001591
1592 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001593 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001594
Robert Greenwalt7b816022014-04-18 15:25:25 -07001595 if (networkAgent.networkCapabilities.hasTransport(
1596 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001597 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1598 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001599 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001600 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001601 } else if (networkAgent.networkCapabilities.hasTransport(
1602 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001603 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1604 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001605 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001606 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001607 } else {
1608 // do not track any other networks
1609 timeout = 0;
1610 }
1611
Robert Greenwalt7b816022014-04-18 15:25:25 -07001612 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001613 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001614 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001615 } catch (Exception e) {
1616 // You shall not crash!
1617 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001618 }
1619 }
1620 }
1621
1622 /**
1623 * Remove data activity tracking when network disconnects.
1624 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001625 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1626 final String iface = networkAgent.linkProperties.getInterfaceName();
1627 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001628
Robert Greenwalt7b816022014-04-18 15:25:25 -07001629 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1630 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001631 try {
1632 // the call fails silently if no idletimer setup for this interface
1633 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001634 } catch (Exception e) {
1635 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001636 }
1637 }
1638 }
1639
1640 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001641 * Reads the network specific MTU size from reources.
1642 * and set it on it's iface.
1643 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001644 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1645 final String iface = newLp.getInterfaceName();
1646 final int mtu = newLp.getMtu();
1647 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1648 if (VDBG) log("identical MTU - not setting");
1649 return;
1650 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001651
Robert Greenwalt43074032014-08-15 17:53:05 -07001652 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001653 loge("Unexpected mtu value: " + mtu + ", " + iface);
1654 return;
1655 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001656
w1997615afd812014-08-05 15:18:11 -07001657 // Cannot set MTU without interface name
1658 if (TextUtils.isEmpty(iface)) {
1659 loge("Setting MTU size with null iface.");
1660 return;
1661 }
1662
Robert Greenwalt7b816022014-04-18 15:25:25 -07001663 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001664 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001665 mNetd.setMtu(iface, mtu);
1666 } catch (Exception e) {
1667 Slog.e(TAG, "exception in setMtu()" + e);
1668 }
1669 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001670
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001671 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001672 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1673
1674 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001675 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001676 protected int getDefaultTcpRwnd() {
1677 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1678 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001679
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001680 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1681 if (isDefaultNetwork(nai) == false) {
1682 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001683 }
1684
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001685 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1686 String[] values = null;
1687 if (tcpBufferSizes != null) {
1688 values = tcpBufferSizes.split(",");
1689 }
1690
1691 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001692 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001693 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1694 values = tcpBufferSizes.split(",");
1695 }
1696
1697 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1698
1699 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001700 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001701
1702 final String prefix = "/sys/kernel/ipv4/tcp_";
1703 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1704 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1705 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1706 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1707 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1708 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1709 mCurrentTcpBufferSizes = tcpBufferSizes;
1710 } catch (IOException e) {
1711 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001712 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001713
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001714 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001715 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001716 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1717 if (rwndValue != 0) {
1718 SystemProperties.set(sysctlKey, rwndValue.toString());
1719 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001720 }
1721
Mattias Falk8b47b362011-08-23 14:15:13 +02001722 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001723 /*
1724 * Tell the VMs to toss their DNS caches
1725 */
1726 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1727 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001728 /*
1729 * Connectivity events can happen before boot has completed ...
1730 */
1731 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001732 final long ident = Binder.clearCallingIdentity();
1733 try {
1734 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1735 } finally {
1736 Binder.restoreCallingIdentity(ident);
1737 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001738 }
1739
Robert Greenwalt562cc542014-05-15 18:07:26 -07001740 @Override
1741 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001742 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1743 NETWORK_RESTORE_DELAY_PROP_NAME);
1744 if(restoreDefaultNetworkDelayStr != null &&
1745 restoreDefaultNetworkDelayStr.length() != 0) {
1746 try {
1747 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1748 } catch (NumberFormatException e) {
1749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001751 // if the system property isn't set, use the value for the apn type
1752 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1753
1754 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1755 (mNetConfigs[networkType] != null)) {
1756 ret = mNetConfigs[networkType].restoreTime;
1757 }
1758 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 }
1760
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001761 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001762 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001763 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001764 }
1765 return false;
1766 }
1767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001769 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1770 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001771 if (mContext.checkCallingOrSelfPermission(
1772 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001774 pw.println("Permission Denial: can't dump ConnectivityService " +
1775 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1776 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 return;
1778 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001779
Erik Kline379747a2015-06-05 17:47:34 +09001780 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001781 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001782 final long DIAG_TIME_MS = 5000;
1783 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1784 // Start gathering diagnostic information.
1785 netDiags.add(new NetworkDiagnostics(
1786 nai.network,
Lorenzo Colitti87cfc702015-07-27 16:35:33 +09001787 new LinkProperties(nai.linkProperties), // Must be a copy.
Erik Kline379747a2015-06-05 17:47:34 +09001788 DIAG_TIME_MS));
1789 }
1790
1791 for (NetworkDiagnostics netDiag : netDiags) {
1792 pw.println();
1793 netDiag.waitForMeasurements();
1794 netDiag.dump(pw);
1795 }
1796
1797 return;
1798 }
1799
Lorenzo Colittie3805462015-06-03 11:18:24 +09001800 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001801 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001802 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001803 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001804 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001805 pw.println();
1806
Paul Jensen85cf78e2015-06-25 13:25:07 -04001807 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001808 pw.print("Active default network: ");
1809 if (defaultNai == null) {
1810 pw.println("none");
1811 } else {
1812 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001814 pw.println();
1815
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001816 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001817 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001818 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1819 pw.println(nai.toString());
1820 pw.increaseIndent();
1821 pw.println("Requests:");
1822 pw.increaseIndent();
1823 for (int i = 0; i < nai.networkRequests.size(); i++) {
1824 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001825 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001826 pw.decreaseIndent();
1827 pw.println("Lingered:");
1828 pw.increaseIndent();
1829 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1830 pw.decreaseIndent();
1831 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001832 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001833 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001834 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001835
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001836 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001837 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001838 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1839 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001840 }
1841 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001842 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001843
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001844 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001845
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001846 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001847 pw.print("mNetTransitionWakeLock: currently " +
1848 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1849 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1850 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1851 } else {
1852 pw.println(", last requested never");
1853 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001854 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001855
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001856 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001857 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001858
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001859 pw.println();
1860 mKeepaliveTracker.dump(pw);
1861
Lorenzo Colittie3805462015-06-03 11:18:24 +09001862 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001863 pw.println();
1864 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001865 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001866 for(int i = 0; i < mInetLog.size(); i++) {
1867 pw.println(mInetLog.get(i));
1868 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001869 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001870 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001871
1872 if (argsContain(args, "--short") == false) {
1873 pw.println();
1874 synchronized (mValidationLogs) {
1875 pw.println("mValidationLogs (most recent first):");
1876 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1877 pw.println(p.first);
1878 pw.increaseIndent();
1879 p.second.dump(fd, pw, args);
1880 pw.decreaseIndent();
1881 }
1882 }
Erik Kline7523eb32015-07-09 18:24:03 +09001883
1884 pw.println();
1885 pw.println("mNetworkRequestInfoLogs (most recent first):");
1886 pw.increaseIndent();
1887 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1888 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
1891
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001892 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001893 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001894 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001895 if (officialNai != null && officialNai.equals(nai)) return true;
1896 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001897 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001898 " - " + nai);
1899 }
1900 return false;
1901 }
1902
Paul Jensenc8b9a742014-09-30 15:37:41 -04001903 private boolean isRequest(NetworkRequest request) {
1904 return mNetworkRequests.get(request).isRequest;
1905 }
1906
Robert Greenwalt42acef32009-08-12 16:08:25 -07001907 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001908 private class NetworkStateTrackerHandler extends Handler {
1909 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001910 super(looper);
1911 }
1912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 @Override
1914 public void handleMessage(Message msg) {
1915 NetworkInfo info;
1916 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001917 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001918 handleAsyncChannelHalfConnect(msg);
1919 break;
1920 }
1921 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1922 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1923 if (nai != null) nai.asyncChannel.disconnect();
1924 break;
1925 }
1926 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1927 handleAsyncChannelDisconnected(msg);
1928 break;
1929 }
1930 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1931 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1932 if (nai == null) {
1933 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1934 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001935 final NetworkCapabilities networkCapabilities =
1936 (NetworkCapabilities)msg.obj;
1937 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1938 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001939 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Paul Jensen1c7ba022015-06-16 14:27:36 -04001940 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001941 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1942 networkCapabilities)) {
1943 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1944 + nai.networkCapabilities + " -> " + networkCapabilities);
1945 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001946 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001947 }
1948 break;
1949 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001950 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1951 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1952 if (nai == null) {
1953 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1954 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001955 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001956 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001957 "; created=" + nai.created);
1958 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001959 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001960 synchronized (nai) {
1961 nai.linkProperties = (LinkProperties)msg.obj;
1962 }
Paul Jenseneec75412014-08-04 12:21:19 -04001963 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001964 }
1965 break;
1966 }
1967 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1968 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1969 if (nai == null) {
1970 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1971 break;
1972 }
1973 info = (NetworkInfo) msg.obj;
1974 updateNetworkInfo(nai, info);
1975 break;
1976 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001977 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1978 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1979 if (nai == null) {
1980 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1981 break;
1982 }
1983 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001984 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001985 break;
1986 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001987 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1988 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1989 if (nai == null) {
1990 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1991 break;
1992 }
1993 try {
1994 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001995 } catch (Exception e) {
1996 // Never crash!
1997 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001998 }
1999 break;
2000 }
2001 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2002 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2003 if (nai == null) {
2004 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
2005 break;
2006 }
2007 try {
2008 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002009 } catch (Exception e) {
2010 // Never crash!
2011 loge("Exception in removeVpnUidRanges: " + e);
2012 }
2013 break;
2014 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002015 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2016 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2017 if (nai == null) {
2018 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
2019 break;
2020 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002021 if (nai.created && !nai.networkMisc.explicitlySelected) {
2022 loge("ERROR: created network explicitly selected.");
2023 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002024 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002025 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002026 break;
2027 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002028 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2029 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2030 if (nai == null) {
2031 loge("EVENT_PACKET_KEEPALIVE from unknown NetworkAgent");
2032 break;
2033 }
2034 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2035 break;
2036 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002037 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002038 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002039 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2040 final boolean valid =
2041 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002042 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2043 if (valid != nai.lastValidated) {
2044 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002045 nai.lastValidated = valid;
2046 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002047 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002048 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2049 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002050 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002051 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002052 // Let the NetworkAgent know the state of its network
2053 nai.asyncChannel.sendMessage(
2054 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2055 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2056 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002057 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002058 break;
2059 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002060 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002061 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002062 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2063 handleLingerComplete(nai);
2064 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002065 break;
2066 }
Paul Jensen869868be2014-05-15 10:33:05 -04002067 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002068 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002069 final boolean visible = (msg.arg1 != 0);
2070 final NetworkAgentInfo nai;
2071 synchronized (mNetworkForNetId) {
2072 nai = mNetworkForNetId.get(netId);
2073 }
2074 // If captive portal status has changed, update capabilities.
2075 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2076 nai.lastCaptivePortalDetected = visible;
2077 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002078 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002079 }
2080 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002081 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002082 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002083 if (nai == null) {
2084 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2085 break;
2086 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002087 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002088 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2089 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002090 }
Paul Jensen869868be2014-05-15 10:33:05 -04002091 break;
2092 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002093 }
2094 }
2095 }
2096
Paul Jensen85cf78e2015-06-25 13:25:07 -04002097 private void linger(NetworkAgentInfo nai) {
2098 nai.lingering = true;
2099 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2100 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2101 }
2102
Paul Jensen0cc17322014-11-25 15:26:53 -05002103 // Cancel any lingering so the linger timeout doesn't teardown a network.
2104 // This should be called when a network begins satisfying a NetworkRequest.
2105 // Note: depending on what state the NetworkMonitor is in (e.g.,
2106 // if it's awaiting captive portal login, or if validation failed), this
2107 // may trigger a re-evaluation of the network.
2108 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002109 nai.networkLingered.clear();
2110 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002111 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002112 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002113 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2114 }
2115
Robert Greenwalt7b816022014-04-18 15:25:25 -07002116 private void handleAsyncChannelHalfConnect(Message msg) {
2117 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002118 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002119 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2120 if (VDBG) log("NetworkFactory connected");
2121 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002122 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002123 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002124 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002125 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002126 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002127 }
2128 } else {
2129 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002130 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002131 }
2132 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2133 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2134 if (VDBG) log("NetworkAgent connected");
2135 // A network agent has requested a connection. Establish the connection.
2136 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2137 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2138 } else {
2139 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002140 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002141 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002142 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002143 synchronized (mNetworkForNetId) {
2144 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002145 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002146 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002147 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002148 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002149 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 }
2151 }
2152 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002153
Robert Greenwalt7b816022014-04-18 15:25:25 -07002154 private void handleAsyncChannelDisconnected(Message msg) {
2155 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2156 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002157 if (DBG) {
2158 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2159 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002160 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002161 // TODO - if we move the logic to the network agent (have them disconnect
2162 // because they lost all their requests or because their score isn't good)
2163 // then they would disconnect organically, report their new state and then
2164 // disconnect the channel.
2165 if (nai.networkInfo.isConnected()) {
2166 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2167 null, null);
2168 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002169 final boolean wasDefault = isDefaultNetwork(nai);
2170 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002171 mDefaultInetConditionPublished = 0;
2172 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002173 notifyIfacesChanged();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002174 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2175 // by other networks that are already connected. Perhaps that can be done by
2176 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2177 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002178 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002179 mKeepaliveTracker.handleStopAllKeepalives(nai,
2180 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002181 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002182 mNetworkAgentInfos.remove(msg.replyTo);
2183 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002184 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002185 // Remove the NetworkAgent, but don't mark the netId as
2186 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002187 mNetworkForNetId.remove(nai.network.netId);
2188 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002189 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002190 for (int i = 0; i < nai.networkRequests.size(); i++) {
2191 NetworkRequest request = nai.networkRequests.valueAt(i);
2192 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2193 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2194 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002195 sendUpdatedScoreToFactories(request, 0);
2196 }
2197 }
2198 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2199 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002200 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002201 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002202 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002203 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002204 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002205 if (nai.created) {
2206 // Tell netd to clean up the configuration for this network
2207 // (routing rules, DNS, etc).
2208 // This may be slow as it requires a lot of netd shelling out to ip and
2209 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2210 // after we've rematched networks with requests which should make a potential
2211 // fallback network the default or requested a new network from the
2212 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2213 // long time.
2214 try {
2215 mNetd.removeNetwork(nai.network.netId);
2216 } catch (Exception e) {
2217 loge("Exception removing network: " + e);
2218 }
2219 }
2220 synchronized (mNetworkForNetId) {
2221 mNetIdInUse.delete(nai.network.netId);
2222 }
2223 } else {
2224 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2225 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002226 }
2227 }
2228
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002229 // If this method proves to be too slow then we can maintain a separate
2230 // pendingIntent => NetworkRequestInfo map.
2231 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2232 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2233 Intent intent = pendingIntent.getIntent();
2234 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2235 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2236 if (existingPendingIntent != null &&
2237 existingPendingIntent.getIntent().filterEquals(intent)) {
2238 return entry.getValue();
2239 }
2240 }
2241 return null;
2242 }
2243
2244 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2245 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2246
2247 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2248 if (existingRequest != null) { // remove the existing request.
2249 if (DBG) log("Replacing " + existingRequest.request + " with "
2250 + nri.request + " because their intents matched.");
2251 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2252 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002253 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002254 }
2255
Erik Klineda4bfa82015-04-30 12:58:40 +09002256 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002257 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002258 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002259 if (!nri.isRequest) {
2260 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
2261 if (network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2262 updateSignalStrengthThresholds(network);
2263 }
2264 }
2265 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002266 rematchAllNetworksAndRequests(null, 0);
2267 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2268 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002269 }
2270 }
2271
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002272 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2273 int callingUid) {
2274 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2275 if (nri != null) {
2276 handleReleaseNetworkRequest(nri.request, callingUid);
2277 }
2278 }
2279
Paul Jensen99364842014-12-09 11:43:45 -05002280 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002281 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2282 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002283 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002284 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002285 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2286 // If this Network is already the highest scoring Network for a request, or if
2287 // there is hope for it to become one if it validated, then it is needed.
2288 if (nri.isRequest && nai.satisfies(nri.request) &&
2289 (nai.networkRequests.get(nri.request.requestId) != null ||
2290 // Note that this catches two important cases:
2291 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2292 // is currently satisfying the request. This is desirable when
2293 // cellular ends up validating but WiFi does not.
2294 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002295 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002296 // WiFi ends up validating and out scoring cellular.
2297 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2298 nai.getCurrentScoreAsValidated())) {
2299 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002300 }
2301 }
Paul Jensene0988542015-06-25 15:30:08 -04002302 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002303 }
2304
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002305 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2306 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002307 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002308 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002309 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2310 return;
2311 }
2312 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002313 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002314 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002315 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002316 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002317 // Find all networks that are satisfying this request and remove the request
2318 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002319 // TODO - it's my understanding that for a request there is only a single
2320 // network satisfying it, so this loop is wasteful
2321 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002322 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2323 if (nai.networkRequests.get(nri.request.requestId) != null) {
2324 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002325 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002326 log(" Removing from current network " + nai.name() +
2327 ", leaving " + nai.networkRequests.size() +
2328 " requests.");
2329 }
Paul Jensen99364842014-12-09 11:43:45 -05002330 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002331 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002332 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002333 } else {
2334 // suspect there should only be one pass through here
2335 // but if any were kept do the check below
2336 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002337 }
2338 }
2339 }
2340
Robert Greenwalt51481852015-01-08 14:43:31 -08002341 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2342 if (nai != null) {
2343 mNetworkForRequestId.remove(nri.request.requestId);
2344 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002345 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002346 // that a network connected to serve it, even though the network was already
2347 // connected. Now that this request has gone away, we might have to pretend
2348 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002349 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002350 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2351 boolean doRemove = true;
2352 if (wasKept) {
2353 // check if any of the remaining requests for this network are for the
2354 // same legacy type - if so, don't remove the nai
2355 for (int i = 0; i < nai.networkRequests.size(); i++) {
2356 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2357 if (otherRequest.legacyType == nri.request.legacyType &&
2358 isRequest(otherRequest)) {
2359 if (DBG) log(" still have other legacy request - leaving");
2360 doRemove = false;
2361 }
2362 }
2363 }
2364
2365 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002366 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002367 }
2368 }
2369
Robert Greenwalta67be032014-05-16 15:49:14 -07002370 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002371 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2372 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002373 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002374 } else {
2375 // listens don't have a singular affectedNetwork. Check all networks to see
2376 // if this listen request applies and remove it.
2377 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2378 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002379 if (nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2380 updateSignalStrengthThresholds(nai);
2381 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002382 }
2383 }
2384 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2385 }
2386 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002387
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002388 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2389 enforceConnectivityInternalPermission();
2390 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2391 accept ? 1 : 0, always ? 1: 0, network));
2392 }
2393
2394 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2395 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2396 " accept=" + accept + " always=" + always);
2397
2398 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2399 if (nai == null) {
2400 // Nothing to do.
2401 return;
2402 }
2403
2404 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002405 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002406 return;
2407 }
2408
2409 if (!nai.networkMisc.explicitlySelected) {
2410 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2411 }
2412
2413 if (accept != nai.networkMisc.acceptUnvalidated) {
2414 int oldScore = nai.getCurrentScore();
2415 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002416 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002417 sendUpdatedScoreToFactories(nai);
2418 }
2419
2420 if (always) {
2421 nai.asyncChannel.sendMessage(
2422 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2423 }
2424
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002425 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002426 // Tell the NetworkAgent to not automatically reconnect to the network.
2427 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2428 // Teardown the nework.
2429 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002430 }
2431
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002432 }
2433
2434 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002435 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002436 mHandler.sendMessageDelayed(
2437 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2438 PROMPT_UNVALIDATED_DELAY_MS);
2439 }
2440
2441 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002442 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002443 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2444
2445 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2446 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002447 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002448 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002449 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2450 return;
2451 }
2452
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002453 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002454 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002455 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2456 intent.setClassName("com.android.settings",
2457 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002458
2459 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2460 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2461 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002462 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002463 }
2464
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002465 private class InternalHandler extends Handler {
2466 public InternalHandler(Looper looper) {
2467 super(looper);
2468 }
2469
2470 @Override
2471 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002472 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002473 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002474 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002475 String causedBy = null;
2476 synchronized (ConnectivityService.this) {
2477 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2478 mNetTransitionWakeLock.isHeld()) {
2479 mNetTransitionWakeLock.release();
2480 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002481 } else {
2482 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002483 }
2484 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002485 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2486 log("Failed to find a new network - expiring NetTransition Wakelock");
2487 } else {
2488 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2489 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002490 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002491 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002492 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002493 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002494 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002495 break;
2496 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002497 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002498 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002499 sendStickyBroadcast(intent);
2500 break;
2501 }
Jason Monkdecd2952013-10-10 14:02:51 -04002502 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002503 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002504 break;
2505 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002506 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002507 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2508 break;
2509 }
2510 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2511 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002512 break;
2513 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002514 case EVENT_REGISTER_NETWORK_AGENT: {
2515 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2516 break;
2517 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002518 case EVENT_REGISTER_NETWORK_REQUEST:
2519 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002520 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002521 break;
2522 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002523 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2524 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002525 handleRegisterNetworkRequestWithIntent(msg);
2526 break;
2527 }
2528 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2529 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2530 break;
2531 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002532 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002533 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002534 break;
2535 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002536 case EVENT_SET_ACCEPT_UNVALIDATED: {
2537 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2538 break;
2539 }
2540 case EVENT_PROMPT_UNVALIDATED: {
2541 handlePromptUnvalidated((Network) msg.obj);
2542 break;
2543 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002544 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2545 handleMobileDataAlwaysOn();
2546 break;
2547 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002548 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2549 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2550 mKeepaliveTracker.handleStartKeepalive(msg);
2551 break;
2552 }
2553 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2554 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2555 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2556 int slot = msg.arg1;
2557 int reason = msg.arg2;
2558 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2559 break;
2560 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002561 case EVENT_SYSTEM_READY: {
2562 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2563 nai.networkMonitor.systemReady = true;
2564 }
2565 break;
2566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 }
2568 }
2569 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002570
2571 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002572 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002573 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002574 if (isTetheringSupported()) {
2575 return mTethering.tether(iface);
2576 } else {
2577 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2578 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002579 }
2580
2581 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002582 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002583 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002584
2585 if (isTetheringSupported()) {
2586 return mTethering.untether(iface);
2587 } else {
2588 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2589 }
2590 }
2591
2592 // javadoc from interface
2593 public int getLastTetherError(String iface) {
2594 enforceTetherAccessPermission();
2595
2596 if (isTetheringSupported()) {
2597 return mTethering.getLastTetherError(iface);
2598 } else {
2599 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2600 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002601 }
2602
2603 // TODO - proper iface API for selection by property, inspection, etc
2604 public String[] getTetherableUsbRegexs() {
2605 enforceTetherAccessPermission();
2606 if (isTetheringSupported()) {
2607 return mTethering.getTetherableUsbRegexs();
2608 } else {
2609 return new String[0];
2610 }
2611 }
2612
2613 public String[] getTetherableWifiRegexs() {
2614 enforceTetherAccessPermission();
2615 if (isTetheringSupported()) {
2616 return mTethering.getTetherableWifiRegexs();
2617 } else {
2618 return new String[0];
2619 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002620 }
2621
Danica Chang6fdd0c62010-08-11 14:54:43 -07002622 public String[] getTetherableBluetoothRegexs() {
2623 enforceTetherAccessPermission();
2624 if (isTetheringSupported()) {
2625 return mTethering.getTetherableBluetoothRegexs();
2626 } else {
2627 return new String[0];
2628 }
2629 }
2630
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002631 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002632 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002633 if (isTetheringSupported()) {
2634 return mTethering.setUsbTethering(enable);
2635 } else {
2636 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2637 }
2638 }
2639
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002640 // TODO - move iface listing, queries, etc to new module
2641 // javadoc from interface
2642 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002643 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002644 return mTethering.getTetherableIfaces();
2645 }
2646
2647 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002648 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002649 return mTethering.getTetheredIfaces();
2650 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002651
Robert Greenwalt5a735062010-03-02 17:25:02 -08002652 public String[] getTetheringErroredIfaces() {
2653 enforceTetherAccessPermission();
2654 return mTethering.getErroredIfaces();
2655 }
2656
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002657 public String[] getTetheredDhcpRanges() {
2658 enforceConnectivityInternalPermission();
2659 return mTethering.getTetheredDhcpRanges();
2660 }
2661
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002662 // if ro.tether.denied = true we default to no tethering
2663 // gservices could set the secure setting to 1 though to enable it on a build where it
2664 // had previously been turned off.
2665 public boolean isTetheringSupported() {
2666 enforceTetherAccessPermission();
2667 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002668 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002669 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2670 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002671 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2672 mTethering.getTetherableWifiRegexs().length != 0 ||
2673 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2674 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002675 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002676
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002677 // Called when we lose the default network and have no replacement yet.
2678 // This will automatically be cleared after X seconds or a new default network
2679 // becomes CONNECTED, whichever happens first. The timer is started by the
2680 // first caller and not restarted by subsequent callers.
2681 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002682 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002683 synchronized (this) {
2684 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002685 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002686 mNetTransitionWakeLock.acquire();
2687 mNetTransitionWakeLockCausedBy = forWhom;
2688 }
2689 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002690 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002691 mNetTransitionWakeLockTimeout);
2692 return;
2693 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002694
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002695 // 100 percent is full good, 0 is full bad.
2696 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002697 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002698 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002699 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002700 }
2701
Paul Jensenbfd17b72015-04-07 12:43:13 -04002702 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002703 enforceAccessPermission();
2704 enforceInternetPermission();
2705
Paul Jensenbfd17b72015-04-07 12:43:13 -04002706 NetworkAgentInfo nai;
2707 if (network == null) {
2708 nai = getDefaultNetwork();
2709 } else {
2710 nai = getNetworkAgentInfoForNetwork(network);
2711 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002712 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2713 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2714 return;
2715 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002716 // Revalidate if the app report does not match our current validated state.
2717 if (hasConnectivity == nai.lastValidated) return;
2718 final int uid = Binder.getCallingUid();
2719 if (DBG) {
2720 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2721 ") by " + uid);
2722 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002723 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002724 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2725 // which isn't meant to work on uncreated networks.
2726 if (!nai.created) return;
2727
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002728 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002729
2730 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2731 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002732 }
2733
Paul Jensencee9b512015-05-06 07:32:40 -04002734 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002735 // this information is already available as a world read/writable jvm property
2736 // so this API change wouldn't have a benifit. It also breaks the passing
2737 // of proxy info to all the JVMs.
2738 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002739 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002740 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002741 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2742 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002743 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002744 }
2745
Paul Jensencee9b512015-05-06 07:32:40 -04002746 public ProxyInfo getProxyForNetwork(Network network) {
2747 if (network == null) return getDefaultProxy();
2748 final ProxyInfo globalProxy = getGlobalProxy();
2749 if (globalProxy != null) return globalProxy;
2750 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2751 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2752 // caller may not have.
2753 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2754 if (nai == null) return null;
2755 synchronized (nai) {
2756 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2757 if (proxyInfo == null) return null;
2758 return new ProxyInfo(proxyInfo);
2759 }
2760 }
2761
Paul Jensene0bef712014-12-10 15:12:18 -05002762 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2763 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2764 // proxy is null then there is no proxy in place).
2765 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2766 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2767 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2768 proxy = null;
2769 }
2770 return proxy;
2771 }
2772
2773 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2774 // better for determining if a new proxy broadcast is necessary:
2775 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2776 // avoid unnecessary broadcasts.
2777 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2778 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2779 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2780 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2781 // all set.
2782 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2783 a = canonicalizeProxyInfo(a);
2784 b = canonicalizeProxyInfo(b);
2785 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2786 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2787 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2788 }
2789
Jason Monk207900c2014-04-25 15:00:09 -04002790 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002791 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002792
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002793 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002794 if (proxyProperties == mGlobalProxy) return;
2795 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2796 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2797
2798 String host = "";
2799 int port = 0;
2800 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002801 String pacFileUrl = "";
2802 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002803 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002804 if (!proxyProperties.isValid()) {
2805 if (DBG)
2806 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2807 return;
2808 }
Jason Monk207900c2014-04-25 15:00:09 -04002809 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002810 host = mGlobalProxy.getHost();
2811 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002812 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002813 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002814 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002815 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002816 } else {
2817 mGlobalProxy = null;
2818 }
2819 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002820 final long token = Binder.clearCallingIdentity();
2821 try {
2822 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2823 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2824 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2825 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002826 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002827 } finally {
2828 Binder.restoreCallingIdentity(token);
2829 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002830
Jason Monkcf0f97a2014-10-02 15:39:38 -04002831 if (mGlobalProxy == null) {
2832 proxyProperties = mDefaultProxy;
2833 }
2834 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002835 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002836 }
2837
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002838 private void loadGlobalProxy() {
2839 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002840 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2841 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2842 String exclList = Settings.Global.getString(res,
2843 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002844 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2845 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002846 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002847 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002848 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002849 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002850 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002851 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002852 if (!proxyProperties.isValid()) {
2853 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2854 return;
2855 }
2856
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002857 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002858 mGlobalProxy = proxyProperties;
2859 }
2860 }
2861 }
2862
Jason Monk207900c2014-04-25 15:00:09 -04002863 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002864 // this information is already available as a world read/writable jvm property
2865 // so this API change wouldn't have a benifit. It also breaks the passing
2866 // of proxy info to all the JVMs.
2867 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002868 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002869 return mGlobalProxy;
2870 }
2871 }
2872
Jason Monk207900c2014-04-25 15:00:09 -04002873 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002874 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002875 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002876 proxy = null;
2877 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002878 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002879 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002880 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002881 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002882 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2883 return;
2884 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002885
2886 // This call could be coming from the PacManager, containing the port of the local
2887 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2888 // global (to get the correct local port), and send a broadcast.
2889 // TODO: Switch PacManager to have its own message to send back rather than
2890 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002891 if ((mGlobalProxy != null) && (proxy != null)
2892 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002893 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2894 mGlobalProxy = proxy;
2895 sendProxyBroadcast(mGlobalProxy);
2896 return;
2897 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002898 mDefaultProxy = proxy;
2899
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002900 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002901 if (!mDefaultProxyDisabled) {
2902 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002903 }
2904 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002905 }
2906
Paul Jensene0bef712014-12-10 15:12:18 -05002907 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2908 // This method gets called when any network changes proxy, but the broadcast only ever contains
2909 // the default proxy (even if it hasn't changed).
2910 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2911 // world where an app might be bound to a non-default network.
2912 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2913 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2914 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2915
2916 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2917 sendProxyBroadcast(getDefaultProxy());
2918 }
2919 }
2920
Robert Greenwalt434203a2010-10-11 16:00:27 -07002921 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002922 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2923 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002924 if (!TextUtils.isEmpty(proxy)) {
2925 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002926 if (data.length == 0) {
2927 return;
2928 }
2929
Robert Greenwalt434203a2010-10-11 16:00:27 -07002930 String proxyHost = data[0];
2931 int proxyPort = 8080;
2932 if (data.length > 1) {
2933 try {
2934 proxyPort = Integer.parseInt(data[1]);
2935 } catch (NumberFormatException e) {
2936 return;
2937 }
2938 }
Jason Monk207900c2014-04-25 15:00:09 -04002939 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002940 setGlobalProxy(p);
2941 }
2942 }
2943
Jason Monk207900c2014-04-25 15:00:09 -04002944 private void sendProxyBroadcast(ProxyInfo proxy) {
2945 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002946 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002947 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002948 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002949 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2950 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002951 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002952 final long ident = Binder.clearCallingIdentity();
2953 try {
2954 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2955 } finally {
2956 Binder.restoreCallingIdentity(ident);
2957 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002958 }
2959
2960 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002961 final private HashMap<Uri, Integer> mUriEventMap;
2962 final private Context mContext;
2963 final private Handler mHandler;
2964
2965 SettingsObserver(Context context, Handler handler) {
2966 super(null);
2967 mUriEventMap = new HashMap<Uri, Integer>();
2968 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002969 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002970 }
2971
Erik Klineda4bfa82015-04-30 12:58:40 +09002972 void observe(Uri uri, int what) {
2973 mUriEventMap.put(uri, what);
2974 final ContentResolver resolver = mContext.getContentResolver();
2975 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002976 }
2977
2978 @Override
2979 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002980 Slog.wtf(TAG, "Should never be reached.");
2981 }
2982
2983 @Override
2984 public void onChange(boolean selfChange, Uri uri) {
2985 final Integer what = mUriEventMap.get(uri);
2986 if (what != null) {
2987 mHandler.obtainMessage(what.intValue()).sendToTarget();
2988 } else {
2989 loge("No matching event to send for URI=" + uri);
2990 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002991 }
2992 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002993
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002994 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002995 Slog.d(TAG, s);
2996 }
2997
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002998 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002999 Slog.e(TAG, s);
3000 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003001
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003002 private static <T> T checkNotNull(T value, String message) {
3003 if (value == null) {
3004 throw new NullPointerException(message);
3005 }
3006 return value;
3007 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003008
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003009 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003010 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003011 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3012 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3013 *
3014 * @param oldPackage Package name of the application which currently controls VPN, which will
3015 * be replaced. If there is no such application, this should should either be
3016 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3017 * @param newPackage Package name of the application which should gain control of VPN, or
3018 * {@code null} to disable.
3019 * @param userId User for whom to prepare the new VPN.
3020 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003021 * @hide
3022 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003023 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003024 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3025 int userId) {
3026 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003027 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003028
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003029 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003030 Vpn vpn = mVpns.get(userId);
3031 if (vpn != null) {
3032 return vpn.prepare(oldPackage, newPackage);
3033 } else {
3034 return false;
3035 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003036 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003037 }
3038
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003039 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003040 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3041 * This method is used by system-privileged apps.
3042 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3043 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3044 *
3045 * @param packageName The package for which authorization state should change.
3046 * @param userId User for whom {@code packageName} is installed.
3047 * @param authorized {@code true} if this app should be able to start a VPN connection without
3048 * explicit user approval, {@code false} if not.
3049 *
Jeff Davidson05542602014-08-11 14:07:27 -07003050 * @hide
3051 */
3052 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003053 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3054 enforceCrossUserPermission(userId);
3055
Jeff Davidson05542602014-08-11 14:07:27 -07003056 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003057 Vpn vpn = mVpns.get(userId);
3058 if (vpn != null) {
3059 vpn.setPackageAuthorization(packageName, authorized);
3060 }
Jeff Davidson05542602014-08-11 14:07:27 -07003061 }
3062 }
3063
3064 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003065 * Configure a TUN interface and return its file descriptor. Parameters
3066 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003067 * and not available in ConnectivityManager. Permissions are checked in
3068 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003069 * @hide
3070 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003071 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003072 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003073 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003074 int user = UserHandle.getUserId(Binder.getCallingUid());
3075 synchronized(mVpns) {
3076 return mVpns.get(user).establish(config);
3077 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003078 }
3079
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003080 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003081 * Start legacy VPN, controlling native daemons as needed. Creates a
3082 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003083 */
3084 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003085 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003086 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003087 final LinkProperties egress = getActiveLinkProperties();
3088 if (egress == null) {
3089 throw new IllegalStateException("Missing active network connection");
3090 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003091 int user = UserHandle.getUserId(Binder.getCallingUid());
3092 synchronized(mVpns) {
3093 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3094 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003095 }
3096
3097 /**
3098 * Return the information of the ongoing legacy VPN. This method is used
3099 * by VpnSettings and not available in ConnectivityManager. Permissions
3100 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003101 */
3102 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003103 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3104 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003105 if (mLockdownEnabled) {
3106 return null;
3107 }
3108
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003109 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003110 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003111 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003112 }
3113
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003114 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003115 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3116 * and not available in ConnectivityManager.
3117 */
3118 @Override
3119 public VpnInfo[] getAllVpnInfo() {
3120 enforceConnectivityInternalPermission();
3121 if (mLockdownEnabled) {
3122 return new VpnInfo[0];
3123 }
3124
3125 synchronized(mVpns) {
3126 List<VpnInfo> infoList = new ArrayList<>();
3127 for (int i = 0; i < mVpns.size(); i++) {
3128 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3129 if (info != null) {
3130 infoList.add(info);
3131 }
3132 }
3133 return infoList.toArray(new VpnInfo[infoList.size()]);
3134 }
3135 }
3136
3137 /**
3138 * @return VPN information for accounting, or null if we can't retrieve all required
3139 * information, e.g primary underlying iface.
3140 */
3141 @Nullable
3142 private VpnInfo createVpnInfo(Vpn vpn) {
3143 VpnInfo info = vpn.getVpnInfo();
3144 if (info == null) {
3145 return null;
3146 }
3147 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3148 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3149 // the underlyingNetworks list.
3150 if (underlyingNetworks == null) {
3151 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3152 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3153 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3154 }
3155 } else if (underlyingNetworks.length > 0) {
3156 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3157 if (linkProperties != null) {
3158 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3159 }
3160 }
3161 return info.primaryUnderlyingIface == null ? null : info;
3162 }
3163
3164 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003165 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3166 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003167 * Permissions are checked in Vpn class.
3168 * @hide
3169 */
3170 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003171 public VpnConfig getVpnConfig(int userId) {
3172 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003173 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003174 Vpn vpn = mVpns.get(userId);
3175 if (vpn != null) {
3176 return vpn.getVpnConfig();
3177 } else {
3178 return null;
3179 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003180 }
3181 }
3182
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003183 @Override
3184 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003185 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3186 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3187 return false;
3188 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003189
3190 // Tear down existing lockdown if profile was removed
3191 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3192 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003193 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003194 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3195 return false;
3196 }
3197
3198 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3199 final VpnProfile profile = VpnProfile.decode(
3200 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003201 int user = UserHandle.getUserId(Binder.getCallingUid());
3202 synchronized(mVpns) {
3203 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3204 profile));
3205 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003206 } else {
3207 setLockdownTracker(null);
3208 }
3209
3210 return true;
3211 }
3212
3213 /**
3214 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3215 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3216 */
3217 private void setLockdownTracker(LockdownVpnTracker tracker) {
3218 // Shutdown any existing tracker
3219 final LockdownVpnTracker existing = mLockdownTracker;
3220 mLockdownTracker = null;
3221 if (existing != null) {
3222 existing.shutdown();
3223 }
3224
3225 try {
3226 if (tracker != null) {
3227 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003228 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003229 mLockdownTracker = tracker;
3230 mLockdownTracker.init();
3231 } else {
3232 mNetd.setFirewallEnabled(false);
3233 }
3234 } catch (RemoteException e) {
3235 // ignored; NMS lives inside system_server
3236 }
3237 }
3238
3239 private void throwIfLockdownEnabled() {
3240 if (mLockdownEnabled) {
3241 throw new IllegalStateException("Unavailable in lockdown mode");
3242 }
3243 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003244
Wink Savilleab9321d2013-06-29 21:10:57 -07003245 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003246 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003247 // TODO: Remove? Any reason to trigger a provisioning check?
3248 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003249 }
3250
3251 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003252 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003253
Paul Jensen89e0f092014-09-15 15:59:36 -04003254 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003255 if (DBG) {
3256 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003257 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003258 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003259 Intent intent = new Intent(action);
3260 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003261 // Concatenate the range of types onto the range of NetIDs.
3262 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003263 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003264 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003265 }
3266
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003267 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003268 * Show or hide network provisioning notifications.
3269 *
3270 * We use notifications for two purposes: to notify that a network requires sign in
3271 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3272 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3273 * particular network we can display the notification type that was most recently requested.
3274 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3275 * might first display NO_INTERNET, and then when the captive portal check completes, display
3276 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003277 *
3278 * @param id an identifier that uniquely identifies this notification. This must match
3279 * between show and hide calls. We use the NetID value but for legacy callers
3280 * we concatenate the range of types with the range of NetIDs.
3281 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003282 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003283 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3284 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003285 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003286 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3287 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003288 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003289 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003290
3291 Resources r = Resources.getSystem();
3292 NotificationManager notificationManager = (NotificationManager) mContext
3293 .getSystemService(Context.NOTIFICATION_SERVICE);
3294
3295 if (visible) {
3296 CharSequence title;
3297 CharSequence details;
3298 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003299 if (notifyType == NotificationType.NO_INTERNET &&
3300 networkType == ConnectivityManager.TYPE_WIFI) {
3301 title = r.getString(R.string.wifi_no_internet, 0);
3302 details = r.getString(R.string.wifi_no_internet_detailed);
3303 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3304 } else if (notifyType == NotificationType.SIGN_IN) {
3305 switch (networkType) {
3306 case ConnectivityManager.TYPE_WIFI:
3307 title = r.getString(R.string.wifi_available_sign_in, 0);
3308 details = r.getString(R.string.network_available_sign_in_detailed,
3309 extraInfo);
3310 icon = R.drawable.stat_notify_wifi_in_range;
3311 break;
3312 case ConnectivityManager.TYPE_MOBILE:
3313 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3314 title = r.getString(R.string.network_available_sign_in, 0);
3315 // TODO: Change this to pull from NetworkInfo once a printable
3316 // name has been added to it
3317 details = mTelephonyManager.getNetworkOperatorName();
3318 icon = R.drawable.stat_notify_rssi_in_range;
3319 break;
3320 default:
3321 title = r.getString(R.string.network_available_sign_in, 0);
3322 details = r.getString(R.string.network_available_sign_in_detailed,
3323 extraInfo);
3324 icon = R.drawable.stat_notify_rssi_in_range;
3325 break;
3326 }
3327 } else {
3328 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3329 + getNetworkTypeName(networkType));
3330 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003331 }
3332
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003333 Notification notification = new Notification.Builder(mContext)
3334 .setWhen(0)
3335 .setSmallIcon(icon)
3336 .setAutoCancel(true)
3337 .setTicker(title)
3338 .setColor(mContext.getColor(
3339 com.android.internal.R.color.system_notification_accent_color))
3340 .setContentTitle(title)
3341 .setContentText(details)
3342 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003343 .setLocalOnly(true)
3344 .setPriority(highPriority ?
3345 Notification.PRIORITY_HIGH :
3346 Notification.PRIORITY_DEFAULT)
3347 .setDefaults(Notification.DEFAULT_ALL)
3348 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003349 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003350
Wink Saville948282b2013-08-29 08:55:16 -07003351 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003352 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003353 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003354 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003355 npe.printStackTrace();
3356 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003357 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003358 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003359 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003360 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003361 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003362 npe.printStackTrace();
3363 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003364 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003365 }
3366
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003367 /** Location to an updatable file listing carrier provisioning urls.
3368 * An example:
3369 *
3370 * <?xml version="1.0" encoding="utf-8"?>
3371 * <provisioningUrls>
3372 * <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 -07003373 * </provisioningUrls>
3374 */
3375 private static final String PROVISIONING_URL_PATH =
3376 "/data/misc/radio/provisioning_urls.xml";
3377 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003378
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003379 /** XML tag for root element. */
3380 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3381 /** XML tag for individual url */
3382 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003383 /** XML attribute for mcc */
3384 private static final String ATTR_MCC = "mcc";
3385 /** XML attribute for mnc */
3386 private static final String ATTR_MNC = "mnc";
3387
Paul Jensen434dde82015-06-11 09:43:30 -04003388 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003389 FileReader fileReader = null;
3390 XmlPullParser parser = null;
3391 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003392
3393 try {
3394 fileReader = new FileReader(mProvisioningUrlFile);
3395 parser = Xml.newPullParser();
3396 parser.setInput(fileReader);
3397 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3398
3399 while (true) {
3400 XmlUtils.nextElement(parser);
3401
3402 String element = parser.getName();
3403 if (element == null) break;
3404
Paul Jensen434dde82015-06-11 09:43:30 -04003405 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003406 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3407 try {
3408 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3409 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3410 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3411 parser.next();
3412 if (parser.getEventType() == XmlPullParser.TEXT) {
3413 return parser.getText();
3414 }
3415 }
3416 }
3417 } catch (NumberFormatException e) {
3418 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3419 }
3420 }
3421 }
3422 return null;
3423 } catch (FileNotFoundException e) {
3424 loge("Carrier Provisioning Urls file not found");
3425 } catch (XmlPullParserException e) {
3426 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3427 } catch (IOException e) {
3428 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3429 } finally {
3430 if (fileReader != null) {
3431 try {
3432 fileReader.close();
3433 } catch (IOException e) {}
3434 }
3435 }
3436 return null;
3437 }
3438
Wink Saville42d4f082013-07-20 20:31:59 -07003439 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003440 public String getMobileProvisioningUrl() {
3441 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003442 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003443 if (TextUtils.isEmpty(url)) {
3444 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003445 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003446 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003447 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003448 }
Wink Saville8cf35602013-07-10 23:00:07 -07003449 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003450 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003451 String phoneNumber = mTelephonyManager.getLine1Number();
3452 if (TextUtils.isEmpty(phoneNumber)) {
3453 phoneNumber = "0000000000";
3454 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003455 url = String.format(url,
3456 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3457 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003458 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003459 }
3460
Wink Savilleab9321d2013-06-29 21:10:57 -07003461 return url;
3462 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003463
Wink Saville948282b2013-08-29 08:55:16 -07003464 @Override
3465 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003466 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003467 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003468 final long ident = Binder.clearCallingIdentity();
3469 try {
3470 setProvNotificationVisible(visible, networkType, action);
3471 } finally {
3472 Binder.restoreCallingIdentity(ident);
3473 }
Wink Saville948282b2013-08-29 08:55:16 -07003474 }
Wink Saville7788c612013-08-29 14:57:08 -07003475
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003476 @Override
3477 public void setAirplaneMode(boolean enable) {
3478 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003479 final long ident = Binder.clearCallingIdentity();
3480 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003481 final ContentResolver cr = mContext.getContentResolver();
3482 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3483 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3484 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003485 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003486 } finally {
3487 Binder.restoreCallingIdentity(ident);
3488 }
3489 }
3490
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003491 private void onUserStart(int userId) {
3492 synchronized(mVpns) {
3493 Vpn userVpn = mVpns.get(userId);
3494 if (userVpn != null) {
3495 loge("Starting user already has a VPN");
3496 return;
3497 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003498 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003499 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003500 }
3501 }
3502
3503 private void onUserStop(int userId) {
3504 synchronized(mVpns) {
3505 Vpn userVpn = mVpns.get(userId);
3506 if (userVpn == null) {
3507 loge("Stopping user has no VPN");
3508 return;
3509 }
3510 mVpns.delete(userId);
3511 }
3512 }
3513
3514 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3515 @Override
3516 public void onReceive(Context context, Intent intent) {
3517 final String action = intent.getAction();
3518 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3519 if (userId == UserHandle.USER_NULL) return;
3520
3521 if (Intent.ACTION_USER_STARTING.equals(action)) {
3522 onUserStart(userId);
3523 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3524 onUserStop(userId);
3525 }
3526 }
3527 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003528
Robert Greenwalta67be032014-05-16 15:49:14 -07003529 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3530 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003531 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3532 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003533
Robert Greenwalta67be032014-05-16 15:49:14 -07003534 private static class NetworkFactoryInfo {
3535 public final String name;
3536 public final Messenger messenger;
3537 public final AsyncChannel asyncChannel;
3538
3539 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3540 this.name = name;
3541 this.messenger = messenger;
3542 this.asyncChannel = asyncChannel;
3543 }
3544 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003545
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003546 /**
3547 * Tracks info about the requester.
3548 * Also used to notice when the calling process dies so we can self-expire
3549 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003550 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3551 static final boolean REQUEST = true;
3552 static final boolean LISTEN = false;
3553
3554 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003555 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003556 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003557 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003558 final int mPid;
3559 final int mUid;
3560 final Messenger messenger;
3561 final boolean isRequest;
3562
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003563 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3564 request = r;
3565 mPendingIntent = pi;
3566 messenger = null;
3567 mBinder = null;
3568 mPid = getCallingPid();
3569 mUid = getCallingUid();
3570 this.isRequest = isRequest;
3571 }
3572
Robert Greenwalt9258c642014-03-26 16:47:06 -07003573 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3574 super();
3575 messenger = m;
3576 request = r;
3577 mBinder = binder;
3578 mPid = getCallingPid();
3579 mUid = getCallingUid();
3580 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003581 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003582
3583 try {
3584 mBinder.linkToDeath(this, 0);
3585 } catch (RemoteException e) {
3586 binderDied();
3587 }
3588 }
3589
3590 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003591 if (mBinder != null) {
3592 mBinder.unlinkToDeath(this, 0);
3593 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003594 }
3595
3596 public void binderDied() {
3597 log("ConnectivityService NetworkRequestInfo binderDied(" +
3598 request + ", " + mBinder + ")");
3599 releaseNetworkRequest(request);
3600 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003601
3602 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003603 return (isRequest ? "Request" : "Listen") +
3604 " from uid/pid:" + mUid + "/" + mPid +
3605 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003606 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003607 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003608 }
3609
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003610 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3611 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3612 if (badCapability != null) {
3613 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003614 }
3615 }
3616
Erik Kline9d598e12015-07-13 16:37:51 +09003617 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003618 final SortedSet<Integer> thresholds = new TreeSet();
3619 synchronized (nai) {
3620 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3621 if (nri.request.networkCapabilities.hasSignalStrength() &&
3622 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3623 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3624 }
3625 }
3626 }
Erik Kline9d598e12015-07-13 16:37:51 +09003627 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003628 }
3629
3630 private void updateSignalStrengthThresholds(NetworkAgentInfo nai) {
Erik Kline9d598e12015-07-13 16:37:51 +09003631 Bundle thresholds = new Bundle();
3632 thresholds.putIntegerArrayList("thresholds", getSignalStrengthThresholds(nai));
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003633 nai.asyncChannel.sendMessage(
3634 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003635 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003636 }
3637
Robert Greenwalt9258c642014-03-26 16:47:06 -07003638 @Override
3639 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003640 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003641 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003642 enforceNetworkRequestPermissions(networkCapabilities);
3643 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003644 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003645
Robert Greenwalt6078b502014-06-11 16:05:07 -07003646 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003647 throw new IllegalArgumentException("Bad timeout specified");
3648 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003649
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003650 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3651 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003652 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3653 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003654 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003655
3656 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003657 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003658 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003659 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003660 }
3661 return networkRequest;
3662 }
3663
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003664 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003665 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003666 enforceConnectivityInternalPermission();
3667 } else {
3668 enforceChangePermission();
3669 }
3670 }
3671
fenglub15e72b2015-03-20 11:29:56 -07003672 @Override
fengludb571472015-04-21 17:12:05 -07003673 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003674 enforceAccessPermission();
3675 NetworkAgentInfo nai = null;
3676 if (network == null) {
3677 return false;
3678 }
3679 synchronized (mNetworkForNetId) {
3680 nai = mNetworkForNetId.get(network.netId);
3681 }
3682 if (nai != null) {
3683 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3684 return true;
3685 }
3686 return false;
3687 }
3688
3689
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003690 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3691 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003692 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003693 final int uidRules;
3694 final int uid = Binder.getCallingUid();
3695 synchronized(mRulesLock) {
3696 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3697 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003698 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003699 // we could silently fail or we can filter the available nets to only give
3700 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003701 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003702 }
3703 }
3704 }
3705
Robert Greenwalt9258c642014-03-26 16:47:06 -07003706 @Override
3707 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3708 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003709 checkNotNull(operation, "PendingIntent cannot be null.");
3710 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3711 enforceNetworkRequestPermissions(networkCapabilities);
3712 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003713 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003714
3715 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3716 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003717 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3718 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003719 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3721 nri));
3722 return networkRequest;
3723 }
3724
Jeremy Joslin79294842014-12-03 17:15:28 -08003725 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3726 mHandler.sendMessageDelayed(
3727 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3728 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3729 }
3730
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003731 @Override
3732 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003733 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003734 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3735 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003736 }
3737
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003738 // In order to implement the compatibility measure for pre-M apps that call
3739 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3740 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3741 // This ensures it has permission to do so.
3742 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3743 if (nc == null) {
3744 return false;
3745 }
3746 int[] transportTypes = nc.getTransportTypes();
3747 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3748 return false;
3749 }
3750 try {
3751 mContext.enforceCallingOrSelfPermission(
3752 android.Manifest.permission.ACCESS_WIFI_STATE,
3753 "ConnectivityService");
3754 } catch (SecurityException e) {
3755 return false;
3756 }
3757 return true;
3758 }
3759
Robert Greenwalt9258c642014-03-26 16:47:06 -07003760 @Override
3761 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3762 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003763 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3764 enforceAccessPermission();
3765 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003766
Erik Kline7523eb32015-07-09 18:24:03 +09003767 NetworkRequest networkRequest = new NetworkRequest(
3768 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003769 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3770 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003771 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003772
3773 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3774 return networkRequest;
3775 }
3776
3777 @Override
3778 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3779 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003780 checkNotNull(operation, "PendingIntent cannot be null.");
3781 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3782 enforceAccessPermission();
3783 }
3784
Erik Kline7523eb32015-07-09 18:24:03 +09003785 NetworkRequest networkRequest = new NetworkRequest(
3786 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003787 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3788 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003789 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003790
3791 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003792 }
3793
3794 @Override
3795 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003796 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3797 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003798 }
3799
3800 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003801 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003802 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003803 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3804 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003805 }
3806
Robert Greenwalta67be032014-05-16 15:49:14 -07003807 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003808 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003809 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3810 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3811 }
3812
3813 @Override
3814 public void unregisterNetworkFactory(Messenger messenger) {
3815 enforceConnectivityInternalPermission();
3816 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3817 }
3818
3819 private void handleUnregisterNetworkFactory(Messenger messenger) {
3820 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3821 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003822 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003823 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003824 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003825 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003826 }
3827
Robert Greenwalt7b816022014-04-18 15:25:25 -07003828 /**
3829 * NetworkAgentInfo supporting a request by requestId.
3830 * These have already been vetted (their Capabilities satisfy the request)
3831 * and the are the highest scored network available.
3832 * the are keyed off the Requests requestId.
3833 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003834 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003835 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3836 new SparseArray<NetworkAgentInfo>();
3837
Paul Jensen31a94f42015-02-13 14:18:39 -05003838 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3839 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003840 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3841 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003842 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3843 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3844 // there may not be a strict 1:1 correlation between the two.
3845 @GuardedBy("mNetworkForNetId")
3846 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003847
Robert Greenwalt7b816022014-04-18 15:25:25 -07003848 // NetworkAgentInfo keyed off its connecting messenger
3849 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003850 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003851 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3852 new HashMap<Messenger, NetworkAgentInfo>();
3853
Paul Jensen2c311d62014-11-17 12:34:51 -05003854 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003855 private final NetworkRequest mDefaultRequest;
3856
Erik Klineda4bfa82015-04-30 12:58:40 +09003857 // Request used to optionally keep mobile data active even when higher
3858 // priority networks like Wi-Fi are active.
3859 private final NetworkRequest mDefaultMobileDataRequest;
3860
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003861 private NetworkAgentInfo getDefaultNetwork() {
3862 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3863 }
3864
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003865 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003866 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003867 }
3868
Paul Jensen31a94f42015-02-13 14:18:39 -05003869 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003870 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003871 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003872 enforceConnectivityInternalPermission();
3873
Paul Jensen2c311d62014-11-17 12:34:51 -05003874 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3875 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04003876 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003877 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3878 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04003879 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003880 synchronized (this) {
3881 nai.networkMonitor.systemReady = mSystemReady;
3882 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003883 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003884 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003885 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003886 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003887 }
3888
3889 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3890 if (VDBG) log("Got NetworkAgent Messenger");
3891 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003892 synchronized (mNetworkForNetId) {
3893 mNetworkForNetId.put(na.network.netId, na);
3894 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003895 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3896 NetworkInfo networkInfo = na.networkInfo;
3897 na.networkInfo = null;
3898 updateNetworkInfo(na, networkInfo);
3899 }
3900
3901 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3902 LinkProperties newLp = networkAgent.linkProperties;
3903 int netId = networkAgent.network.netId;
3904
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003905 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3906 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003907 if (networkAgent.clatd != null) {
3908 networkAgent.clatd.fixupLinkProperties(oldLp);
3909 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003910
Paul Jensen992f2522014-04-28 10:33:11 -04003911 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003912 updateMtu(newLp, oldLp);
3913 // TODO - figure out what to do for clat
3914// for (LinkProperties lp : newLp.getStackedLinks()) {
3915// updateMtu(lp, null);
3916// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003917 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003918
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003919 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3920 // In L, we used it only when the network had Internet access but provided no DNS servers.
3921 // For now, just disable it, and if disabling it doesn't break things, remove it.
3922 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3923 // NET_CAPABILITY_INTERNET);
3924 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003925 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003926 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3927
Paul Jensen3b759822014-05-13 11:44:01 -04003928 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003929 if (isDefaultNetwork(networkAgent)) {
3930 handleApplyDefaultProxy(newLp.getHttpProxy());
3931 } else {
3932 updateProxy(newLp, oldLp, networkAgent);
3933 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003934 // TODO - move this check to cover the whole function
3935 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003936 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003937 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3938 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003939
3940 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04003941 }
3942
Lorenzo Colitti95439462014-10-09 13:44:48 +09003943 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3944 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3945 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003946
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003947 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003948 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3949 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003950 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003951 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003952 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003953 }
Paul Jensen992f2522014-04-28 10:33:11 -04003954
3955 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3956 CompareResult<String> interfaceDiff = new CompareResult<String>();
3957 if (oldLp != null) {
3958 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3959 } else if (newLp != null) {
3960 interfaceDiff.added = newLp.getAllInterfaceNames();
3961 }
3962 for (String iface : interfaceDiff.added) {
3963 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003964 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003965 mNetd.addInterfaceToNetwork(iface, netId);
3966 } catch (Exception e) {
3967 loge("Exception adding interface: " + e);
3968 }
3969 }
3970 for (String iface : interfaceDiff.removed) {
3971 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003972 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003973 mNetd.removeInterfaceFromNetwork(iface, netId);
3974 } catch (Exception e) {
3975 loge("Exception removing interface: " + e);
3976 }
3977 }
3978 }
3979
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003980 /**
3981 * Have netd update routes from oldLp to newLp.
3982 * @return true if routes changed between oldLp and newLp
3983 */
3984 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003985 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3986 if (oldLp != null) {
3987 routeDiff = oldLp.compareAllRoutes(newLp);
3988 } else if (newLp != null) {
3989 routeDiff.added = newLp.getAllRoutes();
3990 }
3991
3992 // add routes before removing old in case it helps with continuous connectivity
3993
3994 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3995 for (RouteInfo route : routeDiff.added) {
3996 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003997 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003998 try {
3999 mNetd.addRoute(netId, route);
4000 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004001 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4002 loge("Exception in addRoute for non-gateway: " + e);
4003 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004004 }
4005 }
4006 for (RouteInfo route : routeDiff.added) {
4007 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004008 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004009 try {
4010 mNetd.addRoute(netId, route);
4011 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004012 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4013 loge("Exception in addRoute for gateway: " + e);
4014 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004015 }
4016 }
4017
4018 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004019 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004020 try {
4021 mNetd.removeRoute(netId, route);
4022 } catch (Exception e) {
4023 loge("Exception in removeRoute: " + e);
4024 }
4025 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004026 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004027 }
Erik Kline41368502015-06-17 13:19:54 +09004028
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004029 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4030 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004031 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09004032 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004033 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004034 dnses = new ArrayList();
4035 dnses.add(mDefaultDns);
4036 if (DBG) {
4037 loge("no dns provided for netId " + netId + ", so using defaults");
4038 }
4039 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004040 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004041 try {
4042 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4043 newLp.getDomains());
4044 } catch (Exception e) {
4045 loge("Exception in setDnsServersForNetwork: " + e);
4046 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04004047 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004048 if (defaultNai != null && defaultNai.network.netId == netId) {
4049 setDefaultDnsSystemProperties(dnses);
4050 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004051 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004052 } else if (flush) {
4053 try {
4054 mNetd.flushNetworkDnsCache(netId);
4055 } catch (Exception e) {
4056 loge("Exception in flushNetworkDnsCache: " + e);
4057 }
4058 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004059 }
4060 }
4061
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004062 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4063 int last = 0;
4064 for (InetAddress dns : dnses) {
4065 ++last;
4066 String key = "net.dns" + last;
4067 String value = dns.getHostAddress();
4068 SystemProperties.set(key, value);
4069 }
4070 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4071 String key = "net.dns" + i;
4072 SystemProperties.set(key, "");
4073 }
4074 mNumDnsEntries = last;
4075 }
4076
Paul Jensen3d194ea2015-06-16 14:27:36 -04004077 /**
4078 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4079 * augmented with any stateful capabilities implied from {@code networkAgent}
4080 * (e.g., validated status and captive portal status).
4081 *
Paul Jensene0988542015-06-25 15:30:08 -04004082 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004083 * @param networkCapabilities the new network capabilities.
4084 */
Paul Jensene0988542015-06-25 15:30:08 -04004085 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004086 // Don't modify caller's NetworkCapabilities.
4087 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004088 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004089 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4090 } else {
4091 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4092 }
Paul Jensene0988542015-06-25 15:30:08 -04004093 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004094 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4095 } else {
4096 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4097 }
Paul Jensene0988542015-06-25 15:30:08 -04004098 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4099 final int oldScore = nai.getCurrentScore();
4100 synchronized (nai) {
4101 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004102 }
Paul Jensene0988542015-06-25 15:30:08 -04004103 rematchAllNetworksAndRequests(nai, oldScore);
4104 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004105 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004106 }
4107
Paul Jensenc8b9a742014-09-30 15:37:41 -04004108 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4109 for (int i = 0; i < nai.networkRequests.size(); i++) {
4110 NetworkRequest nr = nai.networkRequests.valueAt(i);
4111 // Don't send listening requests to factories. b/17393458
4112 if (!isRequest(nr)) continue;
4113 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4114 }
4115 }
4116
Robert Greenwalt7b816022014-04-18 15:25:25 -07004117 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4118 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004119 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004120 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4121 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004122 }
4123 }
4124
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004125 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4126 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004127 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004128 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004129 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4130 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004131 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004132 sendIntent(nri.mPendingIntent, intent);
4133 }
4134 // else not handled
4135 }
4136
4137 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4138 mPendingIntentWakeLock.acquire();
4139 try {
4140 if (DBG) log("Sending " + pendingIntent);
4141 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4142 } catch (PendingIntent.CanceledException e) {
4143 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4144 mPendingIntentWakeLock.release();
4145 releasePendingNetworkRequest(pendingIntent);
4146 }
4147 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4148 }
4149
4150 @Override
4151 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4152 String resultData, Bundle resultExtras) {
4153 if (DBG) log("Finished sending " + pendingIntent);
4154 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004155 // Release with a delay so the receiving client has an opportunity to put in its
4156 // own request.
4157 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004158 }
4159
Robert Greenwalt9258c642014-03-26 16:47:06 -07004160 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004161 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004162 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004163 Bundle bundle = new Bundle();
4164 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4165 new NetworkRequest(nri.request));
4166 Message msg = Message.obtain();
4167 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4168 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4169 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4170 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004172 case ConnectivityManager.CALLBACK_LOSING: {
4173 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4174 break;
4175 }
4176 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4177 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4178 new NetworkCapabilities(networkAgent.networkCapabilities));
4179 break;
4180 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004181 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004182 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4183 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004184 break;
4185 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004186 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004187 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004188 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004189 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004190 if (VDBG) {
4191 log("sending notification " + notifyTypeToName(notificationType) +
4192 " for " + nri.request);
4193 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194 nri.messenger.send(msg);
4195 } catch (RemoteException e) {
4196 // may occur naturally in the race of binder death.
4197 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4198 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004199 }
4200
Paul Jensenc8b9a742014-09-30 15:37:41 -04004201 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4202 for (int i = 0; i < nai.networkRequests.size(); i++) {
4203 NetworkRequest nr = nai.networkRequests.valueAt(i);
4204 // Ignore listening requests.
4205 if (!isRequest(nr)) continue;
4206 loge("Dead network still had at least " + nr);
4207 break;
4208 }
4209 nai.asyncChannel.disconnect();
4210 }
4211
Robert Greenwalt7b816022014-04-18 15:25:25 -07004212 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4213 if (oldNetwork == null) {
4214 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4215 return;
4216 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004217 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4218 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004219 }
4220
Paul Jensen27b02b72014-07-14 12:03:33 -04004221 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004222 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004223 setupDataActivityTracking(newNetwork);
4224 try {
4225 mNetd.setDefaultNetId(newNetwork.network.netId);
4226 } catch (Exception e) {
4227 loge("Exception setting default network :" + e);
4228 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004229 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004230 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004231 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004232 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004233 }
4234
Paul Jensen2161a8e2014-09-11 11:00:39 -04004235 // Handles a network appearing or improving its score.
4236 //
4237 // - Evaluates all current NetworkRequests that can be
4238 // satisfied by newNetwork, and reassigns to newNetwork
4239 // any such requests for which newNetwork is the best.
4240 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004241 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004242 // needed. A network is needed if it is the best network for
4243 // one or more NetworkRequests, or if it is a VPN.
4244 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004245 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004246 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004247 //
4248 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4249 // networks that have no chance (i.e. even if validated)
4250 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004251 //
4252 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4253 // it does not remove NetworkRequests that other Networks could better satisfy.
4254 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4255 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4256 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004257 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004258 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004259 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4260 // performed to tear down unvalidated networks that have no chance (i.e. even if
4261 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004262 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004263 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004264 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004265 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004266 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004267 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004268 if (DBG) log("rematching " + newNetwork.name());
4269 // Find and migrate to this Network any NetworkRequests for
4270 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004271 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004272 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004273 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004274 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004275 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4276 final boolean satisfies = newNetwork.satisfies(nri.request);
4277 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004278 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004279 log("Network " + newNetwork.name() + " was already satisfying" +
4280 " request " + nri.request.requestId + ". No change.");
4281 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004282 keep = true;
4283 continue;
4284 }
4285
4286 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004287 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004288 if (satisfies) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004289 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004290 // This is not a request, it's a callback listener.
4291 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004292 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004293 continue;
4294 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004295
Robert Greenwalt7b816022014-04-18 15:25:25 -07004296 // next check if it's better than any current network we're using for
4297 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004298 if (VDBG) {
4299 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004300 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4301 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004302 }
4303 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004304 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004305 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004306 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004307 currentNetwork.networkRequests.remove(nri.request.requestId);
4308 currentNetwork.networkLingered.add(nri.request);
4309 affectedNetworks.add(currentNetwork);
4310 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004311 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004312 }
Paul Jensen573a0352015-01-08 10:49:34 -05004313 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004314 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004315 if (!newNetwork.addRequest(nri.request)) {
4316 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4317 }
4318 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004319 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004320 // Tell NetworkFactories about the new score, so they can stop
4321 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004322 // TODO - this could get expensive if we have alot of requests for this
4323 // network. Think about if there is a way to reduce this. Push
4324 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004325 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004326 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004327 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004328 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004329 }
4330 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004331 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4332 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4333 // mark it as no longer satisfying "nri". Because networks are processed by
4334 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4335 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4336 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4337 // This means this code doesn't have to handle the case where "currentNetwork" no
4338 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4339 if (DBG) {
4340 log("Network " + newNetwork.name() + " stopped satisfying" +
4341 " request " + nri.request.requestId);
4342 }
4343 newNetwork.networkRequests.remove(nri.request.requestId);
4344 if (currentNetwork == newNetwork) {
4345 mNetworkForRequestId.remove(nri.request.requestId);
4346 sendUpdatedScoreToFactories(nri.request, 0);
4347 } else {
4348 if (nri.isRequest == true) {
4349 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4350 newNetwork.name() +
4351 " without updating mNetworkForRequestId or factories!");
4352 }
4353 }
4354 // TODO: technically, sending CALLBACK_LOST here is
4355 // incorrect if nri is a request (not a listen) and there
4356 // is a replacement network currently connected that can
4357 // satisfy it. However, the only capability that can both
4358 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4359 // so this code is only incorrect for a network that loses
4360 // the TRUSTED capability, which is a rare case.
4361 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004362 }
4363 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004364 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004365 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004366 if (nai.lingering) {
4367 // Already lingered. Nothing to do. This can only happen if "nai" is in
4368 // "affectedNetworks" twice. The reasoning being that to get added to
4369 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4370 // (i.e. not lingered) so it could have only been lingered by this loop.
4371 // unneeded(nai) will be false and we'll call unlinger() below which would
4372 // be bad, so handle it here.
4373 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004374 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004375 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004376 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004377 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004378 }
4379 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004380 if (isNewDefault) {
4381 // Notify system services that this network is up.
4382 makeDefault(newNetwork);
4383 synchronized (ConnectivityService.this) {
4384 // have a new default network, release the transition wakelock in
4385 // a second if it's held. The second pause is to allow apps
4386 // to reconnect over the new network
4387 if (mNetTransitionWakeLock.isHeld()) {
4388 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4389 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4390 mNetTransitionWakeLockSerialNumber, 0),
4391 1000);
4392 }
4393 }
4394 }
4395
4396 // do this after the default net is switched, but
4397 // before LegacyTypeTracker sends legacy broadcasts
4398 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4399
4400 if (isNewDefault) {
4401 // Maintain the illusion: since the legacy API only
4402 // understands one network at a time, we must pretend
4403 // that the current default network disconnected before
4404 // the new one connected.
4405 if (oldDefaultNetwork != null) {
4406 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4407 oldDefaultNetwork, true);
4408 }
4409 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4410 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4411 notifyLockdownVpn(newNetwork);
4412 }
4413
Robert Greenwalt7b816022014-04-18 15:25:25 -07004414 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004415 // Notify battery stats service about this network, both the normal
4416 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004417 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004418 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004419 final IBatteryStats bs = BatteryStatsService.getService();
4420 final int type = newNetwork.networkInfo.getType();
4421
4422 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4423 bs.noteNetworkInterfaceType(baseIface, type);
4424 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4425 final String stackedIface = stacked.getInterfaceName();
4426 bs.noteNetworkInterfaceType(stackedIface, type);
4427 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4428 }
4429 } catch (RemoteException ignored) {
4430 }
4431
Robert Greenwalt152ed372014-12-17 17:19:53 -08004432 // This has to happen after the notifyNetworkCallbacks as that tickles each
4433 // ConnectivityManager instance so that legacy requests correctly bind dns
4434 // requests to this network. The legacy users are listening for this bcast
4435 // and will generally do a dns request so they can ensureRouteToHost and if
4436 // they do that before the callbacks happen they'll use the default network.
4437 //
4438 // TODO: Is there still a race here? We send the broadcast
4439 // after sending the callback, but if the app can receive the
4440 // broadcast before the callback, it might still break.
4441 //
4442 // This *does* introduce a race where if the user uses the new api
4443 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4444 // they may get old info. Reverse this after the old startUsing api is removed.
4445 // This is on top of the multiple intent sequencing referenced in the todo above.
4446 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4447 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4448 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4449 // legacy type tracker filters out repeat adds
4450 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4451 }
4452 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004453
4454 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4455 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4456 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4457 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4458 if (newNetwork.isVPN()) {
4459 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4460 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004461 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004462 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4463 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004464 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004465 if (DBG) log("Reaping " + nai.name());
4466 teardownUnneededNetwork(nai);
4467 }
4468 }
4469 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004470 }
4471
Paul Jensen1c7ba022015-06-16 14:27:36 -04004472 /**
4473 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4474 * being disconnected.
4475 * @param changed If only one Network's score or capabilities have been modified since the last
4476 * time this function was called, pass this Network in this argument, otherwise pass
4477 * null.
4478 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4479 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4480 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4481 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4482 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004483 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004484 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004485 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4486 // to avoid the slowness. It is not simply enough to process just "changed", for
4487 // example in the case where "changed"'s score decreases and another network should begin
4488 // satifying a NetworkRequest that "changed" currently satisfies.
4489
4490 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4491 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4492 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004493 if (changed != null && oldScore < changed.getCurrentScore()) {
4494 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004495 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004496 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4497 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4498 // Rematch higher scoring networks first to prevent requests first matching a lower
4499 // scoring network and then a higher scoring network, which could produce multiple
4500 // callbacks and inadvertently unlinger networks.
4501 Arrays.sort(nais);
4502 for (NetworkAgentInfo nai : nais) {
4503 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004504 // Only reap the last time through the loop. Reaping before all rematching
4505 // is complete could incorrectly teardown a network that hasn't yet been
4506 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004507 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004508 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004509 }
4510 }
4511 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004512
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004513 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004514 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004515 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004516 // For now only update icons for default connection.
4517 // TODO: Update WiFi and cellular icons separately. b/17237507
4518 if (!isDefaultNetwork(nai)) return;
4519
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004520 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004521 // Don't repeat publish.
4522 if (newInetCondition == mDefaultInetConditionPublished) return;
4523
4524 mDefaultInetConditionPublished = newInetCondition;
4525 sendInetConditionBroadcast(nai.networkInfo);
4526 }
4527
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004528 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4529 if (mLockdownTracker != null) {
4530 if (nai != null && nai.isVPN()) {
4531 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4532 } else {
4533 mLockdownTracker.onNetworkInfoChanged();
4534 }
4535 }
4536 }
4537
Robert Greenwalt7b816022014-04-18 15:25:25 -07004538 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4539 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004540 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004541 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004542 synchronized (networkAgent) {
4543 oldInfo = networkAgent.networkInfo;
4544 networkAgent.networkInfo = newInfo;
4545 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004546 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004547
4548 if (oldInfo != null && oldInfo.getState() == state) {
4549 if (VDBG) log("ignoring duplicate network state non-change");
4550 return;
4551 }
4552 if (DBG) {
4553 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4554 (oldInfo == null ? "null" : oldInfo.getState()) +
4555 " to " + state);
4556 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004557
Paul Jenseneec75412014-08-04 12:21:19 -04004558 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004559 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004560 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004561 if (networkAgent.isVPN()) {
4562 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004563 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4564 (networkAgent.networkMisc == null ||
4565 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004566 } else {
4567 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4568 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004569 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004570 loge("Error creating network " + networkAgent.network.netId + ": "
4571 + e.getMessage());
4572 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004573 }
Paul Jenseneec75412014-08-04 12:21:19 -04004574 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004575 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004576 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004577
Paul Jensenca8f16a2014-05-09 12:47:55 -04004578 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004579 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004580
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004581 if (networkAgent.isVPN()) {
4582 // Temporarily disable the default proxy (not global).
4583 synchronized (mProxyLock) {
4584 if (!mDefaultProxyDisabled) {
4585 mDefaultProxyDisabled = true;
4586 if (mGlobalProxy == null && mDefaultProxy != null) {
4587 sendProxyBroadcast(null);
4588 }
4589 }
4590 }
4591 // TODO: support proxy per network.
4592 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004593
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004594 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4595 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4596 // capabilities, so it only needs to be done once on initial connect, not every time the
4597 // network's capabilities change. Note that we do this before rematching the network,
4598 // so we could decide to tear it down immediately afterwards. That's fine though - on
4599 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4600 // doing.
4601 updateSignalStrengthThresholds(networkAgent);
4602
Paul Jensen2161a8e2014-09-11 11:00:39 -04004603 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004604 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004605
4606 // This has to happen after matching the requests, because callbacks are just requests.
4607 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004608 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004609 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004610 if (networkAgent.isVPN()) {
4611 synchronized (mProxyLock) {
4612 if (mDefaultProxyDisabled) {
4613 mDefaultProxyDisabled = false;
4614 if (mGlobalProxy == null && mDefaultProxy != null) {
4615 sendProxyBroadcast(mDefaultProxy);
4616 }
4617 }
4618 }
4619 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004620 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4621 state == NetworkInfo.State.SUSPENDED) {
4622 // going into or coming out of SUSPEND: rescore and notify
4623 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004624 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004625 }
4626 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4627 ConnectivityManager.CALLBACK_SUSPENDED :
4628 ConnectivityManager.CALLBACK_RESUMED));
4629 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004630 }
4631 }
4632
Robert Greenwaltac96c522014-06-03 16:43:57 -07004633 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4634 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004635 if (score < 0) {
4636 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4637 "). Bumping score to min of 0");
4638 score = 0;
4639 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004640
Paul Jensen2161a8e2014-09-11 11:00:39 -04004641 final int oldScore = nai.getCurrentScore();
4642 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004643
Paul Jensen85cf78e2015-06-25 13:25:07 -04004644 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004645
Paul Jensenc8b9a742014-09-30 15:37:41 -04004646 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004647 }
4648
Robert Greenwalt9258c642014-03-26 16:47:06 -07004649 // notify only this one new request of the current state
4650 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4651 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4652 // TODO - read state from monitor to decide what to send.
4653// if (nai.networkMonitor.isLingering()) {
4654// notifyType = NetworkCallbacks.LOSING;
4655// } else if (nai.networkMonitor.isEvaluating()) {
4656// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4657// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004658 if (nri.mPendingIntent == null) {
4659 callCallbackForRequest(nri, nai, notifyType);
4660 } else {
4661 sendPendingIntentForRequest(nri, nai, notifyType);
4662 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004663 }
4664
Robert Greenwalt8d482522015-06-24 13:23:42 -07004665 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004666 // The NetworkInfo we actually send out has no bearing on the real
4667 // state of affairs. For example, if the default connection is mobile,
4668 // and a request for HIPRI has just gone away, we need to pretend that
4669 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4670 // the state to DISCONNECTED, even though the network is of type MOBILE
4671 // and is still connected.
4672 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4673 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004674 if (state != DetailedState.DISCONNECTED) {
4675 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004676 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004677 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004678 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004679 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4680 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4681 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4682 if (info.isFailover()) {
4683 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4684 nai.networkInfo.setFailover(false);
4685 }
4686 if (info.getReason() != null) {
4687 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4688 }
4689 if (info.getExtraInfo() != null) {
4690 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4691 }
4692 NetworkAgentInfo newDefaultAgent = null;
4693 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004694 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004695 if (newDefaultAgent != null) {
4696 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4697 newDefaultAgent.networkInfo);
4698 } else {
4699 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4700 }
4701 }
4702 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4703 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004704 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004705 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004706 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004707 }
4708 }
4709 }
4710
Robert Greenwalt7b816022014-04-18 15:25:25 -07004711 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004712 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004713 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004714 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4715 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4716 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004717 if (nri.mPendingIntent == null) {
4718 callCallbackForRequest(nri, networkAgent, notifyType);
4719 } else {
4720 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4721 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004722 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004723 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004724
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004725 private String notifyTypeToName(int notifyType) {
4726 switch (notifyType) {
4727 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4728 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4729 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4730 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4731 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4732 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4733 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4734 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4735 }
4736 return "UNKNOWN";
4737 }
4738
Jeff Sharkey69736342014-12-08 14:50:12 -08004739 /**
4740 * Notify other system services that set of active ifaces has changed.
4741 */
4742 private void notifyIfacesChanged() {
4743 try {
4744 mStatsService.forceUpdateIfaces();
4745 } catch (Exception ignored) {
4746 }
4747 }
4748
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004749 @Override
4750 public boolean addVpnAddress(String address, int prefixLength) {
4751 throwIfLockdownEnabled();
4752 int user = UserHandle.getUserId(Binder.getCallingUid());
4753 synchronized (mVpns) {
4754 return mVpns.get(user).addAddress(address, prefixLength);
4755 }
4756 }
4757
4758 @Override
4759 public boolean removeVpnAddress(String address, int prefixLength) {
4760 throwIfLockdownEnabled();
4761 int user = UserHandle.getUserId(Binder.getCallingUid());
4762 synchronized (mVpns) {
4763 return mVpns.get(user).removeAddress(address, prefixLength);
4764 }
4765 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004766
4767 @Override
4768 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4769 throwIfLockdownEnabled();
4770 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004771 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004772 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004773 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004774 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004775 if (success) {
4776 notifyIfacesChanged();
4777 }
4778 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004779 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004780
4781 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004782 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4783 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4784 enforceKeepalivePermission();
4785 mKeepaliveTracker.startNattKeepalive(
4786 getNetworkAgentInfoForNetwork(network),
4787 intervalSeconds, messenger, binder,
4788 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4789 }
4790
4791 @Override
4792 public void stopKeepalive(Network network, int slot) {
4793 mHandler.sendMessage(mHandler.obtainMessage(
4794 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
4795 }
4796
4797 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07004798 public void factoryReset() {
4799 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004800
4801 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4802 return;
4803 }
4804
Robin Lee3b3dd942015-05-12 18:14:58 +01004805 final int userId = UserHandle.getCallingUserId();
4806
Stuart Scottf1fb3972015-04-02 18:00:02 -07004807 // Turn airplane mode off
4808 setAirplaneMode(false);
4809
Stuart Scotte3e314d2015-04-20 14:07:45 -07004810 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4811 // Untether
4812 for (String tether : getTetheredIfaces()) {
4813 untether(tether);
4814 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004815 }
4816
Stuart Scotte3e314d2015-04-20 14:07:45 -07004817 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4818 // Turn VPN off
4819 VpnConfig vpnConfig = getVpnConfig(userId);
4820 if (vpnConfig != null) {
4821 if (vpnConfig.legacy) {
4822 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4823 } else {
4824 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4825 // in the future without user intervention.
4826 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004827
Stuart Scotte3e314d2015-04-20 14:07:45 -07004828 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4829 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004830 }
4831 }
4832 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004833
4834 @VisibleForTesting
4835 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
4836 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
4837 return new NetworkMonitor(context, handler, nai, defaultRequest);
4838 }
4839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840}