blob: d95b2337b305a949178183f3dad6f90543db0d9f [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;
50import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070051import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070052import android.net.INetworkPolicyListener;
53import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070054import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080055import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070056import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070057import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070058import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070059import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070060import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070062import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070063import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070064import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070065import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070066import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070067import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070068import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040069import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070070import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040071import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040072import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070074import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040075import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070077import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070078import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070079import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Looper;
81import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070082import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070083import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070084import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070085import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070086import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070087import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070089import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040090import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070092import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070093import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070094import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070095import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070096import android.util.LocalLog;
97import android.util.LocalLog.ReadOnlyLocalLog;
98import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080099import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700100import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500101import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700102import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700103import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400106import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400107import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700108import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700109import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700110import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700111import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800112import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700113import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700114import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700115import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700116import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700117import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700118import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400119import com.android.server.connectivity.DataConnectionStats;
Erik Kline379747a2015-06-05 17:47:34 +0900120import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900121import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700122import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400123import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400124import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700125import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800126import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700127import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700128import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700129import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700130import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700131import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700132
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700133import org.xmlpull.v1.XmlPullParser;
134import org.xmlpull.v1.XmlPullParserException;
135
136import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700138import java.io.FileNotFoundException;
139import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700140import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700142import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700143import java.net.InetAddress;
144import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700145import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700146import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700147import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700148import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700149import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700150import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500151import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700152import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700153import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700154import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700155import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
157/**
158 * @hide
159 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800160public class ConnectivityService extends IConnectivityManager.Stub
161 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700162 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700164 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700165 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Jake Hamby786e71a2014-02-06 14:43:50 -0800167 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700168
Jeff Sharkey899223b2012-08-04 15:24:58 -0700169 // TODO: create better separation between radio types and network types
170
Robert Greenwalt42acef32009-08-12 16:08:25 -0700171 // how long to wait before switching back to a radio's default network
172 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
173 // system property that can override the above value
174 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
175 "android.telephony.apn-restore";
176
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900177 // How long to wait before putting up a "This network doesn't have an Internet connection,
178 // connect anyway?" dialog after the user selects a network that doesn't validate.
179 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
180
Jeremy Joslin79294842014-12-03 17:15:28 -0800181 // How long to delay to removal of a pending intent based request.
182 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
183 private final int mReleasePendingIntentDelayMs;
184
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800185 private Tethering mTethering;
186
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700187 private final PermissionMonitor mPermissionMonitor;
188
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700189 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700190
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700191 @GuardedBy("mVpns")
192 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700193
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700194 private boolean mLockdownEnabled;
195 private LockdownVpnTracker mLockdownTracker;
196
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700197 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
198 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700199 /** Currently active network rules by UID. */
200 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700201 /** Set of ifaces that are costly. */
202 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700203
Erik Klineda4bfa82015-04-30 12:58:40 +0900204 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700206 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700207 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800209 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
211 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700212 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700214 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800215 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700216 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700217
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700218 private String mCurrentTcpBufferSizes;
219
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700220 private static final int ENABLED = 1;
221 private static final int DISABLED = 0;
222
Paul Jensenb10e37f2014-11-25 12:33:08 -0500223 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400224 // Tear down networks that have no chance (e.g. even if validated) of becoming
225 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500226 // all networks have been rematched against all NetworkRequests.
227 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400228 // Don't reap networks. This should be passed when some networks have not yet been
229 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500230 DONT_REAP
231 };
232
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700233 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700234 * used internally to change our mobile data enabled flag
235 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700236 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237
238 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700239 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700240 * from one net to another. Clear happens when we get a new
241 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
242 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700243 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700244 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700245
Robert Greenwalt434203a2010-10-11 16:00:27 -0700246 /**
247 * used internally to reload global proxy settings
248 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700249 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700250
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700251 /**
Wink Saville628b0852011-08-04 15:01:58 -0700252 * used internally to send a sticky broadcast delayed.
253 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700254 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700255
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700256 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400257 * PAC manager has received new port.
258 */
259 private static final int EVENT_PROXY_HAS_CHANGED = 16;
260
Robert Greenwalte049c232014-04-11 15:53:27 -0700261 /**
262 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700263 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700264 */
265 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
266
Robert Greenwalt7b816022014-04-18 15:25:25 -0700267 /**
268 * used internally when registering NetworkAgents
269 * obj = Messenger
270 */
271 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
272
Robert Greenwalt9258c642014-03-26 16:47:06 -0700273 /**
274 * used to add a network request
275 * includes a NetworkRequestInfo
276 */
277 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
278
279 /**
280 * indicates a timeout period is over - check if we had a network yet or not
281 * and if not, call the timeout calback (but leave the request live until they
282 * cancel it.
283 * includes a NetworkRequestInfo
284 */
285 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
286
287 /**
288 * used to add a network listener - no request
289 * includes a NetworkRequestInfo
290 */
291 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
292
293 /**
294 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400295 * arg1 = UID of caller
296 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700297 */
298 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
299
Robert Greenwalta67be032014-05-16 15:49:14 -0700300 /**
301 * used internally when registering NetworkFactories
302 * obj = Messenger
303 */
304 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
305
Robert Greenwalt27711812014-06-25 16:45:57 -0700306 /**
307 * used internally to expire a wakelock when transitioning
308 * from one net to another. Expire happens when we fail to find
309 * a new network (typically after 1 minute) -
310 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
311 * a replacement network.
312 */
313 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
314
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700315 /**
316 * Used internally to indicate the system is ready.
317 */
318 private static final int EVENT_SYSTEM_READY = 25;
319
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800320 /**
321 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400322 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800323 */
324 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
325
326 /**
327 * used to remove a pending intent and its associated network request.
328 * arg1 = UID of caller
329 * obj = PendingIntent
330 */
331 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
332
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900333 /**
334 * used to specify whether a network should be used even if unvalidated.
335 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
336 * arg2 = whether to remember this choice in the future (1 or 0)
337 * obj = network
338 */
339 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
340
341 /**
342 * used to ask the user to confirm a connection to an unvalidated network.
343 * obj = network
344 */
345 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700346
Erik Klineda4bfa82015-04-30 12:58:40 +0900347 /**
348 * used internally to (re)configure mobile data always-on settings.
349 */
350 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
351
Paul Jensen694f2b82015-06-17 14:15:39 -0400352 /**
353 * used to add a network listener with a pending intent
354 * obj = NetworkRequestInfo
355 */
356 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
357
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700358 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700359 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700360 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700361 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700362
Mike Lockwood0f79b542009-08-14 14:18:49 -0400363 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800364 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400365
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700366 private PowerManager.WakeLock mNetTransitionWakeLock;
367 private String mNetTransitionWakeLockCausedBy = "";
368 private int mNetTransitionWakeLockSerialNumber;
369 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800370 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700371
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700372 private InetAddress mDefaultDns;
373
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700374 // used in DBG mode to track inet condition reports
375 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
376 private ArrayList mInetLog;
377
Robert Greenwalt434203a2010-10-11 16:00:27 -0700378 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400379 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700380 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700381 private boolean mDefaultProxyDisabled = false;
382
Robert Greenwalt434203a2010-10-11 16:00:27 -0700383 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400384 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700385
Jason Monk602b2322013-07-03 17:04:33 -0400386 private PacManager mPacManager = null;
387
Erik Klineda4bfa82015-04-30 12:58:40 +0900388 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700389
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400390 private UserManager mUserManager;
391
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700392 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700393 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700394
Robert Greenwalt50393202011-06-21 17:26:14 -0700395 // the set of network types that can only be enabled by system/sig apps
396 List mProtectedNetworks;
397
John Spurlockbf991a82013-06-24 14:20:23 -0400398 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700399
Wink Savilleab9321d2013-06-29 21:10:57 -0700400 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400401
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700402 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
403 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700404 private final static int MAX_NET_ID = 65535;
405 private int mNextNetId = MIN_NET_ID;
406
Robert Greenwalt34524f02014-05-18 16:22:10 -0700407 // sequence number of NetworkRequests
408 private int mNextNetworkRequestId = 1;
409
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700410 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
411 private static final int MAX_VALIDATION_LOGS = 10;
412 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
413 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
414
415 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
416 synchronized(mValidationLogs) {
417 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
418 mValidationLogs.removeLast();
419 }
420 mValidationLogs.addFirst(new Pair(network, log));
421 }
422 }
423
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700424 /**
425 * Implements support for the legacy "one network per network type" model.
426 *
427 * We used to have a static array of NetworkStateTrackers, one for each
428 * network type, but that doesn't work any more now that we can have,
429 * for example, more that one wifi network. This class stores all the
430 * NetworkAgentInfo objects that support a given type, but the legacy
431 * API will only see the first one.
432 *
433 * It serves two main purposes:
434 *
435 * 1. Provide information about "the network for a given type" (since this
436 * API only supports one).
437 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
438 * the first network for a given type changes, or if the default network
439 * changes.
440 */
441 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900442
443 private static final boolean DBG = true;
444 private static final boolean VDBG = false;
445 private static final String TAG = "CSLegacyTypeTracker";
446
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700447 /**
448 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
449 * Each list holds references to all NetworkAgentInfos that are used to
450 * satisfy requests for that network type.
451 *
452 * This array is built out at startup such that an unsupported network
453 * doesn't get an ArrayList instance, making this a tristate:
454 * unsupported, supported but not active and active.
455 *
456 * The actual lists are populated when we scan the network types that
457 * are supported on this device.
458 */
459 private ArrayList<NetworkAgentInfo> mTypeLists[];
460
461 public LegacyTypeTracker() {
462 mTypeLists = (ArrayList<NetworkAgentInfo>[])
463 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
464 }
465
466 public void addSupportedType(int type) {
467 if (mTypeLists[type] != null) {
468 throw new IllegalStateException(
469 "legacy list for type " + type + "already initialized");
470 }
471 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
472 }
473
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700474 public boolean isTypeSupported(int type) {
475 return isNetworkTypeValid(type) && mTypeLists[type] != null;
476 }
477
478 public NetworkAgentInfo getNetworkForType(int type) {
479 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
480 return mTypeLists[type].get(0);
481 } else {
482 return null;
483 }
484 }
485
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900486 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type,
487 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900488 if (DBG) {
489 log("Sending " + (connected ? "connected" : "disconnected") +
490 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900491 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900492 }
493 }
494
495 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700496 public void add(int type, NetworkAgentInfo nai) {
497 if (!isTypeSupported(type)) {
498 return; // Invalid network type.
499 }
500 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
501
502 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
503 if (list.contains(nai)) {
504 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
505 return;
506 }
507
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900508 list.add(nai);
509
510 // 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 +0900511 final boolean isDefaultNetwork = isDefaultNetwork(nai);
512 if (list.size() == 1 || isDefaultNetwork) {
513 maybeLogBroadcast(nai, true, type, isDefaultNetwork);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700514 sendLegacyNetworkBroadcast(nai, true, type);
515 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700516 }
517
Lorenzo Colittia793a672014-07-31 23:20:17 +0900518 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900519 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900520 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
521 if (list == null || list.isEmpty()) {
522 return;
523 }
524
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900525 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900526
527 if (!list.remove(nai)) {
528 return;
529 }
530
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900531 if (wasFirstNetwork || wasDefault) {
532 maybeLogBroadcast(nai, false, type, wasDefault);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900533 sendLegacyNetworkBroadcast(nai, false, type);
534 }
535
536 if (!list.isEmpty() && wasFirstNetwork) {
537 if (DBG) log("Other network available for type " + type +
538 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900539 final NetworkAgentInfo replacement = list.get(0);
540 maybeLogBroadcast(replacement, false, type, isDefaultNetwork(replacement));
541 sendLegacyNetworkBroadcast(replacement, false, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900542 }
543 }
544
545 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900546 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
547 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700548 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900549 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700550 }
551 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700552
Lorenzo Colittia793a672014-07-31 23:20:17 +0900553 private String naiToString(NetworkAgentInfo nai) {
554 String name = (nai != null) ? nai.name() : "null";
555 String state = (nai.networkInfo != null) ?
556 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
557 "???/???";
558 return name + " " + state;
559 }
560
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700561 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900562 pw.println("mLegacyTypeTracker:");
563 pw.increaseIndent();
564 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700565 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900566 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700567 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900568 pw.println();
569 pw.println("Current state:");
570 pw.increaseIndent();
571 for (int type = 0; type < mTypeLists.length; type++) {
572 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
573 for (NetworkAgentInfo nai : mTypeLists[type]) {
574 pw.println(type + " " + naiToString(nai));
575 }
576 }
577 pw.decreaseIndent();
578 pw.decreaseIndent();
579 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700580 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900581
582 // This class needs its own log method because it has a different TAG.
583 private void log(String s) {
584 Slog.d(TAG, s);
585 }
586
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700587 }
588 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
589
Jeff Sharkey899223b2012-08-04 15:24:58 -0700590 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700591 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800592 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800593
Erik Klineda4bfa82015-04-30 12:58:40 +0900594 mDefaultRequest = createInternetRequestForTransport(-1);
595 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
596 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
597
598 mDefaultMobileDataRequest = createInternetRequestForTransport(
599 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700600
Wink Savillebb08caf2010-09-02 19:23:52 -0700601 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
602 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700603 mHandler = new InternalHandler(handlerThread.getLooper());
604 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700605
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800606 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800607 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
608 String id = Settings.Secure.getString(context.getContentResolver(),
609 Settings.Secure.ANDROID_ID);
610 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700611 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800612 SystemProperties.set("net.hostname", name);
613 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800614 }
615
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700616 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700617 String dns = Settings.Global.getString(context.getContentResolver(),
618 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700619 if (dns == null || dns.length() == 0) {
620 dns = context.getResources().getString(
621 com.android.internal.R.string.config_default_dns_server);
622 }
623 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800624 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
625 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800626 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700627 }
628
Jeremy Joslin79294842014-12-03 17:15:28 -0800629 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
630 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
631
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700632 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700633 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800634 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700635 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700636 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700637 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700638
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700639 try {
640 mPolicyManager.registerListener(mPolicyListener);
641 } catch (RemoteException e) {
642 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700643 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700644 }
645
646 final PowerManager powerManager = (PowerManager) context.getSystemService(
647 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700648 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
649 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
650 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800651 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700652
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700653 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700654
Wink Saville51f456f2013-04-23 14:26:51 -0700655 // TODO: What is the "correct" way to do determine if this is a wifi only device?
656 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
657 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700658 String[] naStrings = context.getResources().getStringArray(
659 com.android.internal.R.array.networkAttributes);
660 for (String naString : naStrings) {
661 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700662 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700663 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700664 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800665 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700666 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700667 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700668 }
Wink Saville51f456f2013-04-23 14:26:51 -0700669 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
670 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
671 n.type);
672 continue;
673 }
Wink Saville975c8482011-04-07 14:23:45 -0700674 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800675 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700676 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700677 continue;
678 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700679 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700680
Wink Saville975c8482011-04-07 14:23:45 -0700681 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700682 mNetworksDefined++;
683 } catch(Exception e) {
684 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700685 }
686 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700687
688 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
689 if (mNetConfigs[TYPE_VPN] == null) {
690 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
691 // don't need to add TYPE_VPN to mNetConfigs.
692 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
693 mNetworksDefined++; // used only in the log() statement below.
694 }
695
Wink Saville5e56bc52013-07-29 15:00:57 -0700696 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700697
Robert Greenwalt50393202011-06-21 17:26:14 -0700698 mProtectedNetworks = new ArrayList<Integer>();
699 int[] protectedNetworks = context.getResources().getIntArray(
700 com.android.internal.R.array.config_protectedNetworks);
701 for (int p : protectedNetworks) {
702 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
703 mProtectedNetworks.add(p);
704 } else {
705 if (DBG) loge("Ignoring protectedNetwork " + p);
706 }
707 }
708
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700709 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
710 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700711
Robert Greenwaltfab501672014-07-23 11:44:01 -0700712 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800713
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700714 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
715
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700716 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700717 IntentFilter intentFilter = new IntentFilter();
718 intentFilter.addAction(Intent.ACTION_USER_STARTING);
719 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
720 mContext.registerReceiverAsUser(
721 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900722
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700723 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700724 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700725 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700726 } catch (RemoteException e) {
727 loge("Error registering observer :" + e);
728 }
729
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700730 if (DBG) {
731 mInetLog = new ArrayList();
732 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700733
Erik Klineda4bfa82015-04-30 12:58:40 +0900734 mSettingsObserver = new SettingsObserver(mContext, mHandler);
735 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800736
John Spurlockbf991a82013-06-24 14:20:23 -0400737 mDataConnectionStats = new DataConnectionStats(mContext);
738 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400739
Jason Monkdecd2952013-10-10 14:02:51 -0400740 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700741
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400742 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700744
Erik Klineda4bfa82015-04-30 12:58:40 +0900745 private NetworkRequest createInternetRequestForTransport(int transportType) {
746 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900747 netCap.addCapability(NET_CAPABILITY_INTERNET);
748 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900749 if (transportType > -1) {
750 netCap.addTransportType(transportType);
751 }
752 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
753 }
754
755 private void handleMobileDataAlwaysOn() {
756 final boolean enable = (Settings.Global.getInt(
757 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
758 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
759 if (enable == isEnabled) {
760 return; // Nothing to do.
761 }
762
763 if (enable) {
764 handleRegisterNetworkRequest(new NetworkRequestInfo(
765 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
766 } else {
767 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
768 }
769 }
770
771 private void registerSettingsCallbacks() {
772 // Watch for global HTTP proxy changes.
773 mSettingsObserver.observe(
774 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
775 EVENT_APPLY_GLOBAL_HTTP_PROXY);
776
777 // Watch for whether or not to keep mobile data always on.
778 mSettingsObserver.observe(
779 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
780 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
781 }
782
Robert Greenwalt34524f02014-05-18 16:22:10 -0700783 private synchronized int nextNetworkRequestId() {
784 return mNextNetworkRequestId++;
785 }
786
Paul Jensen67b0b072015-06-10 11:22:17 -0400787 @VisibleForTesting
788 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400789 synchronized (mNetworkForNetId) {
790 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
791 int netId = mNextNetId;
792 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
793 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500794 if (!mNetIdInUse.get(netId)) {
795 mNetIdInUse.put(netId, true);
796 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400797 }
798 }
799 }
800 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700801 }
802
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800803 private NetworkState getFilteredNetworkState(int networkType, int uid) {
804 NetworkInfo info = null;
805 LinkProperties lp = null;
806 NetworkCapabilities nc = null;
807 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800808 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800809
810 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
811 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
812 if (nai != null) {
813 synchronized (nai) {
814 info = new NetworkInfo(nai.networkInfo);
815 lp = new LinkProperties(nai.linkProperties);
816 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400817 // Network objects are outwardly immutable so there is no point to duplicating.
818 // Duplicating also precludes sharing socket factories and connection pools.
819 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800820 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800821 }
822 info.setType(networkType);
823 } else {
824 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
825 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
826 info.setIsAvailable(true);
827 lp = new LinkProperties();
828 nc = new NetworkCapabilities();
829 network = null;
830 }
831 info = getFilteredNetworkInfo(info, lp, uid);
832 }
833
Jeff Sharkey32566012014-12-02 18:30:14 -0800834 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400835 }
836
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800837 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
838 if (network == null) {
839 return null;
840 }
841 synchronized (mNetworkForNetId) {
842 return mNetworkForNetId.get(network.netId);
843 }
844 };
845
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900846 private Network[] getVpnUnderlyingNetworks(int uid) {
847 if (!mLockdownEnabled) {
848 int user = UserHandle.getUserId(uid);
849 synchronized (mVpns) {
850 Vpn vpn = mVpns.get(user);
851 if (vpn != null && vpn.appliesToUid(uid)) {
852 return vpn.getUnderlyingNetworks();
853 }
854 }
855 }
856 return null;
857 }
858
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800859 private NetworkState getUnfilteredActiveNetworkState(int uid) {
860 NetworkInfo info = null;
861 LinkProperties lp = null;
862 NetworkCapabilities nc = null;
863 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800864 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800865
Paul Jensen85cf78e2015-06-25 13:25:07 -0400866 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800867
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900868 final Network[] networks = getVpnUnderlyingNetworks(uid);
869 if (networks != null) {
870 // getUnderlyingNetworks() returns:
871 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
872 // empty array => the VPN explicitly said "no default network".
873 // non-empty array => the VPN specified one or more default networks; we use the
874 // first one.
875 if (networks.length > 0) {
876 nai = getNetworkAgentInfoForNetwork(networks[0]);
877 } else {
878 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800879 }
880 }
881
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800882 if (nai != null) {
883 synchronized (nai) {
884 info = new NetworkInfo(nai.networkInfo);
885 lp = new LinkProperties(nai.linkProperties);
886 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400887 // Network objects are outwardly immutable so there is no point to duplicating.
888 // Duplicating also precludes sharing socket factories and connection pools.
889 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800890 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800891 }
892 }
893
Jeff Sharkey32566012014-12-02 18:30:14 -0800894 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400895 }
896
897 /**
898 * Check if UID should be blocked from using the network with the given LinkProperties.
899 */
900 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700901 final boolean networkCostly;
902 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700903
Robert Greenwalt12e67352014-05-13 21:41:06 -0700904 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700905 synchronized (mRulesLock) {
906 networkCostly = mMeteredIfaces.contains(iface);
907 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700908 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700909
Amith Yamasani15e472352015-04-24 19:06:07 -0700910 if ((uidRules & RULE_REJECT_ALL) != 0
911 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700912 return true;
913 }
914
915 // no restrictive rules; network is visible
916 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700917 }
918
919 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700920 * Return a filtered {@link NetworkInfo}, potentially marked
921 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800922 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700923 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800924 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
925 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400926 // network is blocked; clone and override state
927 info = new NetworkInfo(info);
928 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900929 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900930 log("returning Blocked NetworkInfo for ifname=" +
931 lp.getInterfaceName() + ", uid=" + uid);
932 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700933 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700935 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900936 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700937 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700938 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700939 }
940
941 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 * Return NetworkInfo for the active (i.e., connected) network interface.
943 * It is assumed that at most one network is active at a time. If more
944 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700945 * @return the info for the active network, or {@code null} if none is
946 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700948 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700950 enforceAccessPermission();
951 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800952 NetworkState state = getUnfilteredActiveNetworkState(uid);
953 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
955
Paul Jensen31a94f42015-02-13 14:18:39 -0500956 @Override
957 public Network getActiveNetwork() {
958 enforceAccessPermission();
959 final int uid = Binder.getCallingUid();
960 final int user = UserHandle.getUserId(uid);
961 int vpnNetId = NETID_UNSET;
962 synchronized (mVpns) {
963 final Vpn vpn = mVpns.get(user);
964 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
965 }
966 NetworkAgentInfo nai;
967 if (vpnNetId != NETID_UNSET) {
968 synchronized (mNetworkForNetId) {
969 nai = mNetworkForNetId.get(vpnNetId);
970 }
971 if (nai != null) return nai.network;
972 }
973 nai = getDefaultNetwork();
974 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
975 return nai != null ? nai.network : null;
976 }
977
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700978 public NetworkInfo getActiveNetworkInfoUnfiltered() {
979 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800980 final int uid = Binder.getCallingUid();
981 NetworkState state = getUnfilteredActiveNetworkState(uid);
982 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700983 }
984
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700985 @Override
986 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
987 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800988 NetworkState state = getUnfilteredActiveNetworkState(uid);
989 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700990 }
991
992 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 public NetworkInfo getNetworkInfo(int networkType) {
994 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700995 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900996 if (getVpnUnderlyingNetworks(uid) != null) {
997 // A VPN is active, so we may need to return one of its underlying networks. This
998 // information is not available in LegacyTypeTracker, so we have to get it from
999 // getUnfilteredActiveNetworkState.
1000 NetworkState state = getUnfilteredActiveNetworkState(uid);
1001 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1002 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1003 }
1004 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001005 NetworkState state = getFilteredNetworkState(networkType, uid);
1006 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001009 @Override
1010 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1011 enforceAccessPermission();
1012 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001013 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001014 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1015 if (nai != null) {
1016 synchronized (nai) {
1017 info = new NetworkInfo(nai.networkInfo);
1018 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 }
1020 }
1021 return info;
1022 }
1023
1024 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 public NetworkInfo[] getAllNetworkInfo() {
1026 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001027 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001028 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1029 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001030 NetworkInfo info = getNetworkInfo(networkType);
1031 if (info != null) {
1032 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001035 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 }
1037
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001038 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001039 public Network getNetworkForType(int networkType) {
1040 enforceAccessPermission();
1041 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001042 NetworkState state = getFilteredNetworkState(networkType, uid);
1043 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1044 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001045 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001046 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001047 }
1048
1049 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001050 public Network[] getAllNetworks() {
1051 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001052 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001053 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001054 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001055 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001056 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001057 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001058 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001059 }
1060
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001061 @Override
1062 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1063 // The basic principle is: if an app's traffic could possibly go over a
1064 // network, without the app doing anything multinetwork-specific,
1065 // (hence, by "default"), then include that network's capabilities in
1066 // the array.
1067 //
1068 // In the normal case, app traffic only goes over the system's default
1069 // network connection, so that's the only network returned.
1070 //
1071 // With a VPN in force, some app traffic may go into the VPN, and thus
1072 // over whatever underlying networks the VPN specifies, while other app
1073 // traffic may go over the system default network (e.g.: a split-tunnel
1074 // VPN, or an app disallowed by the VPN), so the set of networks
1075 // returned includes the VPN's underlying networks and the system
1076 // default.
1077 enforceAccessPermission();
1078
1079 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1080
1081 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001082 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001083 if (nc != null) {
1084 result.put(nai.network, nc);
1085 }
1086
1087 if (!mLockdownEnabled) {
1088 synchronized (mVpns) {
1089 Vpn vpn = mVpns.get(userId);
1090 if (vpn != null) {
1091 Network[] networks = vpn.getUnderlyingNetworks();
1092 if (networks != null) {
1093 for (Network network : networks) {
1094 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001095 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001096 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001097 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001098 }
1099 }
1100 }
1101 }
1102 }
1103 }
1104
1105 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1106 out = result.values().toArray(out);
1107 return out;
1108 }
1109
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001110 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001111 public boolean isNetworkSupported(int networkType) {
1112 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001113 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001114 }
1115
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001116 /**
1117 * Return LinkProperties for the active (i.e., connected) default
1118 * network interface. It is assumed that at most one default network
1119 * is active at a time. If more than one is active, it is indeterminate
1120 * which will be returned.
1121 * @return the ip properties for the active network, or {@code null} if
1122 * none is active
1123 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001124 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001125 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001126 enforceAccessPermission();
1127 final int uid = Binder.getCallingUid();
1128 NetworkState state = getUnfilteredActiveNetworkState(uid);
1129 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001130 }
1131
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001132 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001133 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001134 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001135 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1136 if (nai != null) {
1137 synchronized (nai) {
1138 return new LinkProperties(nai.linkProperties);
1139 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001140 }
1141 return null;
1142 }
1143
Robert Greenwalt12e67352014-05-13 21:41:06 -07001144 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001145 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001146 public LinkProperties getLinkProperties(Network network) {
1147 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001148 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001149 if (nai != null) {
1150 synchronized (nai) {
1151 return new LinkProperties(nai.linkProperties);
1152 }
1153 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001154 return null;
1155 }
1156
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001157 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001158 if (nai != null) {
1159 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001160 if (nai.networkCapabilities != null) {
1161 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001162 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001163 }
1164 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001165 return null;
1166 }
1167
1168 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001169 public NetworkCapabilities getNetworkCapabilities(Network network) {
1170 enforceAccessPermission();
1171 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1172 }
1173
1174 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001175 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001176 // Require internal since we're handing out IMSI details
1177 enforceConnectivityInternalPermission();
1178
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001179 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001180 for (Network network : getAllNetworks()) {
1181 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1182 if (nai != null) {
1183 synchronized (nai) {
1184 final String subscriberId = (nai.networkMisc != null)
1185 ? nai.networkMisc.subscriberId : null;
1186 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1187 nai.networkCapabilities, network, subscriberId, null));
1188 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001189 }
1190 }
1191 return result.toArray(new NetworkState[result.size()]);
1192 }
1193
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001194 @Override
1195 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1196 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001197 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001198 final long token = Binder.clearCallingIdentity();
1199 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001200 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1201 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001202 try {
1203 return mPolicyManager.getNetworkQuotaInfo(state);
1204 } catch (RemoteException e) {
1205 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001206 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001207 return null;
1208 } finally {
1209 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001210 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001211 }
1212
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001213 @Override
1214 public boolean isActiveNetworkMetered() {
1215 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001216 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001217 final long token = Binder.clearCallingIdentity();
1218 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001219 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001220 } finally {
1221 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001222 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001223 }
1224
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001225 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1226 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1227 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001228 try {
1229 return mPolicyManager.isNetworkMetered(state);
1230 } catch (RemoteException e) {
1231 }
1232 }
1233 return false;
1234 }
1235
Jeff Sharkey216c1812012-08-05 14:29:23 -07001236 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1237 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001238 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001239 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001240 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001241 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001242 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001243
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001244 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 * Ensure that a network route exists to deliver traffic to the specified
1246 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001247 * @param networkType the type of the network over which traffic to the
1248 * specified host is to be routed
1249 * @param hostAddress the IP address of the host to which the route is
1250 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 * @return {@code true} on success, {@code false} on failure
1252 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001253 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001255 if (mProtectedNetworks.contains(networkType)) {
1256 enforceConnectivityInternalPermission();
1257 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001258
Chad Brubakerc0234532014-02-14 13:24:29 -08001259 InetAddress addr;
1260 try {
1261 addr = InetAddress.getByAddress(hostAddress);
1262 } catch (UnknownHostException e) {
1263 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1264 return false;
1265 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001268 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 return false;
1270 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001271
1272 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1273 if (nai == null) {
1274 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1275 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1276 } else {
1277 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1278 }
1279 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001280 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001281
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001282 DetailedState netState;
1283 synchronized (nai) {
1284 netState = nai.networkInfo.getDetailedState();
1285 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001286
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001287 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001288 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001289 log("requestRouteToHostAddress on down network "
1290 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001291 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001292 }
1293 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001295
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001296 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001297 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001298 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001299 LinkProperties lp;
1300 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001301 synchronized (nai) {
1302 lp = nai.linkProperties;
1303 netId = nai.network.netId;
1304 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001305 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001306 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1307 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001308 } finally {
1309 Binder.restoreCallingIdentity(token);
1310 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001311 }
1312
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001313 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001314 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001315 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001316 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001317 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001318 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001319 if (bestRoute.getGateway().equals(addr)) {
1320 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001321 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001322 } else {
1323 // if we will connect to this through another route, add a direct route
1324 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001325 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001326 }
1327 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001328 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001329 try {
1330 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1331 } catch (Exception e) {
1332 // never crash - catch them all
1333 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001334 return false;
1335 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001336 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 }
1338
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001339 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1340 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001341 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001342 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001343 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001344 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001345 }
1346
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001347 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001348 // skip update when we've already applied rules
1349 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1350 if (oldRules == uidRules) return;
1351
1352 mUidRules.put(uid, uidRules);
1353 }
1354
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001355 // TODO: notify UID when it has requested targeted updates
1356 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001357
1358 @Override
1359 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001360 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001361 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001362 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001363 }
1364
1365 synchronized (mRulesLock) {
1366 mMeteredIfaces.clear();
1367 for (String iface : meteredIfaces) {
1368 mMeteredIfaces.add(iface);
1369 }
1370 }
1371 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001372
1373 @Override
1374 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1375 // caller is NPMS, since we only register with them
1376 if (LOGD_RULES) {
1377 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1378 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001379 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001380 };
1381
Robin Lee3b3dd942015-05-12 18:14:58 +01001382 /**
1383 * Require that the caller is either in the same user or has appropriate permission to interact
1384 * across users.
1385 *
1386 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1387 */
1388 private void enforceCrossUserPermission(int userId) {
1389 if (userId == UserHandle.getCallingUserId()) {
1390 // Not a cross-user call.
1391 return;
1392 }
1393 mContext.enforceCallingOrSelfPermission(
1394 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1395 "ConnectivityService");
1396 }
1397
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001398 private void enforceInternetPermission() {
1399 mContext.enforceCallingOrSelfPermission(
1400 android.Manifest.permission.INTERNET,
1401 "ConnectivityService");
1402 }
1403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001405 mContext.enforceCallingOrSelfPermission(
1406 android.Manifest.permission.ACCESS_NETWORK_STATE,
1407 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
1409
1410 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001411 mContext.enforceCallingOrSelfPermission(
1412 android.Manifest.permission.CHANGE_NETWORK_STATE,
1413 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001416 private void enforceTetherAccessPermission() {
1417 mContext.enforceCallingOrSelfPermission(
1418 android.Manifest.permission.ACCESS_NETWORK_STATE,
1419 "ConnectivityService");
1420 }
1421
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001422 private void enforceConnectivityInternalPermission() {
1423 mContext.enforceCallingOrSelfPermission(
1424 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1425 "ConnectivityService");
1426 }
1427
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001428 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001429 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001430 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001431 }
1432
1433 private void sendInetConditionBroadcast(NetworkInfo info) {
1434 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1435 }
1436
Wink Saville628b0852011-08-04 15:01:58 -07001437 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001438 if (mLockdownTracker != null) {
1439 info = mLockdownTracker.augmentNetworkInfo(info);
1440 }
1441
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001442 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001443 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001444 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 if (info.isFailover()) {
1446 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1447 info.setFailover(false);
1448 }
1449 if (info.getReason() != null) {
1450 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1451 }
1452 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001453 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1454 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001456 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001457 return intent;
1458 }
1459
1460 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1461 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1462 }
1463
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001464 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001465 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1466 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1467 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001468 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001469 final long ident = Binder.clearCallingIdentity();
1470 try {
1471 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1472 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1473 } finally {
1474 Binder.restoreCallingIdentity(ident);
1475 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001476 }
1477
Mike Lockwood0f79b542009-08-14 14:18:49 -04001478 private void sendStickyBroadcast(Intent intent) {
1479 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001480 if (!mSystemReady) {
1481 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001482 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001483 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001484 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001485 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001486 }
1487
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001488 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001489 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1490 final IBatteryStats bs = BatteryStatsService.getService();
1491 try {
1492 NetworkInfo ni = intent.getParcelableExtra(
1493 ConnectivityManager.EXTRA_NETWORK_INFO);
1494 bs.noteConnectivityChanged(intent.getIntExtra(
1495 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1496 ni != null ? ni.getState().toString() : "?");
1497 } catch (RemoteException e) {
1498 }
1499 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001500 try {
1501 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1502 } finally {
1503 Binder.restoreCallingIdentity(ident);
1504 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001505 }
1506 }
1507
1508 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001509 loadGlobalProxy();
1510
Mike Lockwood0f79b542009-08-14 14:18:49 -04001511 synchronized(this) {
1512 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001513 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001514 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001515 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001516 }
1517 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001518 // load the global proxy at startup
1519 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001520
1521 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1522 // for user to unlock device.
1523 if (!updateLockdownVpn()) {
1524 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1525 mContext.registerReceiver(mUserPresentReceiver, filter);
1526 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001527
Erik Klineda4bfa82015-04-30 12:58:40 +09001528 // Configure whether mobile data is always on.
1529 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1530
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001531 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001532
1533 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
1535
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001536 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1537 @Override
1538 public void onReceive(Context context, Intent intent) {
1539 // Try creating lockdown tracker, since user present usually means
1540 // unlocked keystore.
1541 if (updateLockdownVpn()) {
1542 mContext.unregisterReceiver(this);
1543 }
1544 }
1545 };
1546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001548 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001549 *
1550 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001551 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001552 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001553 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1554 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001555
1556 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001557 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001558
Robert Greenwalt7b816022014-04-18 15:25:25 -07001559 if (networkAgent.networkCapabilities.hasTransport(
1560 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001561 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1562 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001563 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001564 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001565 } else if (networkAgent.networkCapabilities.hasTransport(
1566 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001567 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1568 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001569 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001570 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001571 } else {
1572 // do not track any other networks
1573 timeout = 0;
1574 }
1575
Robert Greenwalt7b816022014-04-18 15:25:25 -07001576 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001577 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001578 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001579 } catch (Exception e) {
1580 // You shall not crash!
1581 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001582 }
1583 }
1584 }
1585
1586 /**
1587 * Remove data activity tracking when network disconnects.
1588 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001589 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1590 final String iface = networkAgent.linkProperties.getInterfaceName();
1591 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001592
Robert Greenwalt7b816022014-04-18 15:25:25 -07001593 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1594 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001595 try {
1596 // the call fails silently if no idletimer setup for this interface
1597 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001598 } catch (Exception e) {
1599 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001600 }
1601 }
1602 }
1603
1604 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001605 * Reads the network specific MTU size from reources.
1606 * and set it on it's iface.
1607 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001608 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1609 final String iface = newLp.getInterfaceName();
1610 final int mtu = newLp.getMtu();
1611 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1612 if (VDBG) log("identical MTU - not setting");
1613 return;
1614 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001615
Robert Greenwalt43074032014-08-15 17:53:05 -07001616 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001617 loge("Unexpected mtu value: " + mtu + ", " + iface);
1618 return;
1619 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001620
w1997615afd812014-08-05 15:18:11 -07001621 // Cannot set MTU without interface name
1622 if (TextUtils.isEmpty(iface)) {
1623 loge("Setting MTU size with null iface.");
1624 return;
1625 }
1626
Robert Greenwalt7b816022014-04-18 15:25:25 -07001627 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001628 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001629 mNetd.setMtu(iface, mtu);
1630 } catch (Exception e) {
1631 Slog.e(TAG, "exception in setMtu()" + e);
1632 }
1633 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001634
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001635 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001636 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1637
1638 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001639 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001640 protected int getDefaultTcpRwnd() {
1641 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1642 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001643
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001644 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1645 if (isDefaultNetwork(nai) == false) {
1646 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001647 }
1648
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001649 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1650 String[] values = null;
1651 if (tcpBufferSizes != null) {
1652 values = tcpBufferSizes.split(",");
1653 }
1654
1655 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001656 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001657 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1658 values = tcpBufferSizes.split(",");
1659 }
1660
1661 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1662
1663 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001664 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001665
1666 final String prefix = "/sys/kernel/ipv4/tcp_";
1667 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1668 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1669 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1670 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1671 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1672 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1673 mCurrentTcpBufferSizes = tcpBufferSizes;
1674 } catch (IOException e) {
1675 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001676 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001677
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001678 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001679 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001680 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1681 if (rwndValue != 0) {
1682 SystemProperties.set(sysctlKey, rwndValue.toString());
1683 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001684 }
1685
Mattias Falk8b47b362011-08-23 14:15:13 +02001686 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001687 /*
1688 * Tell the VMs to toss their DNS caches
1689 */
1690 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1691 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001692 /*
1693 * Connectivity events can happen before boot has completed ...
1694 */
1695 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001696 final long ident = Binder.clearCallingIdentity();
1697 try {
1698 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1699 } finally {
1700 Binder.restoreCallingIdentity(ident);
1701 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001702 }
1703
Robert Greenwalt562cc542014-05-15 18:07:26 -07001704 @Override
1705 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001706 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1707 NETWORK_RESTORE_DELAY_PROP_NAME);
1708 if(restoreDefaultNetworkDelayStr != null &&
1709 restoreDefaultNetworkDelayStr.length() != 0) {
1710 try {
1711 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1712 } catch (NumberFormatException e) {
1713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001715 // if the system property isn't set, use the value for the apn type
1716 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1717
1718 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1719 (mNetConfigs[networkType] != null)) {
1720 ret = mNetConfigs[networkType].restoreTime;
1721 }
1722 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 }
1724
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001725 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001726 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001727 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001728 }
1729 return false;
1730 }
1731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001733 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1734 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001735 if (mContext.checkCallingOrSelfPermission(
1736 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001738 pw.println("Permission Denial: can't dump ConnectivityService " +
1739 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1740 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 return;
1742 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001743
Erik Kline379747a2015-06-05 17:47:34 +09001744 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001745 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001746 final long DIAG_TIME_MS = 5000;
1747 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1748 // Start gathering diagnostic information.
1749 netDiags.add(new NetworkDiagnostics(
1750 nai.network,
1751 new LinkProperties(nai.linkProperties),
1752 DIAG_TIME_MS));
1753 }
1754
1755 for (NetworkDiagnostics netDiag : netDiags) {
1756 pw.println();
1757 netDiag.waitForMeasurements();
1758 netDiag.dump(pw);
1759 }
1760
1761 return;
1762 }
1763
Lorenzo Colittie3805462015-06-03 11:18:24 +09001764 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001765 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001766 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001767 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001768 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001769 pw.println();
1770
Paul Jensen85cf78e2015-06-25 13:25:07 -04001771 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001772 pw.print("Active default network: ");
1773 if (defaultNai == null) {
1774 pw.println("none");
1775 } else {
1776 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001778 pw.println();
1779
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001780 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001781 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001782 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1783 pw.println(nai.toString());
1784 pw.increaseIndent();
1785 pw.println("Requests:");
1786 pw.increaseIndent();
1787 for (int i = 0; i < nai.networkRequests.size(); i++) {
1788 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001789 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001790 pw.decreaseIndent();
1791 pw.println("Lingered:");
1792 pw.increaseIndent();
1793 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1794 pw.decreaseIndent();
1795 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001796 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001797 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001798 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001799
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001800 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001801 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001802 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1803 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001804 }
1805 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001806 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001807
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001808 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001809
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001810 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001811 pw.print("mNetTransitionWakeLock: currently " +
1812 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1813 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1814 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1815 } else {
1816 pw.println(", last requested never");
1817 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001818 }
1819 pw.println();
1820
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001821 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001822
Lorenzo Colittie3805462015-06-03 11:18:24 +09001823 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001824 pw.println();
1825 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001826 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001827 for(int i = 0; i < mInetLog.size(); i++) {
1828 pw.println(mInetLog.get(i));
1829 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001830 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001831 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001832
1833 if (argsContain(args, "--short") == false) {
1834 pw.println();
1835 synchronized (mValidationLogs) {
1836 pw.println("mValidationLogs (most recent first):");
1837 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1838 pw.println(p.first);
1839 pw.increaseIndent();
1840 p.second.dump(fd, pw, args);
1841 pw.decreaseIndent();
1842 }
1843 }
1844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001847 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001848 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001849 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001850 if (officialNai != null && officialNai.equals(nai)) return true;
1851 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001852 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001853 " - " + nai);
1854 }
1855 return false;
1856 }
1857
Paul Jensenc8b9a742014-09-30 15:37:41 -04001858 private boolean isRequest(NetworkRequest request) {
1859 return mNetworkRequests.get(request).isRequest;
1860 }
1861
Robert Greenwalt42acef32009-08-12 16:08:25 -07001862 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001863 private class NetworkStateTrackerHandler extends Handler {
1864 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001865 super(looper);
1866 }
1867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 @Override
1869 public void handleMessage(Message msg) {
1870 NetworkInfo info;
1871 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001872 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001873 handleAsyncChannelHalfConnect(msg);
1874 break;
1875 }
1876 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1877 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1878 if (nai != null) nai.asyncChannel.disconnect();
1879 break;
1880 }
1881 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1882 handleAsyncChannelDisconnected(msg);
1883 break;
1884 }
1885 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1886 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1887 if (nai == null) {
1888 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1889 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001890 final NetworkCapabilities networkCapabilities =
1891 (NetworkCapabilities)msg.obj;
1892 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1893 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1894 Slog.wtf(TAG, "BUG: " + nai + " has stateful capability.");
1895 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001896 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001897 }
1898 break;
1899 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001900 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1901 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1902 if (nai == null) {
1903 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1904 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001905 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001906 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001907 "; created=" + nai.created);
1908 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001909 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001910 synchronized (nai) {
1911 nai.linkProperties = (LinkProperties)msg.obj;
1912 }
Paul Jenseneec75412014-08-04 12:21:19 -04001913 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001914 }
1915 break;
1916 }
1917 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1918 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1919 if (nai == null) {
1920 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1921 break;
1922 }
1923 info = (NetworkInfo) msg.obj;
1924 updateNetworkInfo(nai, info);
1925 break;
1926 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001927 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1928 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1929 if (nai == null) {
1930 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1931 break;
1932 }
1933 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001934 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001935 break;
1936 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001937 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1938 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1939 if (nai == null) {
1940 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1941 break;
1942 }
1943 try {
1944 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001945 } catch (Exception e) {
1946 // Never crash!
1947 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001948 }
1949 break;
1950 }
1951 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1952 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1953 if (nai == null) {
1954 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1955 break;
1956 }
1957 try {
1958 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001959 } catch (Exception e) {
1960 // Never crash!
1961 loge("Exception in removeVpnUidRanges: " + e);
1962 }
1963 break;
1964 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001965 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1966 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1967 if (nai == null) {
1968 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1969 break;
1970 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001971 if (nai.created && !nai.networkMisc.explicitlySelected) {
1972 loge("ERROR: created network explicitly selected.");
1973 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001974 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001975 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001976 break;
1977 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001978 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001979 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001980 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1981 final boolean valid =
1982 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04001983 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
1984 if (valid != nai.lastValidated) {
1985 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04001986 nai.lastValidated = valid;
1987 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04001988 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04001989 // If score has changed, rebroadcast to NetworkFactories. b/17726566
1990 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04001991 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001992 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001993 // Let the NetworkAgent know the state of its network
1994 nai.asyncChannel.sendMessage(
1995 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1996 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1997 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001998 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001999 break;
2000 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002001 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002002 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002003 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2004 handleLingerComplete(nai);
2005 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002006 break;
2007 }
Paul Jensen869868be2014-05-15 10:33:05 -04002008 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002009 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002010 final boolean visible = (msg.arg1 != 0);
2011 final NetworkAgentInfo nai;
2012 synchronized (mNetworkForNetId) {
2013 nai = mNetworkForNetId.get(netId);
2014 }
2015 // If captive portal status has changed, update capabilities.
2016 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2017 nai.lastCaptivePortalDetected = visible;
2018 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002019 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002020 }
2021 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002022 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002023 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002024 if (nai == null) {
2025 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2026 break;
2027 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002028 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002029 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2030 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002031 }
Paul Jensen869868be2014-05-15 10:33:05 -04002032 break;
2033 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002034 }
2035 }
2036 }
2037
Paul Jensen85cf78e2015-06-25 13:25:07 -04002038 private void linger(NetworkAgentInfo nai) {
2039 nai.lingering = true;
2040 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2041 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2042 }
2043
Paul Jensen0cc17322014-11-25 15:26:53 -05002044 // Cancel any lingering so the linger timeout doesn't teardown a network.
2045 // This should be called when a network begins satisfying a NetworkRequest.
2046 // Note: depending on what state the NetworkMonitor is in (e.g.,
2047 // if it's awaiting captive portal login, or if validation failed), this
2048 // may trigger a re-evaluation of the network.
2049 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002050 nai.networkLingered.clear();
2051 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002052 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002053 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002054 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2055 }
2056
Robert Greenwalt7b816022014-04-18 15:25:25 -07002057 private void handleAsyncChannelHalfConnect(Message msg) {
2058 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002059 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002060 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2061 if (VDBG) log("NetworkFactory connected");
2062 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002063 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002064 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002065 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002066 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002067 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002068 }
2069 } else {
2070 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002071 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002072 }
2073 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2074 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2075 if (VDBG) log("NetworkAgent connected");
2076 // A network agent has requested a connection. Establish the connection.
2077 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2078 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2079 } else {
2080 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002081 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002082 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002083 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002084 synchronized (mNetworkForNetId) {
2085 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002086 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002087 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002088 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002089 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002090 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002091 }
2092 }
2093 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002094
Robert Greenwalt7b816022014-04-18 15:25:25 -07002095 private void handleAsyncChannelDisconnected(Message msg) {
2096 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2097 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002098 if (DBG) {
2099 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2100 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002101 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002102 // TODO - if we move the logic to the network agent (have them disconnect
2103 // because they lost all their requests or because their score isn't good)
2104 // then they would disconnect organically, report their new state and then
2105 // disconnect the channel.
2106 if (nai.networkInfo.isConnected()) {
2107 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2108 null, null);
2109 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002110 final boolean wasDefault = isDefaultNetwork(nai);
2111 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002112 mDefaultInetConditionPublished = 0;
2113 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002114 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002115 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002116 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002117 mNetworkAgentInfos.remove(msg.replyTo);
2118 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002119 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002120 // Remove the NetworkAgent, but don't mark the netId as
2121 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002122 mNetworkForNetId.remove(nai.network.netId);
2123 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002124 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002125 for (int i = 0; i < nai.networkRequests.size(); i++) {
2126 NetworkRequest request = nai.networkRequests.valueAt(i);
2127 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2128 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2129 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002130 sendUpdatedScoreToFactories(request, 0);
2131 }
2132 }
2133 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2134 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002135 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002136 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002137 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002138 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002139 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002140 if (nai.created) {
2141 // Tell netd to clean up the configuration for this network
2142 // (routing rules, DNS, etc).
2143 // This may be slow as it requires a lot of netd shelling out to ip and
2144 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2145 // after we've rematched networks with requests which should make a potential
2146 // fallback network the default or requested a new network from the
2147 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2148 // long time.
2149 try {
2150 mNetd.removeNetwork(nai.network.netId);
2151 } catch (Exception e) {
2152 loge("Exception removing network: " + e);
2153 }
2154 }
2155 synchronized (mNetworkForNetId) {
2156 mNetIdInUse.delete(nai.network.netId);
2157 }
2158 } else {
2159 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2160 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002161 }
2162 }
2163
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002164 // If this method proves to be too slow then we can maintain a separate
2165 // pendingIntent => NetworkRequestInfo map.
2166 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2167 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2168 Intent intent = pendingIntent.getIntent();
2169 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2170 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2171 if (existingPendingIntent != null &&
2172 existingPendingIntent.getIntent().filterEquals(intent)) {
2173 return entry.getValue();
2174 }
2175 }
2176 return null;
2177 }
2178
2179 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2180 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2181
2182 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2183 if (existingRequest != null) { // remove the existing request.
2184 if (DBG) log("Replacing " + existingRequest.request + " with "
2185 + nri.request + " because their intents matched.");
2186 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2187 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002188 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002189 }
2190
Erik Klineda4bfa82015-04-30 12:58:40 +09002191 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002192 mNetworkRequests.put(nri.request, nri);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002193 rematchAllNetworksAndRequests(null, 0);
2194 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2195 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002196 }
2197 }
2198
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002199 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2200 int callingUid) {
2201 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2202 if (nri != null) {
2203 handleReleaseNetworkRequest(nri.request, callingUid);
2204 }
2205 }
2206
Paul Jensen99364842014-12-09 11:43:45 -05002207 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002208 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2209 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002210 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002211 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002212 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2213 // If this Network is already the highest scoring Network for a request, or if
2214 // there is hope for it to become one if it validated, then it is needed.
2215 if (nri.isRequest && nai.satisfies(nri.request) &&
2216 (nai.networkRequests.get(nri.request.requestId) != null ||
2217 // Note that this catches two important cases:
2218 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2219 // is currently satisfying the request. This is desirable when
2220 // cellular ends up validating but WiFi does not.
2221 // 2. Unvalidated WiFi will not be reaped when validated cellular
2222 // is currently satsifying the request. This is desirable when
2223 // WiFi ends up validating and out scoring cellular.
2224 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2225 nai.getCurrentScoreAsValidated())) {
2226 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002227 }
2228 }
Paul Jensene0988542015-06-25 15:30:08 -04002229 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002230 }
2231
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002232 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2233 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002234 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002235 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002236 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2237 return;
2238 }
2239 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002240 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002241 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002242 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002243 // Find all networks that are satisfying this request and remove the request
2244 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002245 // TODO - it's my understanding that for a request there is only a single
2246 // network satisfying it, so this loop is wasteful
2247 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002248 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2249 if (nai.networkRequests.get(nri.request.requestId) != null) {
2250 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002251 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002252 log(" Removing from current network " + nai.name() +
2253 ", leaving " + nai.networkRequests.size() +
2254 " requests.");
2255 }
Paul Jensen99364842014-12-09 11:43:45 -05002256 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002257 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002258 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002259 } else {
2260 // suspect there should only be one pass through here
2261 // but if any were kept do the check below
2262 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002263 }
2264 }
2265 }
2266
Robert Greenwalt51481852015-01-08 14:43:31 -08002267 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2268 if (nai != null) {
2269 mNetworkForRequestId.remove(nri.request.requestId);
2270 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002271 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002272 // that a network connected to serve it, even though the network was already
2273 // connected. Now that this request has gone away, we might have to pretend
2274 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002275 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002276 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2277 boolean doRemove = true;
2278 if (wasKept) {
2279 // check if any of the remaining requests for this network are for the
2280 // same legacy type - if so, don't remove the nai
2281 for (int i = 0; i < nai.networkRequests.size(); i++) {
2282 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2283 if (otherRequest.legacyType == nri.request.legacyType &&
2284 isRequest(otherRequest)) {
2285 if (DBG) log(" still have other legacy request - leaving");
2286 doRemove = false;
2287 }
2288 }
2289 }
2290
2291 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002292 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002293 }
2294 }
2295
Robert Greenwalta67be032014-05-16 15:49:14 -07002296 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002297 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2298 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002299 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002300 } else {
2301 // listens don't have a singular affectedNetwork. Check all networks to see
2302 // if this listen request applies and remove it.
2303 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2304 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002305 }
2306 }
2307 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2308 }
2309 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002310
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002311 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2312 enforceConnectivityInternalPermission();
2313 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2314 accept ? 1 : 0, always ? 1: 0, network));
2315 }
2316
2317 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2318 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2319 " accept=" + accept + " always=" + always);
2320
2321 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2322 if (nai == null) {
2323 // Nothing to do.
2324 return;
2325 }
2326
2327 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002328 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002329 return;
2330 }
2331
2332 if (!nai.networkMisc.explicitlySelected) {
2333 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2334 }
2335
2336 if (accept != nai.networkMisc.acceptUnvalidated) {
2337 int oldScore = nai.getCurrentScore();
2338 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002339 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002340 sendUpdatedScoreToFactories(nai);
2341 }
2342
2343 if (always) {
2344 nai.asyncChannel.sendMessage(
2345 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2346 }
2347
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002348 if (!accept) {
2349 // Tell the NetworkAgent that the network does not have Internet access (because that's
2350 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2351 // the future. We do this now because NetworkMonitor might not yet have finished
2352 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2353 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2354 NetworkAgent.INVALID_NETWORK, 0, null);
2355 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2356 // to reconnect to it immediately. http://b/20739299
2357 }
2358
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002359 }
2360
2361 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002362 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002363 mHandler.sendMessageDelayed(
2364 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2365 PROMPT_UNVALIDATED_DELAY_MS);
2366 }
2367
2368 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002369 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002370 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2371
2372 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2373 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002374 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002375 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002376 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2377 return;
2378 }
2379
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002380 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002381 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002382 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2383 intent.setClassName("com.android.settings",
2384 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002385
2386 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2387 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2388 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002389 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002390 }
2391
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002392 private class InternalHandler extends Handler {
2393 public InternalHandler(Looper looper) {
2394 super(looper);
2395 }
2396
2397 @Override
2398 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002399 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002400 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002401 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002402 String causedBy = null;
2403 synchronized (ConnectivityService.this) {
2404 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2405 mNetTransitionWakeLock.isHeld()) {
2406 mNetTransitionWakeLock.release();
2407 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002408 } else {
2409 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002410 }
2411 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002412 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2413 log("Failed to find a new network - expiring NetTransition Wakelock");
2414 } else {
2415 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2416 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002417 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002418 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002419 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002420 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002421 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002422 break;
2423 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002424 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002425 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002426 sendStickyBroadcast(intent);
2427 break;
2428 }
Jason Monkdecd2952013-10-10 14:02:51 -04002429 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002430 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002431 break;
2432 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002433 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002434 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2435 break;
2436 }
2437 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2438 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002439 break;
2440 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002441 case EVENT_REGISTER_NETWORK_AGENT: {
2442 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2443 break;
2444 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002445 case EVENT_REGISTER_NETWORK_REQUEST:
2446 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002447 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002448 break;
2449 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002450 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2451 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002452 handleRegisterNetworkRequestWithIntent(msg);
2453 break;
2454 }
2455 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2456 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2457 break;
2458 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002459 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002460 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002461 break;
2462 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002463 case EVENT_SET_ACCEPT_UNVALIDATED: {
2464 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2465 break;
2466 }
2467 case EVENT_PROMPT_UNVALIDATED: {
2468 handlePromptUnvalidated((Network) msg.obj);
2469 break;
2470 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002471 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2472 handleMobileDataAlwaysOn();
2473 break;
2474 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002475 case EVENT_SYSTEM_READY: {
2476 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2477 nai.networkMonitor.systemReady = true;
2478 }
2479 break;
2480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 }
2482 }
2483 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002484
2485 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002486 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002487 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002488 if (isTetheringSupported()) {
2489 return mTethering.tether(iface);
2490 } else {
2491 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2492 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002493 }
2494
2495 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002496 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002497 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002498
2499 if (isTetheringSupported()) {
2500 return mTethering.untether(iface);
2501 } else {
2502 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2503 }
2504 }
2505
2506 // javadoc from interface
2507 public int getLastTetherError(String iface) {
2508 enforceTetherAccessPermission();
2509
2510 if (isTetheringSupported()) {
2511 return mTethering.getLastTetherError(iface);
2512 } else {
2513 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2514 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002515 }
2516
2517 // TODO - proper iface API for selection by property, inspection, etc
2518 public String[] getTetherableUsbRegexs() {
2519 enforceTetherAccessPermission();
2520 if (isTetheringSupported()) {
2521 return mTethering.getTetherableUsbRegexs();
2522 } else {
2523 return new String[0];
2524 }
2525 }
2526
2527 public String[] getTetherableWifiRegexs() {
2528 enforceTetherAccessPermission();
2529 if (isTetheringSupported()) {
2530 return mTethering.getTetherableWifiRegexs();
2531 } else {
2532 return new String[0];
2533 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002534 }
2535
Danica Chang6fdd0c62010-08-11 14:54:43 -07002536 public String[] getTetherableBluetoothRegexs() {
2537 enforceTetherAccessPermission();
2538 if (isTetheringSupported()) {
2539 return mTethering.getTetherableBluetoothRegexs();
2540 } else {
2541 return new String[0];
2542 }
2543 }
2544
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002545 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002546 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002547 if (isTetheringSupported()) {
2548 return mTethering.setUsbTethering(enable);
2549 } else {
2550 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2551 }
2552 }
2553
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002554 // TODO - move iface listing, queries, etc to new module
2555 // javadoc from interface
2556 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002557 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002558 return mTethering.getTetherableIfaces();
2559 }
2560
2561 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002562 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002563 return mTethering.getTetheredIfaces();
2564 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002565
Robert Greenwalt5a735062010-03-02 17:25:02 -08002566 public String[] getTetheringErroredIfaces() {
2567 enforceTetherAccessPermission();
2568 return mTethering.getErroredIfaces();
2569 }
2570
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002571 public String[] getTetheredDhcpRanges() {
2572 enforceConnectivityInternalPermission();
2573 return mTethering.getTetheredDhcpRanges();
2574 }
2575
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002576 // if ro.tether.denied = true we default to no tethering
2577 // gservices could set the secure setting to 1 though to enable it on a build where it
2578 // had previously been turned off.
2579 public boolean isTetheringSupported() {
2580 enforceTetherAccessPermission();
2581 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002582 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002583 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2584 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002585 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2586 mTethering.getTetherableWifiRegexs().length != 0 ||
2587 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2588 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002589 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002590
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002591 // Called when we lose the default network and have no replacement yet.
2592 // This will automatically be cleared after X seconds or a new default network
2593 // becomes CONNECTED, whichever happens first. The timer is started by the
2594 // first caller and not restarted by subsequent callers.
2595 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002596 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002597 synchronized (this) {
2598 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002599 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002600 mNetTransitionWakeLock.acquire();
2601 mNetTransitionWakeLockCausedBy = forWhom;
2602 }
2603 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002604 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002605 mNetTransitionWakeLockTimeout);
2606 return;
2607 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002608
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002609 // 100 percent is full good, 0 is full bad.
2610 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002611 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002612 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002613 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002614 }
2615
Paul Jensenbfd17b72015-04-07 12:43:13 -04002616 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002617 enforceAccessPermission();
2618 enforceInternetPermission();
2619
Paul Jensenbfd17b72015-04-07 12:43:13 -04002620 NetworkAgentInfo nai;
2621 if (network == null) {
2622 nai = getDefaultNetwork();
2623 } else {
2624 nai = getNetworkAgentInfoForNetwork(network);
2625 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002626 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2627 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2628 return;
2629 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002630 // Revalidate if the app report does not match our current validated state.
2631 if (hasConnectivity == nai.lastValidated) return;
2632 final int uid = Binder.getCallingUid();
2633 if (DBG) {
2634 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2635 ") by " + uid);
2636 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002637 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002638 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2639 // which isn't meant to work on uncreated networks.
2640 if (!nai.created) return;
2641
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002642 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002643
2644 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2645 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002646 }
2647
Paul Jensen25a217c2015-02-27 22:55:47 -05002648 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2649 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2650 enforceConnectivityInternalPermission();
2651 }
2652 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2653 if (nai == null) return;
2654 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2655 actionToken);
2656 }
2657
Paul Jensencee9b512015-05-06 07:32:40 -04002658 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002659 // this information is already available as a world read/writable jvm property
2660 // so this API change wouldn't have a benifit. It also breaks the passing
2661 // of proxy info to all the JVMs.
2662 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002663 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002664 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002665 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2666 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002667 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002668 }
2669
Paul Jensencee9b512015-05-06 07:32:40 -04002670 public ProxyInfo getProxyForNetwork(Network network) {
2671 if (network == null) return getDefaultProxy();
2672 final ProxyInfo globalProxy = getGlobalProxy();
2673 if (globalProxy != null) return globalProxy;
2674 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2675 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2676 // caller may not have.
2677 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2678 if (nai == null) return null;
2679 synchronized (nai) {
2680 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2681 if (proxyInfo == null) return null;
2682 return new ProxyInfo(proxyInfo);
2683 }
2684 }
2685
Paul Jensene0bef712014-12-10 15:12:18 -05002686 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2687 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2688 // proxy is null then there is no proxy in place).
2689 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2690 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2691 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2692 proxy = null;
2693 }
2694 return proxy;
2695 }
2696
2697 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2698 // better for determining if a new proxy broadcast is necessary:
2699 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2700 // avoid unnecessary broadcasts.
2701 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2702 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2703 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2704 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2705 // all set.
2706 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2707 a = canonicalizeProxyInfo(a);
2708 b = canonicalizeProxyInfo(b);
2709 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2710 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2711 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2712 }
2713
Jason Monk207900c2014-04-25 15:00:09 -04002714 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002715 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002716
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002717 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002718 if (proxyProperties == mGlobalProxy) return;
2719 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2720 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2721
2722 String host = "";
2723 int port = 0;
2724 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002725 String pacFileUrl = "";
2726 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002727 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002728 if (!proxyProperties.isValid()) {
2729 if (DBG)
2730 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2731 return;
2732 }
Jason Monk207900c2014-04-25 15:00:09 -04002733 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002734 host = mGlobalProxy.getHost();
2735 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002736 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002737 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002738 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002739 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002740 } else {
2741 mGlobalProxy = null;
2742 }
2743 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002744 final long token = Binder.clearCallingIdentity();
2745 try {
2746 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2747 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2748 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2749 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002750 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002751 } finally {
2752 Binder.restoreCallingIdentity(token);
2753 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002754
Jason Monkcf0f97a2014-10-02 15:39:38 -04002755 if (mGlobalProxy == null) {
2756 proxyProperties = mDefaultProxy;
2757 }
2758 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002759 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002760 }
2761
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002762 private void loadGlobalProxy() {
2763 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002764 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2765 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2766 String exclList = Settings.Global.getString(res,
2767 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002768 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2769 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002770 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002771 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002772 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002773 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002774 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002775 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002776 if (!proxyProperties.isValid()) {
2777 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2778 return;
2779 }
2780
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002781 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002782 mGlobalProxy = proxyProperties;
2783 }
2784 }
2785 }
2786
Jason Monk207900c2014-04-25 15:00:09 -04002787 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002788 // this information is already available as a world read/writable jvm property
2789 // so this API change wouldn't have a benifit. It also breaks the passing
2790 // of proxy info to all the JVMs.
2791 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002792 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002793 return mGlobalProxy;
2794 }
2795 }
2796
Jason Monk207900c2014-04-25 15:00:09 -04002797 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002798 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002799 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002800 proxy = null;
2801 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002802 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002803 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002804 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002805 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002806 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2807 return;
2808 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002809
2810 // This call could be coming from the PacManager, containing the port of the local
2811 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2812 // global (to get the correct local port), and send a broadcast.
2813 // TODO: Switch PacManager to have its own message to send back rather than
2814 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002815 if ((mGlobalProxy != null) && (proxy != null)
2816 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002817 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2818 mGlobalProxy = proxy;
2819 sendProxyBroadcast(mGlobalProxy);
2820 return;
2821 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002822 mDefaultProxy = proxy;
2823
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002824 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002825 if (!mDefaultProxyDisabled) {
2826 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002827 }
2828 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002829 }
2830
Paul Jensene0bef712014-12-10 15:12:18 -05002831 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2832 // This method gets called when any network changes proxy, but the broadcast only ever contains
2833 // the default proxy (even if it hasn't changed).
2834 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2835 // world where an app might be bound to a non-default network.
2836 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2837 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2838 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2839
2840 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2841 sendProxyBroadcast(getDefaultProxy());
2842 }
2843 }
2844
Robert Greenwalt434203a2010-10-11 16:00:27 -07002845 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002846 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2847 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002848 if (!TextUtils.isEmpty(proxy)) {
2849 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002850 if (data.length == 0) {
2851 return;
2852 }
2853
Robert Greenwalt434203a2010-10-11 16:00:27 -07002854 String proxyHost = data[0];
2855 int proxyPort = 8080;
2856 if (data.length > 1) {
2857 try {
2858 proxyPort = Integer.parseInt(data[1]);
2859 } catch (NumberFormatException e) {
2860 return;
2861 }
2862 }
Jason Monk207900c2014-04-25 15:00:09 -04002863 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002864 setGlobalProxy(p);
2865 }
2866 }
2867
Jason Monk207900c2014-04-25 15:00:09 -04002868 private void sendProxyBroadcast(ProxyInfo proxy) {
2869 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002870 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002871 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002872 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002873 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2874 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002875 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002876 final long ident = Binder.clearCallingIdentity();
2877 try {
2878 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2879 } finally {
2880 Binder.restoreCallingIdentity(ident);
2881 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002882 }
2883
2884 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002885 final private HashMap<Uri, Integer> mUriEventMap;
2886 final private Context mContext;
2887 final private Handler mHandler;
2888
2889 SettingsObserver(Context context, Handler handler) {
2890 super(null);
2891 mUriEventMap = new HashMap<Uri, Integer>();
2892 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002893 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002894 }
2895
Erik Klineda4bfa82015-04-30 12:58:40 +09002896 void observe(Uri uri, int what) {
2897 mUriEventMap.put(uri, what);
2898 final ContentResolver resolver = mContext.getContentResolver();
2899 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002900 }
2901
2902 @Override
2903 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002904 Slog.wtf(TAG, "Should never be reached.");
2905 }
2906
2907 @Override
2908 public void onChange(boolean selfChange, Uri uri) {
2909 final Integer what = mUriEventMap.get(uri);
2910 if (what != null) {
2911 mHandler.obtainMessage(what.intValue()).sendToTarget();
2912 } else {
2913 loge("No matching event to send for URI=" + uri);
2914 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002915 }
2916 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002917
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002918 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002919 Slog.d(TAG, s);
2920 }
2921
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002922 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002923 Slog.e(TAG, s);
2924 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002925
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002926 private static <T> T checkNotNull(T value, String message) {
2927 if (value == null) {
2928 throw new NullPointerException(message);
2929 }
2930 return value;
2931 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002932
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002933 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002934 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002935 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2936 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2937 *
2938 * @param oldPackage Package name of the application which currently controls VPN, which will
2939 * be replaced. If there is no such application, this should should either be
2940 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2941 * @param newPackage Package name of the application which should gain control of VPN, or
2942 * {@code null} to disable.
2943 * @param userId User for whom to prepare the new VPN.
2944 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002945 * @hide
2946 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002947 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002948 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2949 int userId) {
2950 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002951 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01002952
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002953 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07002954 Vpn vpn = mVpns.get(userId);
2955 if (vpn != null) {
2956 return vpn.prepare(oldPackage, newPackage);
2957 } else {
2958 return false;
2959 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002960 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002961 }
2962
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002963 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01002964 * Set whether the VPN package has the ability to launch VPNs without user intervention.
2965 * This method is used by system-privileged apps.
2966 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2967 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2968 *
2969 * @param packageName The package for which authorization state should change.
2970 * @param userId User for whom {@code packageName} is installed.
2971 * @param authorized {@code true} if this app should be able to start a VPN connection without
2972 * explicit user approval, {@code false} if not.
2973 *
Jeff Davidson05542602014-08-11 14:07:27 -07002974 * @hide
2975 */
2976 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002977 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
2978 enforceCrossUserPermission(userId);
2979
Jeff Davidson05542602014-08-11 14:07:27 -07002980 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07002981 Vpn vpn = mVpns.get(userId);
2982 if (vpn != null) {
2983 vpn.setPackageAuthorization(packageName, authorized);
2984 }
Jeff Davidson05542602014-08-11 14:07:27 -07002985 }
2986 }
2987
2988 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002989 * Configure a TUN interface and return its file descriptor. Parameters
2990 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002991 * and not available in ConnectivityManager. Permissions are checked in
2992 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002993 * @hide
2994 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002995 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002996 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002997 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002998 int user = UserHandle.getUserId(Binder.getCallingUid());
2999 synchronized(mVpns) {
3000 return mVpns.get(user).establish(config);
3001 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003002 }
3003
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003004 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003005 * Start legacy VPN, controlling native daemons as needed. Creates a
3006 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003007 */
3008 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003009 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003010 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003011 final LinkProperties egress = getActiveLinkProperties();
3012 if (egress == null) {
3013 throw new IllegalStateException("Missing active network connection");
3014 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003015 int user = UserHandle.getUserId(Binder.getCallingUid());
3016 synchronized(mVpns) {
3017 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3018 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003019 }
3020
3021 /**
3022 * Return the information of the ongoing legacy VPN. This method is used
3023 * by VpnSettings and not available in ConnectivityManager. Permissions
3024 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003025 */
3026 @Override
3027 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003028 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003029 int user = UserHandle.getUserId(Binder.getCallingUid());
3030 synchronized(mVpns) {
3031 return mVpns.get(user).getLegacyVpnInfo();
3032 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003033 }
3034
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003035 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003036 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3037 * and not available in ConnectivityManager.
3038 */
3039 @Override
3040 public VpnInfo[] getAllVpnInfo() {
3041 enforceConnectivityInternalPermission();
3042 if (mLockdownEnabled) {
3043 return new VpnInfo[0];
3044 }
3045
3046 synchronized(mVpns) {
3047 List<VpnInfo> infoList = new ArrayList<>();
3048 for (int i = 0; i < mVpns.size(); i++) {
3049 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3050 if (info != null) {
3051 infoList.add(info);
3052 }
3053 }
3054 return infoList.toArray(new VpnInfo[infoList.size()]);
3055 }
3056 }
3057
3058 /**
3059 * @return VPN information for accounting, or null if we can't retrieve all required
3060 * information, e.g primary underlying iface.
3061 */
3062 @Nullable
3063 private VpnInfo createVpnInfo(Vpn vpn) {
3064 VpnInfo info = vpn.getVpnInfo();
3065 if (info == null) {
3066 return null;
3067 }
3068 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3069 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3070 // the underlyingNetworks list.
3071 if (underlyingNetworks == null) {
3072 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3073 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3074 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3075 }
3076 } else if (underlyingNetworks.length > 0) {
3077 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3078 if (linkProperties != null) {
3079 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3080 }
3081 }
3082 return info.primaryUnderlyingIface == null ? null : info;
3083 }
3084
3085 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003086 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3087 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003088 * Permissions are checked in Vpn class.
3089 * @hide
3090 */
3091 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003092 public VpnConfig getVpnConfig(int userId) {
3093 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003094 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003095 Vpn vpn = mVpns.get(userId);
3096 if (vpn != null) {
3097 return vpn.getVpnConfig();
3098 } else {
3099 return null;
3100 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003101 }
3102 }
3103
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003104 @Override
3105 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003106 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3107 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3108 return false;
3109 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003110
3111 // Tear down existing lockdown if profile was removed
3112 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3113 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003114 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003115 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3116 return false;
3117 }
3118
3119 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3120 final VpnProfile profile = VpnProfile.decode(
3121 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003122 int user = UserHandle.getUserId(Binder.getCallingUid());
3123 synchronized(mVpns) {
3124 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3125 profile));
3126 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003127 } else {
3128 setLockdownTracker(null);
3129 }
3130
3131 return true;
3132 }
3133
3134 /**
3135 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3136 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3137 */
3138 private void setLockdownTracker(LockdownVpnTracker tracker) {
3139 // Shutdown any existing tracker
3140 final LockdownVpnTracker existing = mLockdownTracker;
3141 mLockdownTracker = null;
3142 if (existing != null) {
3143 existing.shutdown();
3144 }
3145
3146 try {
3147 if (tracker != null) {
3148 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003149 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003150 mLockdownTracker = tracker;
3151 mLockdownTracker.init();
3152 } else {
3153 mNetd.setFirewallEnabled(false);
3154 }
3155 } catch (RemoteException e) {
3156 // ignored; NMS lives inside system_server
3157 }
3158 }
3159
3160 private void throwIfLockdownEnabled() {
3161 if (mLockdownEnabled) {
3162 throw new IllegalStateException("Unavailable in lockdown mode");
3163 }
3164 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003165
Wink Savilleab9321d2013-06-29 21:10:57 -07003166 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003167 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003168 // TODO: Remove? Any reason to trigger a provisioning check?
3169 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003170 }
3171
3172 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003173 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003174
Paul Jensen89e0f092014-09-15 15:59:36 -04003175 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003176 if (DBG) {
3177 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003178 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003179 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003180 Intent intent = new Intent(action);
3181 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003182 // Concatenate the range of types onto the range of NetIDs.
3183 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003184 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003185 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003186 }
3187
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003188 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003189 * Show or hide network provisioning notifications.
3190 *
3191 * We use notifications for two purposes: to notify that a network requires sign in
3192 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3193 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3194 * particular network we can display the notification type that was most recently requested.
3195 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3196 * might first display NO_INTERNET, and then when the captive portal check completes, display
3197 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003198 *
3199 * @param id an identifier that uniquely identifies this notification. This must match
3200 * between show and hide calls. We use the NetID value but for legacy callers
3201 * we concatenate the range of types with the range of NetIDs.
3202 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003203 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003204 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3205 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003206 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003207 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3208 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003209 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003210 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003211
3212 Resources r = Resources.getSystem();
3213 NotificationManager notificationManager = (NotificationManager) mContext
3214 .getSystemService(Context.NOTIFICATION_SERVICE);
3215
3216 if (visible) {
3217 CharSequence title;
3218 CharSequence details;
3219 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003220 if (notifyType == NotificationType.NO_INTERNET &&
3221 networkType == ConnectivityManager.TYPE_WIFI) {
3222 title = r.getString(R.string.wifi_no_internet, 0);
3223 details = r.getString(R.string.wifi_no_internet_detailed);
3224 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3225 } else if (notifyType == NotificationType.SIGN_IN) {
3226 switch (networkType) {
3227 case ConnectivityManager.TYPE_WIFI:
3228 title = r.getString(R.string.wifi_available_sign_in, 0);
3229 details = r.getString(R.string.network_available_sign_in_detailed,
3230 extraInfo);
3231 icon = R.drawable.stat_notify_wifi_in_range;
3232 break;
3233 case ConnectivityManager.TYPE_MOBILE:
3234 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3235 title = r.getString(R.string.network_available_sign_in, 0);
3236 // TODO: Change this to pull from NetworkInfo once a printable
3237 // name has been added to it
3238 details = mTelephonyManager.getNetworkOperatorName();
3239 icon = R.drawable.stat_notify_rssi_in_range;
3240 break;
3241 default:
3242 title = r.getString(R.string.network_available_sign_in, 0);
3243 details = r.getString(R.string.network_available_sign_in_detailed,
3244 extraInfo);
3245 icon = R.drawable.stat_notify_rssi_in_range;
3246 break;
3247 }
3248 } else {
3249 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3250 + getNetworkTypeName(networkType));
3251 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003252 }
3253
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003254 Notification notification = new Notification.Builder(mContext)
3255 .setWhen(0)
3256 .setSmallIcon(icon)
3257 .setAutoCancel(true)
3258 .setTicker(title)
3259 .setColor(mContext.getColor(
3260 com.android.internal.R.color.system_notification_accent_color))
3261 .setContentTitle(title)
3262 .setContentText(details)
3263 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003264 .setLocalOnly(true)
3265 .setPriority(highPriority ?
3266 Notification.PRIORITY_HIGH :
3267 Notification.PRIORITY_DEFAULT)
3268 .setDefaults(Notification.DEFAULT_ALL)
3269 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003270 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003271
Wink Saville948282b2013-08-29 08:55:16 -07003272 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003273 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003274 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003275 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003276 npe.printStackTrace();
3277 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003278 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003279 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003280 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003281 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003282 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003283 npe.printStackTrace();
3284 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003285 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003286 }
3287
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003288 /** Location to an updatable file listing carrier provisioning urls.
3289 * An example:
3290 *
3291 * <?xml version="1.0" encoding="utf-8"?>
3292 * <provisioningUrls>
3293 * <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 -07003294 * </provisioningUrls>
3295 */
3296 private static final String PROVISIONING_URL_PATH =
3297 "/data/misc/radio/provisioning_urls.xml";
3298 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003299
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003300 /** XML tag for root element. */
3301 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3302 /** XML tag for individual url */
3303 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003304 /** XML attribute for mcc */
3305 private static final String ATTR_MCC = "mcc";
3306 /** XML attribute for mnc */
3307 private static final String ATTR_MNC = "mnc";
3308
Paul Jensen434dde82015-06-11 09:43:30 -04003309 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003310 FileReader fileReader = null;
3311 XmlPullParser parser = null;
3312 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003313
3314 try {
3315 fileReader = new FileReader(mProvisioningUrlFile);
3316 parser = Xml.newPullParser();
3317 parser.setInput(fileReader);
3318 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3319
3320 while (true) {
3321 XmlUtils.nextElement(parser);
3322
3323 String element = parser.getName();
3324 if (element == null) break;
3325
Paul Jensen434dde82015-06-11 09:43:30 -04003326 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003327 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3328 try {
3329 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3330 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3331 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3332 parser.next();
3333 if (parser.getEventType() == XmlPullParser.TEXT) {
3334 return parser.getText();
3335 }
3336 }
3337 }
3338 } catch (NumberFormatException e) {
3339 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3340 }
3341 }
3342 }
3343 return null;
3344 } catch (FileNotFoundException e) {
3345 loge("Carrier Provisioning Urls file not found");
3346 } catch (XmlPullParserException e) {
3347 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3348 } catch (IOException e) {
3349 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3350 } finally {
3351 if (fileReader != null) {
3352 try {
3353 fileReader.close();
3354 } catch (IOException e) {}
3355 }
3356 }
3357 return null;
3358 }
3359
Wink Saville42d4f082013-07-20 20:31:59 -07003360 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003361 public String getMobileProvisioningUrl() {
3362 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003363 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003364 if (TextUtils.isEmpty(url)) {
3365 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003366 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003367 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003368 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003369 }
Wink Saville8cf35602013-07-10 23:00:07 -07003370 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003371 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003372 String phoneNumber = mTelephonyManager.getLine1Number();
3373 if (TextUtils.isEmpty(phoneNumber)) {
3374 phoneNumber = "0000000000";
3375 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003376 url = String.format(url,
3377 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3378 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003379 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003380 }
3381
Wink Savilleab9321d2013-06-29 21:10:57 -07003382 return url;
3383 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003384
Wink Saville948282b2013-08-29 08:55:16 -07003385 @Override
3386 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003387 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003388 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003389 final long ident = Binder.clearCallingIdentity();
3390 try {
3391 setProvNotificationVisible(visible, networkType, action);
3392 } finally {
3393 Binder.restoreCallingIdentity(ident);
3394 }
Wink Saville948282b2013-08-29 08:55:16 -07003395 }
Wink Saville7788c612013-08-29 14:57:08 -07003396
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003397 @Override
3398 public void setAirplaneMode(boolean enable) {
3399 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003400 final long ident = Binder.clearCallingIdentity();
3401 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003402 final ContentResolver cr = mContext.getContentResolver();
3403 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3404 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3405 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003406 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003407 } finally {
3408 Binder.restoreCallingIdentity(ident);
3409 }
3410 }
3411
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003412 private void onUserStart(int userId) {
3413 synchronized(mVpns) {
3414 Vpn userVpn = mVpns.get(userId);
3415 if (userVpn != null) {
3416 loge("Starting user already has a VPN");
3417 return;
3418 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003419 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003420 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003421 }
3422 }
3423
3424 private void onUserStop(int userId) {
3425 synchronized(mVpns) {
3426 Vpn userVpn = mVpns.get(userId);
3427 if (userVpn == null) {
3428 loge("Stopping user has no VPN");
3429 return;
3430 }
3431 mVpns.delete(userId);
3432 }
3433 }
3434
3435 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3436 @Override
3437 public void onReceive(Context context, Intent intent) {
3438 final String action = intent.getAction();
3439 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3440 if (userId == UserHandle.USER_NULL) return;
3441
3442 if (Intent.ACTION_USER_STARTING.equals(action)) {
3443 onUserStart(userId);
3444 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3445 onUserStop(userId);
3446 }
3447 }
3448 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003449
Robert Greenwalta67be032014-05-16 15:49:14 -07003450 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3451 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003452 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3453 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003454
Robert Greenwalta67be032014-05-16 15:49:14 -07003455 private static class NetworkFactoryInfo {
3456 public final String name;
3457 public final Messenger messenger;
3458 public final AsyncChannel asyncChannel;
3459
3460 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3461 this.name = name;
3462 this.messenger = messenger;
3463 this.asyncChannel = asyncChannel;
3464 }
3465 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003466
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003467 /**
3468 * Tracks info about the requester.
3469 * Also used to notice when the calling process dies so we can self-expire
3470 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003471 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3472 static final boolean REQUEST = true;
3473 static final boolean LISTEN = false;
3474
3475 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003476 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003477 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003478 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003479 final int mPid;
3480 final int mUid;
3481 final Messenger messenger;
3482 final boolean isRequest;
3483
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003484 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3485 request = r;
3486 mPendingIntent = pi;
3487 messenger = null;
3488 mBinder = null;
3489 mPid = getCallingPid();
3490 mUid = getCallingUid();
3491 this.isRequest = isRequest;
3492 }
3493
Robert Greenwalt9258c642014-03-26 16:47:06 -07003494 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3495 super();
3496 messenger = m;
3497 request = r;
3498 mBinder = binder;
3499 mPid = getCallingPid();
3500 mUid = getCallingUid();
3501 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003502 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003503
3504 try {
3505 mBinder.linkToDeath(this, 0);
3506 } catch (RemoteException e) {
3507 binderDied();
3508 }
3509 }
3510
3511 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003512 if (mBinder != null) {
3513 mBinder.unlinkToDeath(this, 0);
3514 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003515 }
3516
3517 public void binderDied() {
3518 log("ConnectivityService NetworkRequestInfo binderDied(" +
3519 request + ", " + mBinder + ")");
3520 releaseNetworkRequest(request);
3521 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003522
3523 public String toString() {
3524 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003525 mPid + " for " + request +
3526 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003527 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003528 }
3529
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003530 private void ensureImmutableCapabilities(NetworkCapabilities networkCapabilities) {
3531 if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
3532 throw new IllegalArgumentException(
3533 "Cannot request network with NET_CAPABILITY_VALIDATED");
3534 }
3535 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
3536 throw new IllegalArgumentException(
3537 "Cannot request network with NET_CAPABILITY_CAPTIVE_PORTAL");
3538 }
3539 }
3540
Robert Greenwalt9258c642014-03-26 16:47:06 -07003541 @Override
3542 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003543 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003544 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003545 enforceNetworkRequestPermissions(networkCapabilities);
3546 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003547 ensureImmutableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003548
Robert Greenwalt6078b502014-06-11 16:05:07 -07003549 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003550 throw new IllegalArgumentException("Bad timeout specified");
3551 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003552
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003553 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3554 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003555 if (DBG) log("requestNetwork for " + networkRequest);
3556 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3557 NetworkRequestInfo.REQUEST);
3558
3559 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003560 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003561 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003562 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003563 }
3564 return networkRequest;
3565 }
3566
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003567 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003568 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003569 enforceConnectivityInternalPermission();
3570 } else {
3571 enforceChangePermission();
3572 }
3573 }
3574
fenglub15e72b2015-03-20 11:29:56 -07003575 @Override
fengludb571472015-04-21 17:12:05 -07003576 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003577 enforceAccessPermission();
3578 NetworkAgentInfo nai = null;
3579 if (network == null) {
3580 return false;
3581 }
3582 synchronized (mNetworkForNetId) {
3583 nai = mNetworkForNetId.get(network.netId);
3584 }
3585 if (nai != null) {
3586 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3587 return true;
3588 }
3589 return false;
3590 }
3591
3592
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003593 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3594 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003595 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003596 final int uidRules;
3597 final int uid = Binder.getCallingUid();
3598 synchronized(mRulesLock) {
3599 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3600 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003601 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003602 // we could silently fail or we can filter the available nets to only give
3603 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003604 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003605 }
3606 }
3607 }
3608
Robert Greenwalt9258c642014-03-26 16:47:06 -07003609 @Override
3610 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3611 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003612 checkNotNull(operation, "PendingIntent cannot be null.");
3613 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3614 enforceNetworkRequestPermissions(networkCapabilities);
3615 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003616 ensureImmutableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003617
3618 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3619 nextNetworkRequestId());
3620 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3621 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3622 NetworkRequestInfo.REQUEST);
3623 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3624 nri));
3625 return networkRequest;
3626 }
3627
Jeremy Joslin79294842014-12-03 17:15:28 -08003628 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3629 mHandler.sendMessageDelayed(
3630 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3631 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3632 }
3633
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003634 @Override
3635 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003636 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003637 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3638 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003639 }
3640
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003641 // In order to implement the compatibility measure for pre-M apps that call
3642 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3643 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3644 // This ensures it has permission to do so.
3645 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3646 if (nc == null) {
3647 return false;
3648 }
3649 int[] transportTypes = nc.getTransportTypes();
3650 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3651 return false;
3652 }
3653 try {
3654 mContext.enforceCallingOrSelfPermission(
3655 android.Manifest.permission.ACCESS_WIFI_STATE,
3656 "ConnectivityService");
3657 } catch (SecurityException e) {
3658 return false;
3659 }
3660 return true;
3661 }
3662
Robert Greenwalt9258c642014-03-26 16:47:06 -07003663 @Override
3664 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3665 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003666 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3667 enforceAccessPermission();
3668 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003669
3670 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003671 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003672 if (DBG) log("listenForNetwork for " + networkRequest);
3673 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3674 NetworkRequestInfo.LISTEN);
3675
3676 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3677 return networkRequest;
3678 }
3679
3680 @Override
3681 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3682 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003683 checkNotNull(operation, "PendingIntent cannot be null.");
3684 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3685 enforceAccessPermission();
3686 }
3687
3688 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3689 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3690 if (DBG) log("pendingListenForNetwork for " + networkRequest + " to trigger " + operation);
3691 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3692 NetworkRequestInfo.LISTEN);
3693
3694 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003695 }
3696
3697 @Override
3698 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003699 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3700 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003701 }
3702
3703 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003704 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003705 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003706 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3707 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003708 }
3709
Robert Greenwalta67be032014-05-16 15:49:14 -07003710 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003711 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003712 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3713 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3714 }
3715
3716 @Override
3717 public void unregisterNetworkFactory(Messenger messenger) {
3718 enforceConnectivityInternalPermission();
3719 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3720 }
3721
3722 private void handleUnregisterNetworkFactory(Messenger messenger) {
3723 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3724 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003725 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003726 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003727 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003728 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003729 }
3730
Robert Greenwalt7b816022014-04-18 15:25:25 -07003731 /**
3732 * NetworkAgentInfo supporting a request by requestId.
3733 * These have already been vetted (their Capabilities satisfy the request)
3734 * and the are the highest scored network available.
3735 * the are keyed off the Requests requestId.
3736 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003737 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003738 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3739 new SparseArray<NetworkAgentInfo>();
3740
Paul Jensen31a94f42015-02-13 14:18:39 -05003741 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3742 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003743 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3744 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003745 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3746 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3747 // there may not be a strict 1:1 correlation between the two.
3748 @GuardedBy("mNetworkForNetId")
3749 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003750
Robert Greenwalt7b816022014-04-18 15:25:25 -07003751 // NetworkAgentInfo keyed off its connecting messenger
3752 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003753 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003754 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3755 new HashMap<Messenger, NetworkAgentInfo>();
3756
Paul Jensen2c311d62014-11-17 12:34:51 -05003757 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003758 private final NetworkRequest mDefaultRequest;
3759
Erik Klineda4bfa82015-04-30 12:58:40 +09003760 // Request used to optionally keep mobile data active even when higher
3761 // priority networks like Wi-Fi are active.
3762 private final NetworkRequest mDefaultMobileDataRequest;
3763
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003764 private NetworkAgentInfo getDefaultNetwork() {
3765 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3766 }
3767
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003768 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003769 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003770 }
3771
Paul Jensen31a94f42015-02-13 14:18:39 -05003772 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003773 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003774 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003775 enforceConnectivityInternalPermission();
3776
Paul Jensen2c311d62014-11-17 12:34:51 -05003777 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3778 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003779 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003780 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3781 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3782 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003783 synchronized (this) {
3784 nai.networkMonitor.systemReady = mSystemReady;
3785 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003786 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003787 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003788 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003789 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003790 }
3791
3792 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3793 if (VDBG) log("Got NetworkAgent Messenger");
3794 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003795 synchronized (mNetworkForNetId) {
3796 mNetworkForNetId.put(na.network.netId, na);
3797 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003798 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3799 NetworkInfo networkInfo = na.networkInfo;
3800 na.networkInfo = null;
3801 updateNetworkInfo(na, networkInfo);
3802 }
3803
3804 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3805 LinkProperties newLp = networkAgent.linkProperties;
3806 int netId = networkAgent.network.netId;
3807
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003808 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3809 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003810 if (networkAgent.clatd != null) {
3811 networkAgent.clatd.fixupLinkProperties(oldLp);
3812 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003813
Paul Jensen992f2522014-04-28 10:33:11 -04003814 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003815 updateMtu(newLp, oldLp);
3816 // TODO - figure out what to do for clat
3817// for (LinkProperties lp : newLp.getStackedLinks()) {
3818// updateMtu(lp, null);
3819// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003820 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003821
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003822 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3823 // In L, we used it only when the network had Internet access but provided no DNS servers.
3824 // For now, just disable it, and if disabling it doesn't break things, remove it.
3825 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3826 // NET_CAPABILITY_INTERNET);
3827 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003828 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003829 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3830
Paul Jensen3b759822014-05-13 11:44:01 -04003831 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003832 if (isDefaultNetwork(networkAgent)) {
3833 handleApplyDefaultProxy(newLp.getHttpProxy());
3834 } else {
3835 updateProxy(newLp, oldLp, networkAgent);
3836 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003837 // TODO - move this check to cover the whole function
3838 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003839 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003840 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3841 }
Paul Jensen3b759822014-05-13 11:44:01 -04003842 }
3843
Lorenzo Colitti95439462014-10-09 13:44:48 +09003844 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3845 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3846 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003847
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003848 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003849 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3850 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003851 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003852 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003853 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003854 }
Paul Jensen992f2522014-04-28 10:33:11 -04003855
3856 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3857 CompareResult<String> interfaceDiff = new CompareResult<String>();
3858 if (oldLp != null) {
3859 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3860 } else if (newLp != null) {
3861 interfaceDiff.added = newLp.getAllInterfaceNames();
3862 }
3863 for (String iface : interfaceDiff.added) {
3864 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003865 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003866 mNetd.addInterfaceToNetwork(iface, netId);
3867 } catch (Exception e) {
3868 loge("Exception adding interface: " + e);
3869 }
3870 }
3871 for (String iface : interfaceDiff.removed) {
3872 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003873 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003874 mNetd.removeInterfaceFromNetwork(iface, netId);
3875 } catch (Exception e) {
3876 loge("Exception removing interface: " + e);
3877 }
3878 }
3879 }
3880
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003881 /**
3882 * Have netd update routes from oldLp to newLp.
3883 * @return true if routes changed between oldLp and newLp
3884 */
3885 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003886 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3887 if (oldLp != null) {
3888 routeDiff = oldLp.compareAllRoutes(newLp);
3889 } else if (newLp != null) {
3890 routeDiff.added = newLp.getAllRoutes();
3891 }
3892
3893 // add routes before removing old in case it helps with continuous connectivity
3894
3895 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3896 for (RouteInfo route : routeDiff.added) {
3897 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003898 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003899 try {
3900 mNetd.addRoute(netId, route);
3901 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003902 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3903 loge("Exception in addRoute for non-gateway: " + e);
3904 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003905 }
3906 }
3907 for (RouteInfo route : routeDiff.added) {
3908 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003909 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003910 try {
3911 mNetd.addRoute(netId, route);
3912 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003913 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3914 loge("Exception in addRoute for gateway: " + e);
3915 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003916 }
3917 }
3918
3919 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003920 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003921 try {
3922 mNetd.removeRoute(netId, route);
3923 } catch (Exception e) {
3924 loge("Exception in removeRoute: " + e);
3925 }
3926 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003927 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003928 }
Erik Kline41368502015-06-17 13:19:54 +09003929
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003930 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3931 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003932 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09003933 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003934 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003935 dnses = new ArrayList();
3936 dnses.add(mDefaultDns);
3937 if (DBG) {
3938 loge("no dns provided for netId " + netId + ", so using defaults");
3939 }
3940 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003941 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003942 try {
3943 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3944 newLp.getDomains());
3945 } catch (Exception e) {
3946 loge("Exception in setDnsServersForNetwork: " + e);
3947 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003948 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003949 if (defaultNai != null && defaultNai.network.netId == netId) {
3950 setDefaultDnsSystemProperties(dnses);
3951 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003952 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003953 } else if (flush) {
3954 try {
3955 mNetd.flushNetworkDnsCache(netId);
3956 } catch (Exception e) {
3957 loge("Exception in flushNetworkDnsCache: " + e);
3958 }
3959 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003960 }
3961 }
3962
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003963 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3964 int last = 0;
3965 for (InetAddress dns : dnses) {
3966 ++last;
3967 String key = "net.dns" + last;
3968 String value = dns.getHostAddress();
3969 SystemProperties.set(key, value);
3970 }
3971 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3972 String key = "net.dns" + i;
3973 SystemProperties.set(key, "");
3974 }
3975 mNumDnsEntries = last;
3976 }
3977
Paul Jensen3d194ea2015-06-16 14:27:36 -04003978 /**
3979 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
3980 * augmented with any stateful capabilities implied from {@code networkAgent}
3981 * (e.g., validated status and captive portal status).
3982 *
Paul Jensene0988542015-06-25 15:30:08 -04003983 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003984 * @param networkCapabilities the new network capabilities.
3985 */
Paul Jensene0988542015-06-25 15:30:08 -04003986 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04003987 // Don't modify caller's NetworkCapabilities.
3988 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04003989 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04003990 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
3991 } else {
3992 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
3993 }
Paul Jensene0988542015-06-25 15:30:08 -04003994 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04003995 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
3996 } else {
3997 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
3998 }
Paul Jensene0988542015-06-25 15:30:08 -04003999 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4000 final int oldScore = nai.getCurrentScore();
4001 synchronized (nai) {
4002 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004003 }
Paul Jensene0988542015-06-25 15:30:08 -04004004 rematchAllNetworksAndRequests(nai, oldScore);
4005 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004006 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004007 }
4008
Paul Jensenc8b9a742014-09-30 15:37:41 -04004009 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4010 for (int i = 0; i < nai.networkRequests.size(); i++) {
4011 NetworkRequest nr = nai.networkRequests.valueAt(i);
4012 // Don't send listening requests to factories. b/17393458
4013 if (!isRequest(nr)) continue;
4014 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4015 }
4016 }
4017
Robert Greenwalt7b816022014-04-18 15:25:25 -07004018 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4019 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004020 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004021 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4022 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004023 }
4024 }
4025
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004026 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4027 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004028 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004029 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004030 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4031 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004032 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004033 sendIntent(nri.mPendingIntent, intent);
4034 }
4035 // else not handled
4036 }
4037
4038 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4039 mPendingIntentWakeLock.acquire();
4040 try {
4041 if (DBG) log("Sending " + pendingIntent);
4042 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4043 } catch (PendingIntent.CanceledException e) {
4044 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4045 mPendingIntentWakeLock.release();
4046 releasePendingNetworkRequest(pendingIntent);
4047 }
4048 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4049 }
4050
4051 @Override
4052 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4053 String resultData, Bundle resultExtras) {
4054 if (DBG) log("Finished sending " + pendingIntent);
4055 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004056 // Release with a delay so the receiving client has an opportunity to put in its
4057 // own request.
4058 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004059 }
4060
Robert Greenwalt9258c642014-03-26 16:47:06 -07004061 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004062 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004063 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004064 Bundle bundle = new Bundle();
4065 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4066 new NetworkRequest(nri.request));
4067 Message msg = Message.obtain();
4068 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4069 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4070 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4071 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004072 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004073 case ConnectivityManager.CALLBACK_LOSING: {
4074 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4075 break;
4076 }
4077 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4078 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4079 new NetworkCapabilities(networkAgent.networkCapabilities));
4080 break;
4081 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004082 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004083 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4084 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004085 break;
4086 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004087 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004088 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004089 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004090 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004091 if (VDBG) {
4092 log("sending notification " + notifyTypeToName(notificationType) +
4093 " for " + nri.request);
4094 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004095 nri.messenger.send(msg);
4096 } catch (RemoteException e) {
4097 // may occur naturally in the race of binder death.
4098 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4099 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004100 }
4101
Paul Jensenc8b9a742014-09-30 15:37:41 -04004102 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4103 for (int i = 0; i < nai.networkRequests.size(); i++) {
4104 NetworkRequest nr = nai.networkRequests.valueAt(i);
4105 // Ignore listening requests.
4106 if (!isRequest(nr)) continue;
4107 loge("Dead network still had at least " + nr);
4108 break;
4109 }
4110 nai.asyncChannel.disconnect();
4111 }
4112
Robert Greenwalt7b816022014-04-18 15:25:25 -07004113 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4114 if (oldNetwork == null) {
4115 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4116 return;
4117 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004118 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4119 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004120 }
4121
Paul Jensen27b02b72014-07-14 12:03:33 -04004122 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004123 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004124 setupDataActivityTracking(newNetwork);
4125 try {
4126 mNetd.setDefaultNetId(newNetwork.network.netId);
4127 } catch (Exception e) {
4128 loge("Exception setting default network :" + e);
4129 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004130 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004131 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004132 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004133 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004134 }
4135
Paul Jensen2161a8e2014-09-11 11:00:39 -04004136 // Handles a network appearing or improving its score.
4137 //
4138 // - Evaluates all current NetworkRequests that can be
4139 // satisfied by newNetwork, and reassigns to newNetwork
4140 // any such requests for which newNetwork is the best.
4141 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004142 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004143 // needed. A network is needed if it is the best network for
4144 // one or more NetworkRequests, or if it is a VPN.
4145 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004146 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004147 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004148 //
4149 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4150 // networks that have no chance (i.e. even if validated)
4151 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004152 //
4153 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4154 // it does not remove NetworkRequests that other Networks could better satisfy.
4155 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4156 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4157 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004158 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004159 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004160 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4161 // performed to tear down unvalidated networks that have no chance (i.e. even if
4162 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004163 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004164 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004165 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004166 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004167 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004168 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004169 if (DBG) log("rematching " + newNetwork.name());
4170 // Find and migrate to this Network any NetworkRequests for
4171 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004172 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004173 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004174 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004175 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004176 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4177 if (newNetwork == currentNetwork) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004178 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004179 log("Network " + newNetwork.name() + " was already satisfying" +
4180 " request " + nri.request.requestId + ". No change.");
4181 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004182 keep = true;
4183 continue;
4184 }
4185
4186 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004187 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004188 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004189 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004190 // This is not a request, it's a callback listener.
4191 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004192 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004193 continue;
4194 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004195
Robert Greenwalt7b816022014-04-18 15:25:25 -07004196 // next check if it's better than any current network we're using for
4197 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004198 if (VDBG) {
4199 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004200 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4201 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004202 }
4203 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004204 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004205 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004206 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004207 currentNetwork.networkRequests.remove(nri.request.requestId);
4208 currentNetwork.networkLingered.add(nri.request);
4209 affectedNetworks.add(currentNetwork);
4210 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004211 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004212 }
Paul Jensen573a0352015-01-08 10:49:34 -05004213 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004214 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004215 if (!newNetwork.addRequest(nri.request)) {
4216 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4217 }
4218 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004219 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004220 // Tell NetworkFactories about the new score, so they can stop
4221 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004222 // TODO - this could get expensive if we have alot of requests for this
4223 // network. Think about if there is a way to reduce this. Push
4224 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004225 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004226 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004227 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004228 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004229 }
4230 }
4231 }
4232 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004233 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004234 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004235 if (nai.lingering) {
4236 // Already lingered. Nothing to do. This can only happen if "nai" is in
4237 // "affectedNetworks" twice. The reasoning being that to get added to
4238 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4239 // (i.e. not lingered) so it could have only been lingered by this loop.
4240 // unneeded(nai) will be false and we'll call unlinger() below which would
4241 // be bad, so handle it here.
4242 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004243 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004244 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004245 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004246 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004247 }
4248 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004249 if (keep) {
4250 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004251 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004252 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004253 synchronized (ConnectivityService.this) {
4254 // have a new default network, release the transition wakelock in
4255 // a second if it's held. The second pause is to allow apps
4256 // to reconnect over the new network
4257 if (mNetTransitionWakeLock.isHeld()) {
4258 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4259 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4260 mNetTransitionWakeLockSerialNumber, 0),
4261 1000);
4262 }
4263 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004264 }
4265
4266 // do this after the default net is switched, but
4267 // before LegacyTypeTracker sends legacy broadcasts
Paul Jensen3d911462015-06-12 06:40:24 -04004268 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
Robert Greenwalt152ed372014-12-17 17:19:53 -08004269
4270 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004271 // Maintain the illusion: since the legacy API only
4272 // understands one network at a time, we must pretend
4273 // that the current default network disconnected before
4274 // the new one connected.
4275 if (oldDefaultNetwork != null) {
4276 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004277 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004278 }
Paul Jensene0988542015-06-25 15:30:08 -04004279 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004280 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4281 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004282 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004283
4284 // Notify battery stats service about this network, both the normal
4285 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004286 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004287 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004288 final IBatteryStats bs = BatteryStatsService.getService();
4289 final int type = newNetwork.networkInfo.getType();
4290
4291 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4292 bs.noteNetworkInterfaceType(baseIface, type);
4293 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4294 final String stackedIface = stacked.getInterfaceName();
4295 bs.noteNetworkInterfaceType(stackedIface, type);
4296 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4297 }
4298 } catch (RemoteException ignored) {
4299 }
4300
Robert Greenwalt152ed372014-12-17 17:19:53 -08004301 // This has to happen after the notifyNetworkCallbacks as that tickles each
4302 // ConnectivityManager instance so that legacy requests correctly bind dns
4303 // requests to this network. The legacy users are listening for this bcast
4304 // and will generally do a dns request so they can ensureRouteToHost and if
4305 // they do that before the callbacks happen they'll use the default network.
4306 //
4307 // TODO: Is there still a race here? We send the broadcast
4308 // after sending the callback, but if the app can receive the
4309 // broadcast before the callback, it might still break.
4310 //
4311 // This *does* introduce a race where if the user uses the new api
4312 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4313 // they may get old info. Reverse this after the old startUsing api is removed.
4314 // This is on top of the multiple intent sequencing referenced in the todo above.
4315 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4316 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4317 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4318 // legacy type tracker filters out repeat adds
4319 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4320 }
4321 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004322
4323 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4324 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4325 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4326 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4327 if (newNetwork.isVPN()) {
4328 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4329 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004330 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004331 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4332 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004333 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004334 if (DBG) log("Reaping " + nai.name());
4335 teardownUnneededNetwork(nai);
4336 }
4337 }
4338 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004339 }
4340
Paul Jensen1c7ba022015-06-16 14:27:36 -04004341 /**
4342 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4343 * being disconnected.
4344 * @param changed If only one Network's score or capabilities have been modified since the last
4345 * time this function was called, pass this Network in this argument, otherwise pass
4346 * null.
4347 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4348 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4349 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4350 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4351 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004352 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004353 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004354 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4355 // to avoid the slowness. It is not simply enough to process just "changed", for
4356 // example in the case where "changed"'s score decreases and another network should begin
4357 // satifying a NetworkRequest that "changed" currently satisfies.
4358
4359 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4360 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4361 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004362 if (changed != null && oldScore < changed.getCurrentScore()) {
4363 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004364 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004365 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4366 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4367 // Rematch higher scoring networks first to prevent requests first matching a lower
4368 // scoring network and then a higher scoring network, which could produce multiple
4369 // callbacks and inadvertently unlinger networks.
4370 Arrays.sort(nais);
4371 for (NetworkAgentInfo nai : nais) {
4372 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004373 // Only reap the last time through the loop. Reaping before all rematching
4374 // is complete could incorrectly teardown a network that hasn't yet been
4375 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004376 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004377 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004378 }
4379 }
4380 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004381
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004382 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004383 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004384 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004385 // For now only update icons for default connection.
4386 // TODO: Update WiFi and cellular icons separately. b/17237507
4387 if (!isDefaultNetwork(nai)) return;
4388
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004389 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004390 // Don't repeat publish.
4391 if (newInetCondition == mDefaultInetConditionPublished) return;
4392
4393 mDefaultInetConditionPublished = newInetCondition;
4394 sendInetConditionBroadcast(nai.networkInfo);
4395 }
4396
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004397 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4398 if (mLockdownTracker != null) {
4399 if (nai != null && nai.isVPN()) {
4400 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4401 } else {
4402 mLockdownTracker.onNetworkInfoChanged();
4403 }
4404 }
4405 }
4406
Robert Greenwalt7b816022014-04-18 15:25:25 -07004407 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4408 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004409 NetworkInfo oldInfo = null;
4410 synchronized (networkAgent) {
4411 oldInfo = networkAgent.networkInfo;
4412 networkAgent.networkInfo = newInfo;
4413 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004414 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004415
4416 if (oldInfo != null && oldInfo.getState() == state) {
4417 if (VDBG) log("ignoring duplicate network state non-change");
4418 return;
4419 }
4420 if (DBG) {
4421 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4422 (oldInfo == null ? "null" : oldInfo.getState()) +
4423 " to " + state);
4424 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004425
Paul Jenseneec75412014-08-04 12:21:19 -04004426 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004427 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004428 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004429 if (networkAgent.isVPN()) {
4430 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004431 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4432 (networkAgent.networkMisc == null ||
4433 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004434 } else {
4435 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4436 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004437 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004438 loge("Error creating network " + networkAgent.network.netId + ": "
4439 + e.getMessage());
4440 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004441 }
Paul Jenseneec75412014-08-04 12:21:19 -04004442 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004443 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004444 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004445
Paul Jensenca8f16a2014-05-09 12:47:55 -04004446 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004447 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004448
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004449 if (networkAgent.isVPN()) {
4450 // Temporarily disable the default proxy (not global).
4451 synchronized (mProxyLock) {
4452 if (!mDefaultProxyDisabled) {
4453 mDefaultProxyDisabled = true;
4454 if (mGlobalProxy == null && mDefaultProxy != null) {
4455 sendProxyBroadcast(null);
4456 }
4457 }
4458 }
4459 // TODO: support proxy per network.
4460 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004461
Paul Jensen2161a8e2014-09-11 11:00:39 -04004462 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004463 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004464
4465 // This has to happen after matching the requests, because callbacks are just requests.
4466 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004467 } else if (state == NetworkInfo.State.DISCONNECTED ||
4468 state == NetworkInfo.State.SUSPENDED) {
4469 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004470 if (networkAgent.isVPN()) {
4471 synchronized (mProxyLock) {
4472 if (mDefaultProxyDisabled) {
4473 mDefaultProxyDisabled = false;
4474 if (mGlobalProxy == null && mDefaultProxy != null) {
4475 sendProxyBroadcast(mDefaultProxy);
4476 }
4477 }
4478 }
4479 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004480 }
4481 }
4482
Robert Greenwaltac96c522014-06-03 16:43:57 -07004483 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4484 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004485 if (score < 0) {
4486 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4487 "). Bumping score to min of 0");
4488 score = 0;
4489 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004490
Paul Jensen2161a8e2014-09-11 11:00:39 -04004491 final int oldScore = nai.getCurrentScore();
4492 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004493
Paul Jensen85cf78e2015-06-25 13:25:07 -04004494 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004495
Paul Jensenc8b9a742014-09-30 15:37:41 -04004496 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004497 }
4498
Robert Greenwalt9258c642014-03-26 16:47:06 -07004499 // notify only this one new request of the current state
4500 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4501 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4502 // TODO - read state from monitor to decide what to send.
4503// if (nai.networkMonitor.isLingering()) {
4504// notifyType = NetworkCallbacks.LOSING;
4505// } else if (nai.networkMonitor.isEvaluating()) {
4506// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4507// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004508 if (nri.mPendingIntent == null) {
4509 callCallbackForRequest(nri, nai, notifyType);
4510 } else {
4511 sendPendingIntentForRequest(nri, nai, notifyType);
4512 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004513 }
4514
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004515 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004516 // The NetworkInfo we actually send out has no bearing on the real
4517 // state of affairs. For example, if the default connection is mobile,
4518 // and a request for HIPRI has just gone away, we need to pretend that
4519 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4520 // the state to DISCONNECTED, even though the network is of type MOBILE
4521 // and is still connected.
4522 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4523 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004524 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004525 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004526 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004527 } else {
Feixiong Zhang376133f2015-06-01 18:07:58 -07004528 info.setDetailedState(DetailedState.DISCONNECTED, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004529 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4530 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4531 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4532 if (info.isFailover()) {
4533 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4534 nai.networkInfo.setFailover(false);
4535 }
4536 if (info.getReason() != null) {
4537 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4538 }
4539 if (info.getExtraInfo() != null) {
4540 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4541 }
4542 NetworkAgentInfo newDefaultAgent = null;
4543 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004544 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004545 if (newDefaultAgent != null) {
4546 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4547 newDefaultAgent.networkInfo);
4548 } else {
4549 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4550 }
4551 }
4552 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4553 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004554 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004555 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004556 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004557 }
4558 }
4559 }
4560
Robert Greenwalt7b816022014-04-18 15:25:25 -07004561 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004562 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004563 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004564 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4565 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4566 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004567 if (nri.mPendingIntent == null) {
4568 callCallbackForRequest(nri, networkAgent, notifyType);
4569 } else {
4570 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4571 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004572 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004573 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004574
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004575 private String notifyTypeToName(int notifyType) {
4576 switch (notifyType) {
4577 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4578 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4579 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4580 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4581 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4582 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4583 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4584 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4585 }
4586 return "UNKNOWN";
4587 }
4588
Jeff Sharkey69736342014-12-08 14:50:12 -08004589 /**
4590 * Notify other system services that set of active ifaces has changed.
4591 */
4592 private void notifyIfacesChanged() {
4593 try {
4594 mStatsService.forceUpdateIfaces();
4595 } catch (Exception ignored) {
4596 }
4597 }
4598
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004599 @Override
4600 public boolean addVpnAddress(String address, int prefixLength) {
4601 throwIfLockdownEnabled();
4602 int user = UserHandle.getUserId(Binder.getCallingUid());
4603 synchronized (mVpns) {
4604 return mVpns.get(user).addAddress(address, prefixLength);
4605 }
4606 }
4607
4608 @Override
4609 public boolean removeVpnAddress(String address, int prefixLength) {
4610 throwIfLockdownEnabled();
4611 int user = UserHandle.getUserId(Binder.getCallingUid());
4612 synchronized (mVpns) {
4613 return mVpns.get(user).removeAddress(address, prefixLength);
4614 }
4615 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004616
4617 @Override
4618 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4619 throwIfLockdownEnabled();
4620 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004621 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004622 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004623 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004624 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004625 if (success) {
4626 notifyIfacesChanged();
4627 }
4628 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004629 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004630
4631 @Override
4632 public void factoryReset() {
4633 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004634
4635 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4636 return;
4637 }
4638
Robin Lee3b3dd942015-05-12 18:14:58 +01004639 final int userId = UserHandle.getCallingUserId();
4640
Stuart Scottf1fb3972015-04-02 18:00:02 -07004641 // Turn airplane mode off
4642 setAirplaneMode(false);
4643
Stuart Scotte3e314d2015-04-20 14:07:45 -07004644 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4645 // Untether
4646 for (String tether : getTetheredIfaces()) {
4647 untether(tether);
4648 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004649 }
4650
Stuart Scotte3e314d2015-04-20 14:07:45 -07004651 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4652 // Turn VPN off
4653 VpnConfig vpnConfig = getVpnConfig(userId);
4654 if (vpnConfig != null) {
4655 if (vpnConfig.legacy) {
4656 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4657 } else {
4658 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4659 // in the future without user intervention.
4660 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004661
Stuart Scotte3e314d2015-04-20 14:07:45 -07004662 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4663 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004664 }
4665 }
4666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004667}