blob: 6878caf976c1fc837ab7ae068978ca1892fedf6d [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 Jensen85cf78e2015-06-25 13:25:07 -04002050 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002051 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002052 // If network has never been validated, it cannot have been lingered, so don't bother
2053 // needlessly triggering a re-evaluation.
2054 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002055 nai.networkLingered.clear();
2056 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2057 }
2058
Robert Greenwalt7b816022014-04-18 15:25:25 -07002059 private void handleAsyncChannelHalfConnect(Message msg) {
2060 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002061 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002062 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2063 if (VDBG) log("NetworkFactory connected");
2064 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002065 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002066 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002067 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002068 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002069 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002070 }
2071 } else {
2072 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002073 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002074 }
2075 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2076 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2077 if (VDBG) log("NetworkAgent connected");
2078 // A network agent has requested a connection. Establish the connection.
2079 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2080 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2081 } else {
2082 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002083 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002084 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002085 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002086 synchronized (mNetworkForNetId) {
2087 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002088 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002089 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002090 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002091 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002092 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002093 }
2094 }
2095 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002096
Robert Greenwalt7b816022014-04-18 15:25:25 -07002097 private void handleAsyncChannelDisconnected(Message msg) {
2098 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2099 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002100 if (DBG) {
2101 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2102 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002103 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002104 // TODO - if we move the logic to the network agent (have them disconnect
2105 // because they lost all their requests or because their score isn't good)
2106 // then they would disconnect organically, report their new state and then
2107 // disconnect the channel.
2108 if (nai.networkInfo.isConnected()) {
2109 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2110 null, null);
2111 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002112 final boolean wasDefault = isDefaultNetwork(nai);
2113 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002114 mDefaultInetConditionPublished = 0;
2115 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002116 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002117 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002118 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002119 mNetworkAgentInfos.remove(msg.replyTo);
2120 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002121 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002122 // Remove the NetworkAgent, but don't mark the netId as
2123 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002124 mNetworkForNetId.remove(nai.network.netId);
2125 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002126 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002127 for (int i = 0; i < nai.networkRequests.size(); i++) {
2128 NetworkRequest request = nai.networkRequests.valueAt(i);
2129 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2130 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2131 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 sendUpdatedScoreToFactories(request, 0);
2133 }
2134 }
2135 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2136 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002137 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002138 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002140 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002141 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002142 if (nai.created) {
2143 // Tell netd to clean up the configuration for this network
2144 // (routing rules, DNS, etc).
2145 // This may be slow as it requires a lot of netd shelling out to ip and
2146 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2147 // after we've rematched networks with requests which should make a potential
2148 // fallback network the default or requested a new network from the
2149 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2150 // long time.
2151 try {
2152 mNetd.removeNetwork(nai.network.netId);
2153 } catch (Exception e) {
2154 loge("Exception removing network: " + e);
2155 }
2156 }
2157 synchronized (mNetworkForNetId) {
2158 mNetIdInUse.delete(nai.network.netId);
2159 }
2160 } else {
2161 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2162 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002163 }
2164 }
2165
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002166 // If this method proves to be too slow then we can maintain a separate
2167 // pendingIntent => NetworkRequestInfo map.
2168 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2169 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2170 Intent intent = pendingIntent.getIntent();
2171 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2172 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2173 if (existingPendingIntent != null &&
2174 existingPendingIntent.getIntent().filterEquals(intent)) {
2175 return entry.getValue();
2176 }
2177 }
2178 return null;
2179 }
2180
2181 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2182 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2183
2184 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2185 if (existingRequest != null) { // remove the existing request.
2186 if (DBG) log("Replacing " + existingRequest.request + " with "
2187 + nri.request + " because their intents matched.");
2188 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2189 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002190 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002191 }
2192
Erik Klineda4bfa82015-04-30 12:58:40 +09002193 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002194 mNetworkRequests.put(nri.request, nri);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002195 rematchAllNetworksAndRequests(null, 0);
2196 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2197 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002198 }
2199 }
2200
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002201 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2202 int callingUid) {
2203 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2204 if (nri != null) {
2205 handleReleaseNetworkRequest(nri.request, callingUid);
2206 }
2207 }
2208
Paul Jensen99364842014-12-09 11:43:45 -05002209 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2210 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2211 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2212 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2213 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002214 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensen99364842014-12-09 11:43:45 -05002215 boolean unneeded = true;
2216 if (nai.everValidated) {
2217 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2218 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2219 try {
2220 if (isRequest(nr)) unneeded = false;
2221 } catch (Exception e) {
2222 loge("Request " + nr + " not found in mNetworkRequests.");
2223 loge(" it came from request list of " + nai.name());
2224 }
2225 }
2226 } else {
2227 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2228 // If this Network is already the highest scoring Network for a request, or if
2229 // there is hope for it to become one if it validated, then it is needed.
2230 if (nri.isRequest && nai.satisfies(nri.request) &&
2231 (nai.networkRequests.get(nri.request.requestId) != null ||
2232 // Note that this catches two important cases:
2233 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2234 // is currently satisfying the request. This is desirable when
2235 // cellular ends up validating but WiFi does not.
2236 // 2. Unvalidated WiFi will not be reaped when validated cellular
2237 // is currently satsifying the request. This is desirable when
2238 // WiFi ends up validating and out scoring cellular.
2239 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2240 nai.getCurrentScoreAsValidated())) {
2241 unneeded = false;
2242 break;
2243 }
2244 }
2245 }
2246 return unneeded;
2247 }
2248
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002249 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2250 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002251 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002252 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002253 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2254 return;
2255 }
2256 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002257 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002258 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002259 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002260 // Find all networks that are satisfying this request and remove the request
2261 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002262 // TODO - it's my understanding that for a request there is only a single
2263 // network satisfying it, so this loop is wasteful
2264 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002265 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2266 if (nai.networkRequests.get(nri.request.requestId) != null) {
2267 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002268 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002269 log(" Removing from current network " + nai.name() +
2270 ", leaving " + nai.networkRequests.size() +
2271 " requests.");
2272 }
Paul Jensen99364842014-12-09 11:43:45 -05002273 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002274 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002275 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002276 } else {
2277 // suspect there should only be one pass through here
2278 // but if any were kept do the check below
2279 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002280 }
2281 }
2282 }
2283
Robert Greenwalt51481852015-01-08 14:43:31 -08002284 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2285 if (nai != null) {
2286 mNetworkForRequestId.remove(nri.request.requestId);
2287 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002288 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002289 // that a network connected to serve it, even though the network was already
2290 // connected. Now that this request has gone away, we might have to pretend
2291 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002292 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002293 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2294 boolean doRemove = true;
2295 if (wasKept) {
2296 // check if any of the remaining requests for this network are for the
2297 // same legacy type - if so, don't remove the nai
2298 for (int i = 0; i < nai.networkRequests.size(); i++) {
2299 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2300 if (otherRequest.legacyType == nri.request.legacyType &&
2301 isRequest(otherRequest)) {
2302 if (DBG) log(" still have other legacy request - leaving");
2303 doRemove = false;
2304 }
2305 }
2306 }
2307
2308 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002309 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002310 }
2311 }
2312
Robert Greenwalta67be032014-05-16 15:49:14 -07002313 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002314 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2315 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002316 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002317 } else {
2318 // listens don't have a singular affectedNetwork. Check all networks to see
2319 // if this listen request applies and remove it.
2320 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2321 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002322 }
2323 }
2324 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2325 }
2326 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002327
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002328 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2329 enforceConnectivityInternalPermission();
2330 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2331 accept ? 1 : 0, always ? 1: 0, network));
2332 }
2333
2334 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2335 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2336 " accept=" + accept + " always=" + always);
2337
2338 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2339 if (nai == null) {
2340 // Nothing to do.
2341 return;
2342 }
2343
2344 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002345 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002346 return;
2347 }
2348
2349 if (!nai.networkMisc.explicitlySelected) {
2350 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2351 }
2352
2353 if (accept != nai.networkMisc.acceptUnvalidated) {
2354 int oldScore = nai.getCurrentScore();
2355 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002356 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002357 sendUpdatedScoreToFactories(nai);
2358 }
2359
2360 if (always) {
2361 nai.asyncChannel.sendMessage(
2362 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2363 }
2364
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002365 if (!accept) {
2366 // Tell the NetworkAgent that the network does not have Internet access (because that's
2367 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2368 // the future. We do this now because NetworkMonitor might not yet have finished
2369 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2370 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2371 NetworkAgent.INVALID_NETWORK, 0, null);
2372 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2373 // to reconnect to it immediately. http://b/20739299
2374 }
2375
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002376 }
2377
2378 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002379 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002380 mHandler.sendMessageDelayed(
2381 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2382 PROMPT_UNVALIDATED_DELAY_MS);
2383 }
2384
2385 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002386 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002387 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2388
2389 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2390 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002391 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002392 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002393 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2394 return;
2395 }
2396
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002397 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002398 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002399 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2400 intent.setClassName("com.android.settings",
2401 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002402
2403 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2404 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2405 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002406 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002407 }
2408
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002409 private class InternalHandler extends Handler {
2410 public InternalHandler(Looper looper) {
2411 super(looper);
2412 }
2413
2414 @Override
2415 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002416 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002417 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002418 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002419 String causedBy = null;
2420 synchronized (ConnectivityService.this) {
2421 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2422 mNetTransitionWakeLock.isHeld()) {
2423 mNetTransitionWakeLock.release();
2424 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002425 } else {
2426 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002427 }
2428 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002429 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2430 log("Failed to find a new network - expiring NetTransition Wakelock");
2431 } else {
2432 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2433 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002434 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002435 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002436 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002437 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002438 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002439 break;
2440 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002441 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002442 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002443 sendStickyBroadcast(intent);
2444 break;
2445 }
Jason Monkdecd2952013-10-10 14:02:51 -04002446 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002447 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002448 break;
2449 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002450 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002451 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2452 break;
2453 }
2454 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2455 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002456 break;
2457 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002458 case EVENT_REGISTER_NETWORK_AGENT: {
2459 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2460 break;
2461 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002462 case EVENT_REGISTER_NETWORK_REQUEST:
2463 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002464 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002465 break;
2466 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002467 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2468 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002469 handleRegisterNetworkRequestWithIntent(msg);
2470 break;
2471 }
2472 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2473 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2474 break;
2475 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002476 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002477 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002478 break;
2479 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002480 case EVENT_SET_ACCEPT_UNVALIDATED: {
2481 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2482 break;
2483 }
2484 case EVENT_PROMPT_UNVALIDATED: {
2485 handlePromptUnvalidated((Network) msg.obj);
2486 break;
2487 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002488 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2489 handleMobileDataAlwaysOn();
2490 break;
2491 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002492 case EVENT_SYSTEM_READY: {
2493 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2494 nai.networkMonitor.systemReady = true;
2495 }
2496 break;
2497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 }
2499 }
2500 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002501
2502 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002503 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002504 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002505 if (isTetheringSupported()) {
2506 return mTethering.tether(iface);
2507 } else {
2508 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2509 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002510 }
2511
2512 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002513 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002514 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002515
2516 if (isTetheringSupported()) {
2517 return mTethering.untether(iface);
2518 } else {
2519 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2520 }
2521 }
2522
2523 // javadoc from interface
2524 public int getLastTetherError(String iface) {
2525 enforceTetherAccessPermission();
2526
2527 if (isTetheringSupported()) {
2528 return mTethering.getLastTetherError(iface);
2529 } else {
2530 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2531 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002532 }
2533
2534 // TODO - proper iface API for selection by property, inspection, etc
2535 public String[] getTetherableUsbRegexs() {
2536 enforceTetherAccessPermission();
2537 if (isTetheringSupported()) {
2538 return mTethering.getTetherableUsbRegexs();
2539 } else {
2540 return new String[0];
2541 }
2542 }
2543
2544 public String[] getTetherableWifiRegexs() {
2545 enforceTetherAccessPermission();
2546 if (isTetheringSupported()) {
2547 return mTethering.getTetherableWifiRegexs();
2548 } else {
2549 return new String[0];
2550 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002551 }
2552
Danica Chang6fdd0c62010-08-11 14:54:43 -07002553 public String[] getTetherableBluetoothRegexs() {
2554 enforceTetherAccessPermission();
2555 if (isTetheringSupported()) {
2556 return mTethering.getTetherableBluetoothRegexs();
2557 } else {
2558 return new String[0];
2559 }
2560 }
2561
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002562 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002563 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002564 if (isTetheringSupported()) {
2565 return mTethering.setUsbTethering(enable);
2566 } else {
2567 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2568 }
2569 }
2570
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002571 // TODO - move iface listing, queries, etc to new module
2572 // javadoc from interface
2573 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002574 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002575 return mTethering.getTetherableIfaces();
2576 }
2577
2578 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002579 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002580 return mTethering.getTetheredIfaces();
2581 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002582
Robert Greenwalt5a735062010-03-02 17:25:02 -08002583 public String[] getTetheringErroredIfaces() {
2584 enforceTetherAccessPermission();
2585 return mTethering.getErroredIfaces();
2586 }
2587
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002588 public String[] getTetheredDhcpRanges() {
2589 enforceConnectivityInternalPermission();
2590 return mTethering.getTetheredDhcpRanges();
2591 }
2592
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002593 // if ro.tether.denied = true we default to no tethering
2594 // gservices could set the secure setting to 1 though to enable it on a build where it
2595 // had previously been turned off.
2596 public boolean isTetheringSupported() {
2597 enforceTetherAccessPermission();
2598 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002599 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002600 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2601 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002602 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2603 mTethering.getTetherableWifiRegexs().length != 0 ||
2604 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2605 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002606 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002607
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002608 // Called when we lose the default network and have no replacement yet.
2609 // This will automatically be cleared after X seconds or a new default network
2610 // becomes CONNECTED, whichever happens first. The timer is started by the
2611 // first caller and not restarted by subsequent callers.
2612 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002613 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002614 synchronized (this) {
2615 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002616 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002617 mNetTransitionWakeLock.acquire();
2618 mNetTransitionWakeLockCausedBy = forWhom;
2619 }
2620 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002621 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002622 mNetTransitionWakeLockTimeout);
2623 return;
2624 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002625
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002626 // 100 percent is full good, 0 is full bad.
2627 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002628 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002629 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002630 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002631 }
2632
Paul Jensenbfd17b72015-04-07 12:43:13 -04002633 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002634 enforceAccessPermission();
2635 enforceInternetPermission();
2636
Paul Jensenbfd17b72015-04-07 12:43:13 -04002637 NetworkAgentInfo nai;
2638 if (network == null) {
2639 nai = getDefaultNetwork();
2640 } else {
2641 nai = getNetworkAgentInfoForNetwork(network);
2642 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002643 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2644 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2645 return;
2646 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002647 // Revalidate if the app report does not match our current validated state.
2648 if (hasConnectivity == nai.lastValidated) return;
2649 final int uid = Binder.getCallingUid();
2650 if (DBG) {
2651 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2652 ") by " + uid);
2653 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002654 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002655 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2656 // which isn't meant to work on uncreated networks.
2657 if (!nai.created) return;
2658
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002659 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002660
2661 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2662 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002663 }
2664
Paul Jensen25a217c2015-02-27 22:55:47 -05002665 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2666 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2667 enforceConnectivityInternalPermission();
2668 }
2669 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2670 if (nai == null) return;
2671 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2672 actionToken);
2673 }
2674
Paul Jensencee9b512015-05-06 07:32:40 -04002675 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002676 // this information is already available as a world read/writable jvm property
2677 // so this API change wouldn't have a benifit. It also breaks the passing
2678 // of proxy info to all the JVMs.
2679 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002680 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002681 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002682 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2683 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002684 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002685 }
2686
Paul Jensencee9b512015-05-06 07:32:40 -04002687 public ProxyInfo getProxyForNetwork(Network network) {
2688 if (network == null) return getDefaultProxy();
2689 final ProxyInfo globalProxy = getGlobalProxy();
2690 if (globalProxy != null) return globalProxy;
2691 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2692 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2693 // caller may not have.
2694 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2695 if (nai == null) return null;
2696 synchronized (nai) {
2697 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2698 if (proxyInfo == null) return null;
2699 return new ProxyInfo(proxyInfo);
2700 }
2701 }
2702
Paul Jensene0bef712014-12-10 15:12:18 -05002703 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2704 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2705 // proxy is null then there is no proxy in place).
2706 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2707 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2708 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2709 proxy = null;
2710 }
2711 return proxy;
2712 }
2713
2714 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2715 // better for determining if a new proxy broadcast is necessary:
2716 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2717 // avoid unnecessary broadcasts.
2718 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2719 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2720 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2721 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2722 // all set.
2723 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2724 a = canonicalizeProxyInfo(a);
2725 b = canonicalizeProxyInfo(b);
2726 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2727 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2728 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2729 }
2730
Jason Monk207900c2014-04-25 15:00:09 -04002731 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002732 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002733
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002734 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002735 if (proxyProperties == mGlobalProxy) return;
2736 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2737 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2738
2739 String host = "";
2740 int port = 0;
2741 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002742 String pacFileUrl = "";
2743 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002744 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002745 if (!proxyProperties.isValid()) {
2746 if (DBG)
2747 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2748 return;
2749 }
Jason Monk207900c2014-04-25 15:00:09 -04002750 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002751 host = mGlobalProxy.getHost();
2752 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002753 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002754 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002755 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002756 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002757 } else {
2758 mGlobalProxy = null;
2759 }
2760 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002761 final long token = Binder.clearCallingIdentity();
2762 try {
2763 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2764 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2765 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2766 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002767 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002768 } finally {
2769 Binder.restoreCallingIdentity(token);
2770 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002771
Jason Monkcf0f97a2014-10-02 15:39:38 -04002772 if (mGlobalProxy == null) {
2773 proxyProperties = mDefaultProxy;
2774 }
2775 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002776 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002777 }
2778
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002779 private void loadGlobalProxy() {
2780 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002781 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2782 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2783 String exclList = Settings.Global.getString(res,
2784 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002785 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2786 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002787 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002788 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002789 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002790 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002791 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002792 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002793 if (!proxyProperties.isValid()) {
2794 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2795 return;
2796 }
2797
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002798 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002799 mGlobalProxy = proxyProperties;
2800 }
2801 }
2802 }
2803
Jason Monk207900c2014-04-25 15:00:09 -04002804 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002805 // this information is already available as a world read/writable jvm property
2806 // so this API change wouldn't have a benifit. It also breaks the passing
2807 // of proxy info to all the JVMs.
2808 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002809 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002810 return mGlobalProxy;
2811 }
2812 }
2813
Jason Monk207900c2014-04-25 15:00:09 -04002814 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002815 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002816 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002817 proxy = null;
2818 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002819 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002820 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002821 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002822 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002823 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2824 return;
2825 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002826
2827 // This call could be coming from the PacManager, containing the port of the local
2828 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2829 // global (to get the correct local port), and send a broadcast.
2830 // TODO: Switch PacManager to have its own message to send back rather than
2831 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002832 if ((mGlobalProxy != null) && (proxy != null)
2833 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002834 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2835 mGlobalProxy = proxy;
2836 sendProxyBroadcast(mGlobalProxy);
2837 return;
2838 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002839 mDefaultProxy = proxy;
2840
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002841 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002842 if (!mDefaultProxyDisabled) {
2843 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002844 }
2845 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002846 }
2847
Paul Jensene0bef712014-12-10 15:12:18 -05002848 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2849 // This method gets called when any network changes proxy, but the broadcast only ever contains
2850 // the default proxy (even if it hasn't changed).
2851 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2852 // world where an app might be bound to a non-default network.
2853 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2854 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2855 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2856
2857 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2858 sendProxyBroadcast(getDefaultProxy());
2859 }
2860 }
2861
Robert Greenwalt434203a2010-10-11 16:00:27 -07002862 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002863 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2864 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002865 if (!TextUtils.isEmpty(proxy)) {
2866 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002867 if (data.length == 0) {
2868 return;
2869 }
2870
Robert Greenwalt434203a2010-10-11 16:00:27 -07002871 String proxyHost = data[0];
2872 int proxyPort = 8080;
2873 if (data.length > 1) {
2874 try {
2875 proxyPort = Integer.parseInt(data[1]);
2876 } catch (NumberFormatException e) {
2877 return;
2878 }
2879 }
Jason Monk207900c2014-04-25 15:00:09 -04002880 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002881 setGlobalProxy(p);
2882 }
2883 }
2884
Jason Monk207900c2014-04-25 15:00:09 -04002885 private void sendProxyBroadcast(ProxyInfo proxy) {
2886 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002887 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002888 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002889 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002890 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2891 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002892 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002893 final long ident = Binder.clearCallingIdentity();
2894 try {
2895 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2896 } finally {
2897 Binder.restoreCallingIdentity(ident);
2898 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002899 }
2900
2901 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002902 final private HashMap<Uri, Integer> mUriEventMap;
2903 final private Context mContext;
2904 final private Handler mHandler;
2905
2906 SettingsObserver(Context context, Handler handler) {
2907 super(null);
2908 mUriEventMap = new HashMap<Uri, Integer>();
2909 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002910 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002911 }
2912
Erik Klineda4bfa82015-04-30 12:58:40 +09002913 void observe(Uri uri, int what) {
2914 mUriEventMap.put(uri, what);
2915 final ContentResolver resolver = mContext.getContentResolver();
2916 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002917 }
2918
2919 @Override
2920 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002921 Slog.wtf(TAG, "Should never be reached.");
2922 }
2923
2924 @Override
2925 public void onChange(boolean selfChange, Uri uri) {
2926 final Integer what = mUriEventMap.get(uri);
2927 if (what != null) {
2928 mHandler.obtainMessage(what.intValue()).sendToTarget();
2929 } else {
2930 loge("No matching event to send for URI=" + uri);
2931 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002932 }
2933 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002934
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002935 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002936 Slog.d(TAG, s);
2937 }
2938
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002939 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002940 Slog.e(TAG, s);
2941 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002942
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002943 private static <T> T checkNotNull(T value, String message) {
2944 if (value == null) {
2945 throw new NullPointerException(message);
2946 }
2947 return value;
2948 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002949
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002950 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002951 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002952 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2953 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2954 *
2955 * @param oldPackage Package name of the application which currently controls VPN, which will
2956 * be replaced. If there is no such application, this should should either be
2957 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2958 * @param newPackage Package name of the application which should gain control of VPN, or
2959 * {@code null} to disable.
2960 * @param userId User for whom to prepare the new VPN.
2961 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002962 * @hide
2963 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002964 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002965 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2966 int userId) {
2967 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002968 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01002969
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002970 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07002971 Vpn vpn = mVpns.get(userId);
2972 if (vpn != null) {
2973 return vpn.prepare(oldPackage, newPackage);
2974 } else {
2975 return false;
2976 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002977 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002978 }
2979
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002980 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01002981 * Set whether the VPN package has the ability to launch VPNs without user intervention.
2982 * This method is used by system-privileged apps.
2983 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2984 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2985 *
2986 * @param packageName The package for which authorization state should change.
2987 * @param userId User for whom {@code packageName} is installed.
2988 * @param authorized {@code true} if this app should be able to start a VPN connection without
2989 * explicit user approval, {@code false} if not.
2990 *
Jeff Davidson05542602014-08-11 14:07:27 -07002991 * @hide
2992 */
2993 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002994 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
2995 enforceCrossUserPermission(userId);
2996
Jeff Davidson05542602014-08-11 14:07:27 -07002997 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07002998 Vpn vpn = mVpns.get(userId);
2999 if (vpn != null) {
3000 vpn.setPackageAuthorization(packageName, authorized);
3001 }
Jeff Davidson05542602014-08-11 14:07:27 -07003002 }
3003 }
3004
3005 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003006 * Configure a TUN interface and return its file descriptor. Parameters
3007 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003008 * and not available in ConnectivityManager. Permissions are checked in
3009 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003010 * @hide
3011 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003012 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003013 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003014 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003015 int user = UserHandle.getUserId(Binder.getCallingUid());
3016 synchronized(mVpns) {
3017 return mVpns.get(user).establish(config);
3018 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003019 }
3020
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003021 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003022 * Start legacy VPN, controlling native daemons as needed. Creates a
3023 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003024 */
3025 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003026 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003027 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003028 final LinkProperties egress = getActiveLinkProperties();
3029 if (egress == null) {
3030 throw new IllegalStateException("Missing active network connection");
3031 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003032 int user = UserHandle.getUserId(Binder.getCallingUid());
3033 synchronized(mVpns) {
3034 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3035 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003036 }
3037
3038 /**
3039 * Return the information of the ongoing legacy VPN. This method is used
3040 * by VpnSettings and not available in ConnectivityManager. Permissions
3041 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003042 */
3043 @Override
3044 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003045 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003046 int user = UserHandle.getUserId(Binder.getCallingUid());
3047 synchronized(mVpns) {
3048 return mVpns.get(user).getLegacyVpnInfo();
3049 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003050 }
3051
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003052 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003053 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3054 * and not available in ConnectivityManager.
3055 */
3056 @Override
3057 public VpnInfo[] getAllVpnInfo() {
3058 enforceConnectivityInternalPermission();
3059 if (mLockdownEnabled) {
3060 return new VpnInfo[0];
3061 }
3062
3063 synchronized(mVpns) {
3064 List<VpnInfo> infoList = new ArrayList<>();
3065 for (int i = 0; i < mVpns.size(); i++) {
3066 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3067 if (info != null) {
3068 infoList.add(info);
3069 }
3070 }
3071 return infoList.toArray(new VpnInfo[infoList.size()]);
3072 }
3073 }
3074
3075 /**
3076 * @return VPN information for accounting, or null if we can't retrieve all required
3077 * information, e.g primary underlying iface.
3078 */
3079 @Nullable
3080 private VpnInfo createVpnInfo(Vpn vpn) {
3081 VpnInfo info = vpn.getVpnInfo();
3082 if (info == null) {
3083 return null;
3084 }
3085 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3086 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3087 // the underlyingNetworks list.
3088 if (underlyingNetworks == null) {
3089 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3090 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3091 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3092 }
3093 } else if (underlyingNetworks.length > 0) {
3094 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3095 if (linkProperties != null) {
3096 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3097 }
3098 }
3099 return info.primaryUnderlyingIface == null ? null : info;
3100 }
3101
3102 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003103 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3104 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003105 * Permissions are checked in Vpn class.
3106 * @hide
3107 */
3108 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003109 public VpnConfig getVpnConfig(int userId) {
3110 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003111 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003112 Vpn vpn = mVpns.get(userId);
3113 if (vpn != null) {
3114 return vpn.getVpnConfig();
3115 } else {
3116 return null;
3117 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003118 }
3119 }
3120
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003121 @Override
3122 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003123 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3124 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3125 return false;
3126 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003127
3128 // Tear down existing lockdown if profile was removed
3129 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3130 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003131 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003132 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3133 return false;
3134 }
3135
3136 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3137 final VpnProfile profile = VpnProfile.decode(
3138 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003139 int user = UserHandle.getUserId(Binder.getCallingUid());
3140 synchronized(mVpns) {
3141 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3142 profile));
3143 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003144 } else {
3145 setLockdownTracker(null);
3146 }
3147
3148 return true;
3149 }
3150
3151 /**
3152 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3153 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3154 */
3155 private void setLockdownTracker(LockdownVpnTracker tracker) {
3156 // Shutdown any existing tracker
3157 final LockdownVpnTracker existing = mLockdownTracker;
3158 mLockdownTracker = null;
3159 if (existing != null) {
3160 existing.shutdown();
3161 }
3162
3163 try {
3164 if (tracker != null) {
3165 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003166 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003167 mLockdownTracker = tracker;
3168 mLockdownTracker.init();
3169 } else {
3170 mNetd.setFirewallEnabled(false);
3171 }
3172 } catch (RemoteException e) {
3173 // ignored; NMS lives inside system_server
3174 }
3175 }
3176
3177 private void throwIfLockdownEnabled() {
3178 if (mLockdownEnabled) {
3179 throw new IllegalStateException("Unavailable in lockdown mode");
3180 }
3181 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003182
Wink Savilleab9321d2013-06-29 21:10:57 -07003183 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003184 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003185 // TODO: Remove? Any reason to trigger a provisioning check?
3186 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003187 }
3188
3189 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003190 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003191
Paul Jensen89e0f092014-09-15 15:59:36 -04003192 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003193 if (DBG) {
3194 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003195 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003196 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003197 Intent intent = new Intent(action);
3198 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003199 // Concatenate the range of types onto the range of NetIDs.
3200 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003201 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003202 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003203 }
3204
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003205 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003206 * Show or hide network provisioning notifications.
3207 *
3208 * We use notifications for two purposes: to notify that a network requires sign in
3209 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3210 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3211 * particular network we can display the notification type that was most recently requested.
3212 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3213 * might first display NO_INTERNET, and then when the captive portal check completes, display
3214 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003215 *
3216 * @param id an identifier that uniquely identifies this notification. This must match
3217 * between show and hide calls. We use the NetID value but for legacy callers
3218 * we concatenate the range of types with the range of NetIDs.
3219 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003220 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003221 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3222 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003223 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003224 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3225 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003226 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003227 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003228
3229 Resources r = Resources.getSystem();
3230 NotificationManager notificationManager = (NotificationManager) mContext
3231 .getSystemService(Context.NOTIFICATION_SERVICE);
3232
3233 if (visible) {
3234 CharSequence title;
3235 CharSequence details;
3236 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003237 if (notifyType == NotificationType.NO_INTERNET &&
3238 networkType == ConnectivityManager.TYPE_WIFI) {
3239 title = r.getString(R.string.wifi_no_internet, 0);
3240 details = r.getString(R.string.wifi_no_internet_detailed);
3241 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3242 } else if (notifyType == NotificationType.SIGN_IN) {
3243 switch (networkType) {
3244 case ConnectivityManager.TYPE_WIFI:
3245 title = r.getString(R.string.wifi_available_sign_in, 0);
3246 details = r.getString(R.string.network_available_sign_in_detailed,
3247 extraInfo);
3248 icon = R.drawable.stat_notify_wifi_in_range;
3249 break;
3250 case ConnectivityManager.TYPE_MOBILE:
3251 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3252 title = r.getString(R.string.network_available_sign_in, 0);
3253 // TODO: Change this to pull from NetworkInfo once a printable
3254 // name has been added to it
3255 details = mTelephonyManager.getNetworkOperatorName();
3256 icon = R.drawable.stat_notify_rssi_in_range;
3257 break;
3258 default:
3259 title = r.getString(R.string.network_available_sign_in, 0);
3260 details = r.getString(R.string.network_available_sign_in_detailed,
3261 extraInfo);
3262 icon = R.drawable.stat_notify_rssi_in_range;
3263 break;
3264 }
3265 } else {
3266 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3267 + getNetworkTypeName(networkType));
3268 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003269 }
3270
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003271 Notification notification = new Notification.Builder(mContext)
3272 .setWhen(0)
3273 .setSmallIcon(icon)
3274 .setAutoCancel(true)
3275 .setTicker(title)
3276 .setColor(mContext.getColor(
3277 com.android.internal.R.color.system_notification_accent_color))
3278 .setContentTitle(title)
3279 .setContentText(details)
3280 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003281 .setLocalOnly(true)
3282 .setPriority(highPriority ?
3283 Notification.PRIORITY_HIGH :
3284 Notification.PRIORITY_DEFAULT)
3285 .setDefaults(Notification.DEFAULT_ALL)
3286 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003287 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003288
Wink Saville948282b2013-08-29 08:55:16 -07003289 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003290 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003291 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003292 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003293 npe.printStackTrace();
3294 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003295 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003296 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003297 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003298 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003299 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003300 npe.printStackTrace();
3301 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003302 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003303 }
3304
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003305 /** Location to an updatable file listing carrier provisioning urls.
3306 * An example:
3307 *
3308 * <?xml version="1.0" encoding="utf-8"?>
3309 * <provisioningUrls>
3310 * <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 -07003311 * </provisioningUrls>
3312 */
3313 private static final String PROVISIONING_URL_PATH =
3314 "/data/misc/radio/provisioning_urls.xml";
3315 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003316
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003317 /** XML tag for root element. */
3318 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3319 /** XML tag for individual url */
3320 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003321 /** XML attribute for mcc */
3322 private static final String ATTR_MCC = "mcc";
3323 /** XML attribute for mnc */
3324 private static final String ATTR_MNC = "mnc";
3325
Paul Jensen434dde82015-06-11 09:43:30 -04003326 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003327 FileReader fileReader = null;
3328 XmlPullParser parser = null;
3329 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003330
3331 try {
3332 fileReader = new FileReader(mProvisioningUrlFile);
3333 parser = Xml.newPullParser();
3334 parser.setInput(fileReader);
3335 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3336
3337 while (true) {
3338 XmlUtils.nextElement(parser);
3339
3340 String element = parser.getName();
3341 if (element == null) break;
3342
Paul Jensen434dde82015-06-11 09:43:30 -04003343 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003344 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3345 try {
3346 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3347 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3348 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3349 parser.next();
3350 if (parser.getEventType() == XmlPullParser.TEXT) {
3351 return parser.getText();
3352 }
3353 }
3354 }
3355 } catch (NumberFormatException e) {
3356 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3357 }
3358 }
3359 }
3360 return null;
3361 } catch (FileNotFoundException e) {
3362 loge("Carrier Provisioning Urls file not found");
3363 } catch (XmlPullParserException e) {
3364 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3365 } catch (IOException e) {
3366 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3367 } finally {
3368 if (fileReader != null) {
3369 try {
3370 fileReader.close();
3371 } catch (IOException e) {}
3372 }
3373 }
3374 return null;
3375 }
3376
Wink Saville42d4f082013-07-20 20:31:59 -07003377 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003378 public String getMobileProvisioningUrl() {
3379 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003380 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003381 if (TextUtils.isEmpty(url)) {
3382 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003383 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003384 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003385 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003386 }
Wink Saville8cf35602013-07-10 23:00:07 -07003387 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003388 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003389 String phoneNumber = mTelephonyManager.getLine1Number();
3390 if (TextUtils.isEmpty(phoneNumber)) {
3391 phoneNumber = "0000000000";
3392 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003393 url = String.format(url,
3394 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3395 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003396 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003397 }
3398
Wink Savilleab9321d2013-06-29 21:10:57 -07003399 return url;
3400 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003401
Wink Saville948282b2013-08-29 08:55:16 -07003402 @Override
3403 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003404 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003405 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003406 final long ident = Binder.clearCallingIdentity();
3407 try {
3408 setProvNotificationVisible(visible, networkType, action);
3409 } finally {
3410 Binder.restoreCallingIdentity(ident);
3411 }
Wink Saville948282b2013-08-29 08:55:16 -07003412 }
Wink Saville7788c612013-08-29 14:57:08 -07003413
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003414 @Override
3415 public void setAirplaneMode(boolean enable) {
3416 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003417 final long ident = Binder.clearCallingIdentity();
3418 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003419 final ContentResolver cr = mContext.getContentResolver();
3420 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3421 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3422 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003423 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003424 } finally {
3425 Binder.restoreCallingIdentity(ident);
3426 }
3427 }
3428
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003429 private void onUserStart(int userId) {
3430 synchronized(mVpns) {
3431 Vpn userVpn = mVpns.get(userId);
3432 if (userVpn != null) {
3433 loge("Starting user already has a VPN");
3434 return;
3435 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003436 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003437 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003438 }
3439 }
3440
3441 private void onUserStop(int userId) {
3442 synchronized(mVpns) {
3443 Vpn userVpn = mVpns.get(userId);
3444 if (userVpn == null) {
3445 loge("Stopping user has no VPN");
3446 return;
3447 }
3448 mVpns.delete(userId);
3449 }
3450 }
3451
3452 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3453 @Override
3454 public void onReceive(Context context, Intent intent) {
3455 final String action = intent.getAction();
3456 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3457 if (userId == UserHandle.USER_NULL) return;
3458
3459 if (Intent.ACTION_USER_STARTING.equals(action)) {
3460 onUserStart(userId);
3461 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3462 onUserStop(userId);
3463 }
3464 }
3465 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003466
Robert Greenwalta67be032014-05-16 15:49:14 -07003467 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3468 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003469 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3470 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003471
Robert Greenwalta67be032014-05-16 15:49:14 -07003472 private static class NetworkFactoryInfo {
3473 public final String name;
3474 public final Messenger messenger;
3475 public final AsyncChannel asyncChannel;
3476
3477 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3478 this.name = name;
3479 this.messenger = messenger;
3480 this.asyncChannel = asyncChannel;
3481 }
3482 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003483
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003484 /**
3485 * Tracks info about the requester.
3486 * Also used to notice when the calling process dies so we can self-expire
3487 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003488 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3489 static final boolean REQUEST = true;
3490 static final boolean LISTEN = false;
3491
3492 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003493 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003494 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003495 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003496 final int mPid;
3497 final int mUid;
3498 final Messenger messenger;
3499 final boolean isRequest;
3500
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003501 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3502 request = r;
3503 mPendingIntent = pi;
3504 messenger = null;
3505 mBinder = null;
3506 mPid = getCallingPid();
3507 mUid = getCallingUid();
3508 this.isRequest = isRequest;
3509 }
3510
Robert Greenwalt9258c642014-03-26 16:47:06 -07003511 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3512 super();
3513 messenger = m;
3514 request = r;
3515 mBinder = binder;
3516 mPid = getCallingPid();
3517 mUid = getCallingUid();
3518 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003519 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003520
3521 try {
3522 mBinder.linkToDeath(this, 0);
3523 } catch (RemoteException e) {
3524 binderDied();
3525 }
3526 }
3527
3528 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003529 if (mBinder != null) {
3530 mBinder.unlinkToDeath(this, 0);
3531 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003532 }
3533
3534 public void binderDied() {
3535 log("ConnectivityService NetworkRequestInfo binderDied(" +
3536 request + ", " + mBinder + ")");
3537 releaseNetworkRequest(request);
3538 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003539
3540 public String toString() {
3541 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003542 mPid + " for " + request +
3543 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003544 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003545 }
3546
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003547 private void ensureImmutableCapabilities(NetworkCapabilities networkCapabilities) {
3548 if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
3549 throw new IllegalArgumentException(
3550 "Cannot request network with NET_CAPABILITY_VALIDATED");
3551 }
3552 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
3553 throw new IllegalArgumentException(
3554 "Cannot request network with NET_CAPABILITY_CAPTIVE_PORTAL");
3555 }
3556 }
3557
Robert Greenwalt9258c642014-03-26 16:47:06 -07003558 @Override
3559 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003560 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003561 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003562 enforceNetworkRequestPermissions(networkCapabilities);
3563 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003564 ensureImmutableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003565
Robert Greenwalt6078b502014-06-11 16:05:07 -07003566 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003567 throw new IllegalArgumentException("Bad timeout specified");
3568 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003569
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003570 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3571 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003572 if (DBG) log("requestNetwork for " + networkRequest);
3573 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3574 NetworkRequestInfo.REQUEST);
3575
3576 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003577 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003578 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003579 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003580 }
3581 return networkRequest;
3582 }
3583
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003584 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003585 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003586 enforceConnectivityInternalPermission();
3587 } else {
3588 enforceChangePermission();
3589 }
3590 }
3591
fenglub15e72b2015-03-20 11:29:56 -07003592 @Override
fengludb571472015-04-21 17:12:05 -07003593 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003594 enforceAccessPermission();
3595 NetworkAgentInfo nai = null;
3596 if (network == null) {
3597 return false;
3598 }
3599 synchronized (mNetworkForNetId) {
3600 nai = mNetworkForNetId.get(network.netId);
3601 }
3602 if (nai != null) {
3603 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3604 return true;
3605 }
3606 return false;
3607 }
3608
3609
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003610 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3611 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003612 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003613 final int uidRules;
3614 final int uid = Binder.getCallingUid();
3615 synchronized(mRulesLock) {
3616 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3617 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003618 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003619 // we could silently fail or we can filter the available nets to only give
3620 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003621 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003622 }
3623 }
3624 }
3625
Robert Greenwalt9258c642014-03-26 16:47:06 -07003626 @Override
3627 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3628 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003629 checkNotNull(operation, "PendingIntent cannot be null.");
3630 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3631 enforceNetworkRequestPermissions(networkCapabilities);
3632 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003633 ensureImmutableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003634
3635 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3636 nextNetworkRequestId());
3637 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3638 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3639 NetworkRequestInfo.REQUEST);
3640 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3641 nri));
3642 return networkRequest;
3643 }
3644
Jeremy Joslin79294842014-12-03 17:15:28 -08003645 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3646 mHandler.sendMessageDelayed(
3647 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3648 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3649 }
3650
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003651 @Override
3652 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003653 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003654 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3655 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003656 }
3657
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003658 // In order to implement the compatibility measure for pre-M apps that call
3659 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3660 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3661 // This ensures it has permission to do so.
3662 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3663 if (nc == null) {
3664 return false;
3665 }
3666 int[] transportTypes = nc.getTransportTypes();
3667 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3668 return false;
3669 }
3670 try {
3671 mContext.enforceCallingOrSelfPermission(
3672 android.Manifest.permission.ACCESS_WIFI_STATE,
3673 "ConnectivityService");
3674 } catch (SecurityException e) {
3675 return false;
3676 }
3677 return true;
3678 }
3679
Robert Greenwalt9258c642014-03-26 16:47:06 -07003680 @Override
3681 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3682 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003683 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3684 enforceAccessPermission();
3685 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003686
3687 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003688 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003689 if (DBG) log("listenForNetwork for " + networkRequest);
3690 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3691 NetworkRequestInfo.LISTEN);
3692
3693 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3694 return networkRequest;
3695 }
3696
3697 @Override
3698 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3699 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003700 checkNotNull(operation, "PendingIntent cannot be null.");
3701 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3702 enforceAccessPermission();
3703 }
3704
3705 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3706 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3707 if (DBG) log("pendingListenForNetwork for " + networkRequest + " to trigger " + operation);
3708 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3709 NetworkRequestInfo.LISTEN);
3710
3711 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003712 }
3713
3714 @Override
3715 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003716 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3717 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003718 }
3719
3720 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003721 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003722 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003723 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003725 }
3726
Robert Greenwalta67be032014-05-16 15:49:14 -07003727 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003728 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003729 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3730 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3731 }
3732
3733 @Override
3734 public void unregisterNetworkFactory(Messenger messenger) {
3735 enforceConnectivityInternalPermission();
3736 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3737 }
3738
3739 private void handleUnregisterNetworkFactory(Messenger messenger) {
3740 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3741 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003742 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003743 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003744 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003745 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003746 }
3747
Robert Greenwalt7b816022014-04-18 15:25:25 -07003748 /**
3749 * NetworkAgentInfo supporting a request by requestId.
3750 * These have already been vetted (their Capabilities satisfy the request)
3751 * and the are the highest scored network available.
3752 * the are keyed off the Requests requestId.
3753 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003754 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003755 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3756 new SparseArray<NetworkAgentInfo>();
3757
Paul Jensen31a94f42015-02-13 14:18:39 -05003758 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3759 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003760 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3761 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003762 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3763 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3764 // there may not be a strict 1:1 correlation between the two.
3765 @GuardedBy("mNetworkForNetId")
3766 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003767
Robert Greenwalt7b816022014-04-18 15:25:25 -07003768 // NetworkAgentInfo keyed off its connecting messenger
3769 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003770 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003771 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3772 new HashMap<Messenger, NetworkAgentInfo>();
3773
Paul Jensen2c311d62014-11-17 12:34:51 -05003774 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003775 private final NetworkRequest mDefaultRequest;
3776
Erik Klineda4bfa82015-04-30 12:58:40 +09003777 // Request used to optionally keep mobile data active even when higher
3778 // priority networks like Wi-Fi are active.
3779 private final NetworkRequest mDefaultMobileDataRequest;
3780
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003781 private NetworkAgentInfo getDefaultNetwork() {
3782 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3783 }
3784
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003785 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003786 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003787 }
3788
Paul Jensen31a94f42015-02-13 14:18:39 -05003789 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003790 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003791 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003792 enforceConnectivityInternalPermission();
3793
Paul Jensen2c311d62014-11-17 12:34:51 -05003794 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3795 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003796 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003797 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3798 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3799 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003800 synchronized (this) {
3801 nai.networkMonitor.systemReady = mSystemReady;
3802 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003803 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003804 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003805 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003806 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003807 }
3808
3809 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3810 if (VDBG) log("Got NetworkAgent Messenger");
3811 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003812 synchronized (mNetworkForNetId) {
3813 mNetworkForNetId.put(na.network.netId, na);
3814 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003815 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3816 NetworkInfo networkInfo = na.networkInfo;
3817 na.networkInfo = null;
3818 updateNetworkInfo(na, networkInfo);
3819 }
3820
3821 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3822 LinkProperties newLp = networkAgent.linkProperties;
3823 int netId = networkAgent.network.netId;
3824
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003825 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3826 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003827 if (networkAgent.clatd != null) {
3828 networkAgent.clatd.fixupLinkProperties(oldLp);
3829 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003830
Paul Jensen992f2522014-04-28 10:33:11 -04003831 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003832 updateMtu(newLp, oldLp);
3833 // TODO - figure out what to do for clat
3834// for (LinkProperties lp : newLp.getStackedLinks()) {
3835// updateMtu(lp, null);
3836// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003837 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003838
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003839 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3840 // In L, we used it only when the network had Internet access but provided no DNS servers.
3841 // For now, just disable it, and if disabling it doesn't break things, remove it.
3842 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3843 // NET_CAPABILITY_INTERNET);
3844 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003845 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003846 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3847
Paul Jensen3b759822014-05-13 11:44:01 -04003848 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003849 if (isDefaultNetwork(networkAgent)) {
3850 handleApplyDefaultProxy(newLp.getHttpProxy());
3851 } else {
3852 updateProxy(newLp, oldLp, networkAgent);
3853 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003854 // TODO - move this check to cover the whole function
3855 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003856 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003857 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3858 }
Paul Jensen3b759822014-05-13 11:44:01 -04003859 }
3860
Lorenzo Colitti95439462014-10-09 13:44:48 +09003861 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3862 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3863 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003864
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003865 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003866 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3867 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003868 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003869 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003870 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003871 }
Paul Jensen992f2522014-04-28 10:33:11 -04003872
3873 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3874 CompareResult<String> interfaceDiff = new CompareResult<String>();
3875 if (oldLp != null) {
3876 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3877 } else if (newLp != null) {
3878 interfaceDiff.added = newLp.getAllInterfaceNames();
3879 }
3880 for (String iface : interfaceDiff.added) {
3881 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003882 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003883 mNetd.addInterfaceToNetwork(iface, netId);
3884 } catch (Exception e) {
3885 loge("Exception adding interface: " + e);
3886 }
3887 }
3888 for (String iface : interfaceDiff.removed) {
3889 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003890 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003891 mNetd.removeInterfaceFromNetwork(iface, netId);
3892 } catch (Exception e) {
3893 loge("Exception removing interface: " + e);
3894 }
3895 }
3896 }
3897
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003898 /**
3899 * Have netd update routes from oldLp to newLp.
3900 * @return true if routes changed between oldLp and newLp
3901 */
3902 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003903 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3904 if (oldLp != null) {
3905 routeDiff = oldLp.compareAllRoutes(newLp);
3906 } else if (newLp != null) {
3907 routeDiff.added = newLp.getAllRoutes();
3908 }
3909
3910 // add routes before removing old in case it helps with continuous connectivity
3911
3912 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3913 for (RouteInfo route : routeDiff.added) {
3914 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003915 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003916 try {
3917 mNetd.addRoute(netId, route);
3918 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003919 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3920 loge("Exception in addRoute for non-gateway: " + e);
3921 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003922 }
3923 }
3924 for (RouteInfo route : routeDiff.added) {
3925 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003926 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003927 try {
3928 mNetd.addRoute(netId, route);
3929 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003930 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3931 loge("Exception in addRoute for gateway: " + e);
3932 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003933 }
3934 }
3935
3936 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003937 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003938 try {
3939 mNetd.removeRoute(netId, route);
3940 } catch (Exception e) {
3941 loge("Exception in removeRoute: " + e);
3942 }
3943 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003944 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003945 }
Erik Kline41368502015-06-17 13:19:54 +09003946
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003947 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3948 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003949 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09003950 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003951 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003952 dnses = new ArrayList();
3953 dnses.add(mDefaultDns);
3954 if (DBG) {
3955 loge("no dns provided for netId " + netId + ", so using defaults");
3956 }
3957 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003958 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003959 try {
3960 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3961 newLp.getDomains());
3962 } catch (Exception e) {
3963 loge("Exception in setDnsServersForNetwork: " + e);
3964 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003965 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003966 if (defaultNai != null && defaultNai.network.netId == netId) {
3967 setDefaultDnsSystemProperties(dnses);
3968 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003969 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003970 } else if (flush) {
3971 try {
3972 mNetd.flushNetworkDnsCache(netId);
3973 } catch (Exception e) {
3974 loge("Exception in flushNetworkDnsCache: " + e);
3975 }
3976 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003977 }
3978 }
3979
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003980 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3981 int last = 0;
3982 for (InetAddress dns : dnses) {
3983 ++last;
3984 String key = "net.dns" + last;
3985 String value = dns.getHostAddress();
3986 SystemProperties.set(key, value);
3987 }
3988 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3989 String key = "net.dns" + i;
3990 SystemProperties.set(key, "");
3991 }
3992 mNumDnsEntries = last;
3993 }
3994
Paul Jensen3d194ea2015-06-16 14:27:36 -04003995 /**
3996 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
3997 * augmented with any stateful capabilities implied from {@code networkAgent}
3998 * (e.g., validated status and captive portal status).
3999 *
4000 * @param networkAgent the network having its capabilities updated.
4001 * @param networkCapabilities the new network capabilities.
4002 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07004003 private void updateCapabilities(NetworkAgentInfo networkAgent,
Paul Jensen85cf78e2015-06-25 13:25:07 -04004004 NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004005 // Don't modify caller's NetworkCapabilities.
4006 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4007 if (networkAgent.lastValidated) {
4008 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4009 } else {
4010 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4011 }
4012 if (networkAgent.lastCaptivePortalDetected) {
4013 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4014 } else {
4015 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4016 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004017 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
4018 synchronized (networkAgent) {
4019 networkAgent.networkCapabilities = networkCapabilities;
4020 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04004021 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004022 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004023 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004024 }
4025
Paul Jensenc8b9a742014-09-30 15:37:41 -04004026 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4027 for (int i = 0; i < nai.networkRequests.size(); i++) {
4028 NetworkRequest nr = nai.networkRequests.valueAt(i);
4029 // Don't send listening requests to factories. b/17393458
4030 if (!isRequest(nr)) continue;
4031 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4032 }
4033 }
4034
Robert Greenwalt7b816022014-04-18 15:25:25 -07004035 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4036 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004037 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004038 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4039 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004040 }
4041 }
4042
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004043 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4044 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004045 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004046 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004047 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4048 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004049 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004050 sendIntent(nri.mPendingIntent, intent);
4051 }
4052 // else not handled
4053 }
4054
4055 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4056 mPendingIntentWakeLock.acquire();
4057 try {
4058 if (DBG) log("Sending " + pendingIntent);
4059 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4060 } catch (PendingIntent.CanceledException e) {
4061 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4062 mPendingIntentWakeLock.release();
4063 releasePendingNetworkRequest(pendingIntent);
4064 }
4065 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4066 }
4067
4068 @Override
4069 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4070 String resultData, Bundle resultExtras) {
4071 if (DBG) log("Finished sending " + pendingIntent);
4072 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004073 // Release with a delay so the receiving client has an opportunity to put in its
4074 // own request.
4075 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004076 }
4077
Robert Greenwalt9258c642014-03-26 16:47:06 -07004078 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004079 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004080 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004081 Bundle bundle = new Bundle();
4082 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4083 new NetworkRequest(nri.request));
4084 Message msg = Message.obtain();
4085 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4086 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4087 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4088 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004089 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004090 case ConnectivityManager.CALLBACK_LOSING: {
4091 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4092 break;
4093 }
4094 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4095 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4096 new NetworkCapabilities(networkAgent.networkCapabilities));
4097 break;
4098 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004099 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004100 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4101 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004102 break;
4103 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004104 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004105 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004106 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004107 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004108 if (VDBG) {
4109 log("sending notification " + notifyTypeToName(notificationType) +
4110 " for " + nri.request);
4111 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004112 nri.messenger.send(msg);
4113 } catch (RemoteException e) {
4114 // may occur naturally in the race of binder death.
4115 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4116 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004117 }
4118
Paul Jensenc8b9a742014-09-30 15:37:41 -04004119 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4120 for (int i = 0; i < nai.networkRequests.size(); i++) {
4121 NetworkRequest nr = nai.networkRequests.valueAt(i);
4122 // Ignore listening requests.
4123 if (!isRequest(nr)) continue;
4124 loge("Dead network still had at least " + nr);
4125 break;
4126 }
4127 nai.asyncChannel.disconnect();
4128 }
4129
Robert Greenwalt7b816022014-04-18 15:25:25 -07004130 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4131 if (oldNetwork == null) {
4132 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4133 return;
4134 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004135 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4136 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004137 }
4138
Paul Jensen27b02b72014-07-14 12:03:33 -04004139 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004140 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004141 setupDataActivityTracking(newNetwork);
4142 try {
4143 mNetd.setDefaultNetId(newNetwork.network.netId);
4144 } catch (Exception e) {
4145 loge("Exception setting default network :" + e);
4146 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004147 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004148 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004149 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004150 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004151 }
4152
Paul Jensen2161a8e2014-09-11 11:00:39 -04004153 // Handles a network appearing or improving its score.
4154 //
4155 // - Evaluates all current NetworkRequests that can be
4156 // satisfied by newNetwork, and reassigns to newNetwork
4157 // any such requests for which newNetwork is the best.
4158 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004159 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004160 // needed. A network is needed if it is the best network for
4161 // one or more NetworkRequests, or if it is a VPN.
4162 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004163 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004164 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004165 //
4166 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4167 // networks that have no chance (i.e. even if validated)
4168 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004169 //
4170 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4171 // it does not remove NetworkRequests that other Networks could better satisfy.
4172 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4173 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4174 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004175 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004176 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004177 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4178 // performed to tear down unvalidated networks that have no chance (i.e. even if
4179 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004180 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004181 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004182 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004183 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004184 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004185 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004186 if (DBG) log("rematching " + newNetwork.name());
4187 // Find and migrate to this Network any NetworkRequests for
4188 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004189 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004190 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004191 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004192 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004193 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4194 if (newNetwork == currentNetwork) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004195 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004196 log("Network " + newNetwork.name() + " was already satisfying" +
4197 " request " + nri.request.requestId + ". No change.");
4198 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004199 keep = true;
4200 continue;
4201 }
4202
4203 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004204 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004205 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004206 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004207 // This is not a request, it's a callback listener.
4208 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004209 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004210 continue;
4211 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004212
Robert Greenwalt7b816022014-04-18 15:25:25 -07004213 // next check if it's better than any current network we're using for
4214 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004215 if (VDBG) {
4216 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004217 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4218 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004219 }
4220 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004221 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004222 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004223 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004224 currentNetwork.networkRequests.remove(nri.request.requestId);
4225 currentNetwork.networkLingered.add(nri.request);
4226 affectedNetworks.add(currentNetwork);
4227 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004228 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004229 }
Paul Jensen573a0352015-01-08 10:49:34 -05004230 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004231 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004232 if (!newNetwork.addRequest(nri.request)) {
4233 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4234 }
4235 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004236 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004237 // Tell NetworkFactories about the new score, so they can stop
4238 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004239 // TODO - this could get expensive if we have alot of requests for this
4240 // network. Think about if there is a way to reduce this. Push
4241 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004242 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004243 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004244 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004245 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004246 }
4247 }
4248 }
4249 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004250 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004251 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004252 if (nai.everValidated && unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004253 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004254 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004255 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004256 }
4257 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004258 if (keep) {
4259 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004260 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004261 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004262 synchronized (ConnectivityService.this) {
4263 // have a new default network, release the transition wakelock in
4264 // a second if it's held. The second pause is to allow apps
4265 // to reconnect over the new network
4266 if (mNetTransitionWakeLock.isHeld()) {
4267 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4268 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4269 mNetTransitionWakeLockSerialNumber, 0),
4270 1000);
4271 }
4272 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004273 }
4274
4275 // do this after the default net is switched, but
4276 // before LegacyTypeTracker sends legacy broadcasts
Paul Jensen3d911462015-06-12 06:40:24 -04004277 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
Robert Greenwalt152ed372014-12-17 17:19:53 -08004278
4279 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004280 // Maintain the illusion: since the legacy API only
4281 // understands one network at a time, we must pretend
4282 // that the current default network disconnected before
4283 // the new one connected.
4284 if (oldDefaultNetwork != null) {
4285 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004286 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004287 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004288 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004289 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4290 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004291 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004292
4293 // Notify battery stats service about this network, both the normal
4294 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004295 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004296 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004297 final IBatteryStats bs = BatteryStatsService.getService();
4298 final int type = newNetwork.networkInfo.getType();
4299
4300 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4301 bs.noteNetworkInterfaceType(baseIface, type);
4302 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4303 final String stackedIface = stacked.getInterfaceName();
4304 bs.noteNetworkInterfaceType(stackedIface, type);
4305 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4306 }
4307 } catch (RemoteException ignored) {
4308 }
4309
Robert Greenwalt152ed372014-12-17 17:19:53 -08004310 // This has to happen after the notifyNetworkCallbacks as that tickles each
4311 // ConnectivityManager instance so that legacy requests correctly bind dns
4312 // requests to this network. The legacy users are listening for this bcast
4313 // and will generally do a dns request so they can ensureRouteToHost and if
4314 // they do that before the callbacks happen they'll use the default network.
4315 //
4316 // TODO: Is there still a race here? We send the broadcast
4317 // after sending the callback, but if the app can receive the
4318 // broadcast before the callback, it might still break.
4319 //
4320 // This *does* introduce a race where if the user uses the new api
4321 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4322 // they may get old info. Reverse this after the old startUsing api is removed.
4323 // This is on top of the multiple intent sequencing referenced in the todo above.
4324 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4325 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4326 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4327 // legacy type tracker filters out repeat adds
4328 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4329 }
4330 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004331
4332 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4333 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4334 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4335 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4336 if (newNetwork.isVPN()) {
4337 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4338 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004339 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004340 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4341 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004342 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004343 if (DBG) log("Reaping " + nai.name());
4344 teardownUnneededNetwork(nai);
4345 }
4346 }
4347 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004348 }
4349
Paul Jensen1c7ba022015-06-16 14:27:36 -04004350 /**
4351 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4352 * being disconnected.
4353 * @param changed If only one Network's score or capabilities have been modified since the last
4354 * time this function was called, pass this Network in this argument, otherwise pass
4355 * null.
4356 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4357 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4358 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4359 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4360 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004361 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004362 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004363 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4364 // to avoid the slowness. It is not simply enough to process just "changed", for
4365 // example in the case where "changed"'s score decreases and another network should begin
4366 // satifying a NetworkRequest that "changed" currently satisfies.
4367
4368 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4369 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4370 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004371 if (changed != null && oldScore < changed.getCurrentScore()) {
4372 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004373 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004374 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4375 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4376 // Rematch higher scoring networks first to prevent requests first matching a lower
4377 // scoring network and then a higher scoring network, which could produce multiple
4378 // callbacks and inadvertently unlinger networks.
4379 Arrays.sort(nais);
4380 for (NetworkAgentInfo nai : nais) {
4381 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004382 // Only reap the last time through the loop. Reaping before all rematching
4383 // is complete could incorrectly teardown a network that hasn't yet been
4384 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004385 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004386 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004387 }
4388 }
4389 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004390
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004391 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004392 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004393 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004394 // For now only update icons for default connection.
4395 // TODO: Update WiFi and cellular icons separately. b/17237507
4396 if (!isDefaultNetwork(nai)) return;
4397
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004398 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004399 // Don't repeat publish.
4400 if (newInetCondition == mDefaultInetConditionPublished) return;
4401
4402 mDefaultInetConditionPublished = newInetCondition;
4403 sendInetConditionBroadcast(nai.networkInfo);
4404 }
4405
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004406 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4407 if (mLockdownTracker != null) {
4408 if (nai != null && nai.isVPN()) {
4409 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4410 } else {
4411 mLockdownTracker.onNetworkInfoChanged();
4412 }
4413 }
4414 }
4415
Robert Greenwalt7b816022014-04-18 15:25:25 -07004416 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4417 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004418 NetworkInfo oldInfo = null;
4419 synchronized (networkAgent) {
4420 oldInfo = networkAgent.networkInfo;
4421 networkAgent.networkInfo = newInfo;
4422 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004423 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004424
4425 if (oldInfo != null && oldInfo.getState() == state) {
4426 if (VDBG) log("ignoring duplicate network state non-change");
4427 return;
4428 }
4429 if (DBG) {
4430 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4431 (oldInfo == null ? "null" : oldInfo.getState()) +
4432 " to " + state);
4433 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004434
Paul Jenseneec75412014-08-04 12:21:19 -04004435 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004436 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004437 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004438 if (networkAgent.isVPN()) {
4439 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004440 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4441 (networkAgent.networkMisc == null ||
4442 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004443 } else {
4444 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4445 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004446 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004447 loge("Error creating network " + networkAgent.network.netId + ": "
4448 + e.getMessage());
4449 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004450 }
Paul Jenseneec75412014-08-04 12:21:19 -04004451 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004452 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004453 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004454
Paul Jensenca8f16a2014-05-09 12:47:55 -04004455 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004456 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004457
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004458 if (networkAgent.isVPN()) {
4459 // Temporarily disable the default proxy (not global).
4460 synchronized (mProxyLock) {
4461 if (!mDefaultProxyDisabled) {
4462 mDefaultProxyDisabled = true;
4463 if (mGlobalProxy == null && mDefaultProxy != null) {
4464 sendProxyBroadcast(null);
4465 }
4466 }
4467 }
4468 // TODO: support proxy per network.
4469 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004470
Paul Jensen2161a8e2014-09-11 11:00:39 -04004471 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004472 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004473
4474 // This has to happen after matching the requests, because callbacks are just requests.
4475 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004476 } else if (state == NetworkInfo.State.DISCONNECTED ||
4477 state == NetworkInfo.State.SUSPENDED) {
4478 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004479 if (networkAgent.isVPN()) {
4480 synchronized (mProxyLock) {
4481 if (mDefaultProxyDisabled) {
4482 mDefaultProxyDisabled = false;
4483 if (mGlobalProxy == null && mDefaultProxy != null) {
4484 sendProxyBroadcast(mDefaultProxy);
4485 }
4486 }
4487 }
4488 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004489 }
4490 }
4491
Robert Greenwaltac96c522014-06-03 16:43:57 -07004492 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4493 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004494 if (score < 0) {
4495 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4496 "). Bumping score to min of 0");
4497 score = 0;
4498 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004499
Paul Jensen2161a8e2014-09-11 11:00:39 -04004500 final int oldScore = nai.getCurrentScore();
4501 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004502
Paul Jensen85cf78e2015-06-25 13:25:07 -04004503 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004504
Paul Jensenc8b9a742014-09-30 15:37:41 -04004505 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004506 }
4507
Robert Greenwalt9258c642014-03-26 16:47:06 -07004508 // notify only this one new request of the current state
4509 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4510 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4511 // TODO - read state from monitor to decide what to send.
4512// if (nai.networkMonitor.isLingering()) {
4513// notifyType = NetworkCallbacks.LOSING;
4514// } else if (nai.networkMonitor.isEvaluating()) {
4515// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4516// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004517 if (nri.mPendingIntent == null) {
4518 callCallbackForRequest(nri, nai, notifyType);
4519 } else {
4520 sendPendingIntentForRequest(nri, nai, notifyType);
4521 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004522 }
4523
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004524 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004525 // The NetworkInfo we actually send out has no bearing on the real
4526 // state of affairs. For example, if the default connection is mobile,
4527 // and a request for HIPRI has just gone away, we need to pretend that
4528 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4529 // the state to DISCONNECTED, even though the network is of type MOBILE
4530 // and is still connected.
4531 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4532 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004533 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004534 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004535 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004536 } else {
Feixiong Zhang376133f2015-06-01 18:07:58 -07004537 info.setDetailedState(DetailedState.DISCONNECTED, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004538 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4539 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4540 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4541 if (info.isFailover()) {
4542 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4543 nai.networkInfo.setFailover(false);
4544 }
4545 if (info.getReason() != null) {
4546 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4547 }
4548 if (info.getExtraInfo() != null) {
4549 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4550 }
4551 NetworkAgentInfo newDefaultAgent = null;
4552 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004553 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004554 if (newDefaultAgent != null) {
4555 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4556 newDefaultAgent.networkInfo);
4557 } else {
4558 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4559 }
4560 }
4561 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4562 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004563 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004564 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004565 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004566 }
4567 }
4568 }
4569
Robert Greenwalt7b816022014-04-18 15:25:25 -07004570 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004571 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004572 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004573 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4574 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4575 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004576 if (nri.mPendingIntent == null) {
4577 callCallbackForRequest(nri, networkAgent, notifyType);
4578 } else {
4579 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4580 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004581 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004582 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004583
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004584 private String notifyTypeToName(int notifyType) {
4585 switch (notifyType) {
4586 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4587 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4588 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4589 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4590 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4591 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4592 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4593 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4594 }
4595 return "UNKNOWN";
4596 }
4597
Jeff Sharkey69736342014-12-08 14:50:12 -08004598 /**
4599 * Notify other system services that set of active ifaces has changed.
4600 */
4601 private void notifyIfacesChanged() {
4602 try {
4603 mStatsService.forceUpdateIfaces();
4604 } catch (Exception ignored) {
4605 }
4606 }
4607
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004608 @Override
4609 public boolean addVpnAddress(String address, int prefixLength) {
4610 throwIfLockdownEnabled();
4611 int user = UserHandle.getUserId(Binder.getCallingUid());
4612 synchronized (mVpns) {
4613 return mVpns.get(user).addAddress(address, prefixLength);
4614 }
4615 }
4616
4617 @Override
4618 public boolean removeVpnAddress(String address, int prefixLength) {
4619 throwIfLockdownEnabled();
4620 int user = UserHandle.getUserId(Binder.getCallingUid());
4621 synchronized (mVpns) {
4622 return mVpns.get(user).removeAddress(address, prefixLength);
4623 }
4624 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004625
4626 @Override
4627 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4628 throwIfLockdownEnabled();
4629 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004630 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004631 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004632 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004633 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004634 if (success) {
4635 notifyIfacesChanged();
4636 }
4637 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004638 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004639
4640 @Override
4641 public void factoryReset() {
4642 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004643
4644 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4645 return;
4646 }
4647
Robin Lee3b3dd942015-05-12 18:14:58 +01004648 final int userId = UserHandle.getCallingUserId();
4649
Stuart Scottf1fb3972015-04-02 18:00:02 -07004650 // Turn airplane mode off
4651 setAirplaneMode(false);
4652
Stuart Scotte3e314d2015-04-20 14:07:45 -07004653 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4654 // Untether
4655 for (String tether : getTetheredIfaces()) {
4656 untether(tether);
4657 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004658 }
4659
Stuart Scotte3e314d2015-04-20 14:07:45 -07004660 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4661 // Turn VPN off
4662 VpnConfig vpnConfig = getVpnConfig(userId);
4663 if (vpnConfig != null) {
4664 if (vpnConfig.legacy) {
4665 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4666 } else {
4667 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4668 // in the future without user intervention.
4669 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004670
Stuart Scotte3e314d2015-04-20 14:07:45 -07004671 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4672 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004673 }
4674 }
4675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676}