blob: 2075c07edb44b60de3836cd0455a43a3139e5942 [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
Robert Greenwalt8d482522015-06-24 13:23:42 -0700486 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900487 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900488 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700489 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900490 " 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) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700513 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
514 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700515 }
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
Robert Greenwalt8d482522015-06-24 13:23:42 -0700531 final DetailedState state = DetailedState.DISCONNECTED;
532
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700534 maybeLogBroadcast(nai, state, type, wasDefault);
535 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900536 }
537
538 if (!list.isEmpty() && wasFirstNetwork) {
539 if (DBG) log("Other network available for type " + type +
540 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900541 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700542 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
543 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900544 }
545 }
546
547 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900548 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
549 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700550 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900551 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700552 }
553 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700554
Robert Greenwalt8d482522015-06-24 13:23:42 -0700555 // send out another legacy broadcast - currently only used for suspend/unsuspend
556 // toggle
557 public void update(NetworkAgentInfo nai) {
558 final boolean isDefault = isDefaultNetwork(nai);
559 final DetailedState state = nai.networkInfo.getDetailedState();
560 for (int type = 0; type < mTypeLists.length; type++) {
561 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
562 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
563 if (isFirst || isDefault) {
564 maybeLogBroadcast(nai, state, type, isDefault);
565 sendLegacyNetworkBroadcast(nai, state, type);
566 }
567 }
568 }
569
Lorenzo Colittia793a672014-07-31 23:20:17 +0900570 private String naiToString(NetworkAgentInfo nai) {
571 String name = (nai != null) ? nai.name() : "null";
572 String state = (nai.networkInfo != null) ?
573 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
574 "???/???";
575 return name + " " + state;
576 }
577
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700578 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900579 pw.println("mLegacyTypeTracker:");
580 pw.increaseIndent();
581 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700582 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900583 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700584 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900585 pw.println();
586 pw.println("Current state:");
587 pw.increaseIndent();
588 for (int type = 0; type < mTypeLists.length; type++) {
589 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
590 for (NetworkAgentInfo nai : mTypeLists[type]) {
591 pw.println(type + " " + naiToString(nai));
592 }
593 }
594 pw.decreaseIndent();
595 pw.decreaseIndent();
596 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700597 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900598
599 // This class needs its own log method because it has a different TAG.
600 private void log(String s) {
601 Slog.d(TAG, s);
602 }
603
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700604 }
605 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
606
Jeff Sharkey899223b2012-08-04 15:24:58 -0700607 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700608 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800609 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800610
Erik Klineda4bfa82015-04-30 12:58:40 +0900611 mDefaultRequest = createInternetRequestForTransport(-1);
612 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
613 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
614
615 mDefaultMobileDataRequest = createInternetRequestForTransport(
616 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700617
Wink Savillebb08caf2010-09-02 19:23:52 -0700618 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
619 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700620 mHandler = new InternalHandler(handlerThread.getLooper());
621 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700622
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800623 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800624 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
625 String id = Settings.Secure.getString(context.getContentResolver(),
626 Settings.Secure.ANDROID_ID);
627 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700628 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800629 SystemProperties.set("net.hostname", name);
630 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800631 }
632
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700633 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700634 String dns = Settings.Global.getString(context.getContentResolver(),
635 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700636 if (dns == null || dns.length() == 0) {
637 dns = context.getResources().getString(
638 com.android.internal.R.string.config_default_dns_server);
639 }
640 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800641 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
642 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800643 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700644 }
645
Jeremy Joslin79294842014-12-03 17:15:28 -0800646 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
647 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
648
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700649 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700650 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800651 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700652 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700653 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700654 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700655
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700656 try {
657 mPolicyManager.registerListener(mPolicyListener);
658 } catch (RemoteException e) {
659 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700660 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700661 }
662
663 final PowerManager powerManager = (PowerManager) context.getSystemService(
664 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700665 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
666 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
667 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800668 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700669
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700670 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700671
Wink Saville51f456f2013-04-23 14:26:51 -0700672 // TODO: What is the "correct" way to do determine if this is a wifi only device?
673 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
674 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700675 String[] naStrings = context.getResources().getStringArray(
676 com.android.internal.R.array.networkAttributes);
677 for (String naString : naStrings) {
678 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700679 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700680 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700681 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800682 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700683 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700684 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700685 }
Wink Saville51f456f2013-04-23 14:26:51 -0700686 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
687 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
688 n.type);
689 continue;
690 }
Wink Saville975c8482011-04-07 14:23:45 -0700691 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800692 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700693 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700694 continue;
695 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700696 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700697
Wink Saville975c8482011-04-07 14:23:45 -0700698 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700699 mNetworksDefined++;
700 } catch(Exception e) {
701 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700702 }
703 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700704
705 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
706 if (mNetConfigs[TYPE_VPN] == null) {
707 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
708 // don't need to add TYPE_VPN to mNetConfigs.
709 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
710 mNetworksDefined++; // used only in the log() statement below.
711 }
712
Wink Saville5e56bc52013-07-29 15:00:57 -0700713 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700714
Robert Greenwalt50393202011-06-21 17:26:14 -0700715 mProtectedNetworks = new ArrayList<Integer>();
716 int[] protectedNetworks = context.getResources().getIntArray(
717 com.android.internal.R.array.config_protectedNetworks);
718 for (int p : protectedNetworks) {
719 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
720 mProtectedNetworks.add(p);
721 } else {
722 if (DBG) loge("Ignoring protectedNetwork " + p);
723 }
724 }
725
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700726 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
727 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700728
Robert Greenwaltfab501672014-07-23 11:44:01 -0700729 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800730
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700731 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
732
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700733 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700734 IntentFilter intentFilter = new IntentFilter();
735 intentFilter.addAction(Intent.ACTION_USER_STARTING);
736 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
737 mContext.registerReceiverAsUser(
738 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900739
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700740 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700741 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700742 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700743 } catch (RemoteException e) {
744 loge("Error registering observer :" + e);
745 }
746
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700747 if (DBG) {
748 mInetLog = new ArrayList();
749 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700750
Erik Klineda4bfa82015-04-30 12:58:40 +0900751 mSettingsObserver = new SettingsObserver(mContext, mHandler);
752 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800753
John Spurlockbf991a82013-06-24 14:20:23 -0400754 mDataConnectionStats = new DataConnectionStats(mContext);
755 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400756
Jason Monkdecd2952013-10-10 14:02:51 -0400757 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700758
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400759 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700761
Erik Klineda4bfa82015-04-30 12:58:40 +0900762 private NetworkRequest createInternetRequestForTransport(int transportType) {
763 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900764 netCap.addCapability(NET_CAPABILITY_INTERNET);
765 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900766 if (transportType > -1) {
767 netCap.addTransportType(transportType);
768 }
769 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
770 }
771
772 private void handleMobileDataAlwaysOn() {
773 final boolean enable = (Settings.Global.getInt(
774 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
775 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
776 if (enable == isEnabled) {
777 return; // Nothing to do.
778 }
779
780 if (enable) {
781 handleRegisterNetworkRequest(new NetworkRequestInfo(
782 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
783 } else {
784 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
785 }
786 }
787
788 private void registerSettingsCallbacks() {
789 // Watch for global HTTP proxy changes.
790 mSettingsObserver.observe(
791 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
792 EVENT_APPLY_GLOBAL_HTTP_PROXY);
793
794 // Watch for whether or not to keep mobile data always on.
795 mSettingsObserver.observe(
796 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
797 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
798 }
799
Robert Greenwalt34524f02014-05-18 16:22:10 -0700800 private synchronized int nextNetworkRequestId() {
801 return mNextNetworkRequestId++;
802 }
803
Paul Jensen67b0b072015-06-10 11:22:17 -0400804 @VisibleForTesting
805 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400806 synchronized (mNetworkForNetId) {
807 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
808 int netId = mNextNetId;
809 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
810 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500811 if (!mNetIdInUse.get(netId)) {
812 mNetIdInUse.put(netId, true);
813 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400814 }
815 }
816 }
817 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700818 }
819
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800820 private NetworkState getFilteredNetworkState(int networkType, int uid) {
821 NetworkInfo info = null;
822 LinkProperties lp = null;
823 NetworkCapabilities nc = null;
824 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800825 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800826
827 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
828 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
829 if (nai != null) {
830 synchronized (nai) {
831 info = new NetworkInfo(nai.networkInfo);
832 lp = new LinkProperties(nai.linkProperties);
833 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400834 // Network objects are outwardly immutable so there is no point to duplicating.
835 // Duplicating also precludes sharing socket factories and connection pools.
836 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800837 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800838 }
839 info.setType(networkType);
840 } else {
841 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
842 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
843 info.setIsAvailable(true);
844 lp = new LinkProperties();
845 nc = new NetworkCapabilities();
846 network = null;
847 }
848 info = getFilteredNetworkInfo(info, lp, uid);
849 }
850
Jeff Sharkey32566012014-12-02 18:30:14 -0800851 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400852 }
853
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800854 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
855 if (network == null) {
856 return null;
857 }
858 synchronized (mNetworkForNetId) {
859 return mNetworkForNetId.get(network.netId);
860 }
861 };
862
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900863 private Network[] getVpnUnderlyingNetworks(int uid) {
864 if (!mLockdownEnabled) {
865 int user = UserHandle.getUserId(uid);
866 synchronized (mVpns) {
867 Vpn vpn = mVpns.get(user);
868 if (vpn != null && vpn.appliesToUid(uid)) {
869 return vpn.getUnderlyingNetworks();
870 }
871 }
872 }
873 return null;
874 }
875
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800876 private NetworkState getUnfilteredActiveNetworkState(int uid) {
877 NetworkInfo info = null;
878 LinkProperties lp = null;
879 NetworkCapabilities nc = null;
880 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800881 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800882
Paul Jensen85cf78e2015-06-25 13:25:07 -0400883 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800884
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900885 final Network[] networks = getVpnUnderlyingNetworks(uid);
886 if (networks != null) {
887 // getUnderlyingNetworks() returns:
888 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
889 // empty array => the VPN explicitly said "no default network".
890 // non-empty array => the VPN specified one or more default networks; we use the
891 // first one.
892 if (networks.length > 0) {
893 nai = getNetworkAgentInfoForNetwork(networks[0]);
894 } else {
895 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800896 }
897 }
898
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800899 if (nai != null) {
900 synchronized (nai) {
901 info = new NetworkInfo(nai.networkInfo);
902 lp = new LinkProperties(nai.linkProperties);
903 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400904 // Network objects are outwardly immutable so there is no point to duplicating.
905 // Duplicating also precludes sharing socket factories and connection pools.
906 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800907 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800908 }
909 }
910
Jeff Sharkey32566012014-12-02 18:30:14 -0800911 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400912 }
913
914 /**
915 * Check if UID should be blocked from using the network with the given LinkProperties.
916 */
917 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700918 final boolean networkCostly;
919 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700920
Robert Greenwalt12e67352014-05-13 21:41:06 -0700921 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700922 synchronized (mRulesLock) {
923 networkCostly = mMeteredIfaces.contains(iface);
924 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700925 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700926
Amith Yamasani15e472352015-04-24 19:06:07 -0700927 if ((uidRules & RULE_REJECT_ALL) != 0
928 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700929 return true;
930 }
931
932 // no restrictive rules; network is visible
933 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700934 }
935
936 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700937 * Return a filtered {@link NetworkInfo}, potentially marked
938 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700940 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800941 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
942 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400943 // network is blocked; clone and override state
944 info = new NetworkInfo(info);
945 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900946 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900947 log("returning Blocked NetworkInfo for ifname=" +
948 lp.getInterfaceName() + ", uid=" + uid);
949 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700950 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800951 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700952 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900953 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700954 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700955 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700956 }
957
958 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 * Return NetworkInfo for the active (i.e., connected) network interface.
960 * It is assumed that at most one network is active at a time. If more
961 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700962 * @return the info for the active network, or {@code null} if none is
963 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700965 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700967 enforceAccessPermission();
968 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800969 NetworkState state = getUnfilteredActiveNetworkState(uid);
970 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 }
972
Paul Jensen31a94f42015-02-13 14:18:39 -0500973 @Override
974 public Network getActiveNetwork() {
975 enforceAccessPermission();
976 final int uid = Binder.getCallingUid();
977 final int user = UserHandle.getUserId(uid);
978 int vpnNetId = NETID_UNSET;
979 synchronized (mVpns) {
980 final Vpn vpn = mVpns.get(user);
981 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
982 }
983 NetworkAgentInfo nai;
984 if (vpnNetId != NETID_UNSET) {
985 synchronized (mNetworkForNetId) {
986 nai = mNetworkForNetId.get(vpnNetId);
987 }
988 if (nai != null) return nai.network;
989 }
990 nai = getDefaultNetwork();
991 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
992 return nai != null ? nai.network : null;
993 }
994
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700995 public NetworkInfo getActiveNetworkInfoUnfiltered() {
996 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800997 final int uid = Binder.getCallingUid();
998 NetworkState state = getUnfilteredActiveNetworkState(uid);
999 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001000 }
1001
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001002 @Override
1003 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1004 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001005 NetworkState state = getUnfilteredActiveNetworkState(uid);
1006 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001007 }
1008
1009 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 public NetworkInfo getNetworkInfo(int networkType) {
1011 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001012 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001013 if (getVpnUnderlyingNetworks(uid) != null) {
1014 // A VPN is active, so we may need to return one of its underlying networks. This
1015 // information is not available in LegacyTypeTracker, so we have to get it from
1016 // getUnfilteredActiveNetworkState.
1017 NetworkState state = getUnfilteredActiveNetworkState(uid);
1018 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1019 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1020 }
1021 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001022 NetworkState state = getFilteredNetworkState(networkType, uid);
1023 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001026 @Override
1027 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1028 enforceAccessPermission();
1029 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001030 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001031 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1032 if (nai != null) {
1033 synchronized (nai) {
1034 info = new NetworkInfo(nai.networkInfo);
1035 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001036 }
1037 }
1038 return info;
1039 }
1040
1041 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 public NetworkInfo[] getAllNetworkInfo() {
1043 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001044 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001045 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1046 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 NetworkInfo info = getNetworkInfo(networkType);
1048 if (info != null) {
1049 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001052 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
1054
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001055 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001056 public Network getNetworkForType(int networkType) {
1057 enforceAccessPermission();
1058 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001059 NetworkState state = getFilteredNetworkState(networkType, uid);
1060 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1061 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001062 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001063 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001064 }
1065
1066 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001067 public Network[] getAllNetworks() {
1068 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001069 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001070 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001071 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001072 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001073 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001074 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001075 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001076 }
1077
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001078 @Override
1079 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1080 // The basic principle is: if an app's traffic could possibly go over a
1081 // network, without the app doing anything multinetwork-specific,
1082 // (hence, by "default"), then include that network's capabilities in
1083 // the array.
1084 //
1085 // In the normal case, app traffic only goes over the system's default
1086 // network connection, so that's the only network returned.
1087 //
1088 // With a VPN in force, some app traffic may go into the VPN, and thus
1089 // over whatever underlying networks the VPN specifies, while other app
1090 // traffic may go over the system default network (e.g.: a split-tunnel
1091 // VPN, or an app disallowed by the VPN), so the set of networks
1092 // returned includes the VPN's underlying networks and the system
1093 // default.
1094 enforceAccessPermission();
1095
1096 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1097
1098 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001099 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001100 if (nc != null) {
1101 result.put(nai.network, nc);
1102 }
1103
1104 if (!mLockdownEnabled) {
1105 synchronized (mVpns) {
1106 Vpn vpn = mVpns.get(userId);
1107 if (vpn != null) {
1108 Network[] networks = vpn.getUnderlyingNetworks();
1109 if (networks != null) {
1110 for (Network network : networks) {
1111 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001112 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001113 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001114 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001115 }
1116 }
1117 }
1118 }
1119 }
1120 }
1121
1122 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1123 out = result.values().toArray(out);
1124 return out;
1125 }
1126
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001127 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001128 public boolean isNetworkSupported(int networkType) {
1129 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001130 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001131 }
1132
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001133 /**
1134 * Return LinkProperties for the active (i.e., connected) default
1135 * network interface. It is assumed that at most one default network
1136 * is active at a time. If more than one is active, it is indeterminate
1137 * which will be returned.
1138 * @return the ip properties for the active network, or {@code null} if
1139 * none is active
1140 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001141 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001142 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001143 enforceAccessPermission();
1144 final int uid = Binder.getCallingUid();
1145 NetworkState state = getUnfilteredActiveNetworkState(uid);
1146 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001147 }
1148
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001149 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001150 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001151 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001152 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1153 if (nai != null) {
1154 synchronized (nai) {
1155 return new LinkProperties(nai.linkProperties);
1156 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001157 }
1158 return null;
1159 }
1160
Robert Greenwalt12e67352014-05-13 21:41:06 -07001161 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001162 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001163 public LinkProperties getLinkProperties(Network network) {
1164 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001165 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001166 if (nai != null) {
1167 synchronized (nai) {
1168 return new LinkProperties(nai.linkProperties);
1169 }
1170 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001171 return null;
1172 }
1173
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001174 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001175 if (nai != null) {
1176 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001177 if (nai.networkCapabilities != null) {
1178 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001179 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001180 }
1181 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001182 return null;
1183 }
1184
1185 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001186 public NetworkCapabilities getNetworkCapabilities(Network network) {
1187 enforceAccessPermission();
1188 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1189 }
1190
1191 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001192 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001193 // Require internal since we're handing out IMSI details
1194 enforceConnectivityInternalPermission();
1195
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001196 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001197 for (Network network : getAllNetworks()) {
1198 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1199 if (nai != null) {
1200 synchronized (nai) {
1201 final String subscriberId = (nai.networkMisc != null)
1202 ? nai.networkMisc.subscriberId : null;
1203 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1204 nai.networkCapabilities, network, subscriberId, null));
1205 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001206 }
1207 }
1208 return result.toArray(new NetworkState[result.size()]);
1209 }
1210
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001211 @Override
1212 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1213 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001214 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001215 final long token = Binder.clearCallingIdentity();
1216 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001217 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1218 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001219 try {
1220 return mPolicyManager.getNetworkQuotaInfo(state);
1221 } catch (RemoteException e) {
1222 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001223 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001224 return null;
1225 } finally {
1226 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001227 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001228 }
1229
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001230 @Override
1231 public boolean isActiveNetworkMetered() {
1232 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001233 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001234 final long token = Binder.clearCallingIdentity();
1235 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001237 } finally {
1238 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001239 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001240 }
1241
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001242 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1243 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1244 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001245 try {
1246 return mPolicyManager.isNetworkMetered(state);
1247 } catch (RemoteException e) {
1248 }
1249 }
1250 return false;
1251 }
1252
Jeff Sharkey216c1812012-08-05 14:29:23 -07001253 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1254 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001255 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001256 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001257 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001258 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001259 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001260
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001261 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 * Ensure that a network route exists to deliver traffic to the specified
1263 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001264 * @param networkType the type of the network over which traffic to the
1265 * specified host is to be routed
1266 * @param hostAddress the IP address of the host to which the route is
1267 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 * @return {@code true} on success, {@code false} on failure
1269 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001270 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001272 if (mProtectedNetworks.contains(networkType)) {
1273 enforceConnectivityInternalPermission();
1274 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001275
Chad Brubakerc0234532014-02-14 13:24:29 -08001276 InetAddress addr;
1277 try {
1278 addr = InetAddress.getByAddress(hostAddress);
1279 } catch (UnknownHostException e) {
1280 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1281 return false;
1282 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001285 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 return false;
1287 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001288
1289 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1290 if (nai == null) {
1291 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1292 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1293 } else {
1294 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1295 }
1296 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001297 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001298
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001299 DetailedState netState;
1300 synchronized (nai) {
1301 netState = nai.networkInfo.getDetailedState();
1302 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001303
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001304 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001305 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001306 log("requestRouteToHostAddress on down network "
1307 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001308 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001309 }
1310 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001312
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001313 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001314 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001315 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001316 LinkProperties lp;
1317 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001318 synchronized (nai) {
1319 lp = nai.linkProperties;
1320 netId = nai.network.netId;
1321 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001322 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001323 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1324 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001325 } finally {
1326 Binder.restoreCallingIdentity(token);
1327 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001328 }
1329
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001330 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001331 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001332 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001333 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001334 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001335 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001336 if (bestRoute.getGateway().equals(addr)) {
1337 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001338 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001339 } else {
1340 // if we will connect to this through another route, add a direct route
1341 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001342 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001343 }
1344 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001345 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001346 try {
1347 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1348 } catch (Exception e) {
1349 // never crash - catch them all
1350 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001351 return false;
1352 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001353 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 }
1355
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001356 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1357 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001358 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001359 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001360 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001361 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001362 }
1363
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001364 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001365 // skip update when we've already applied rules
1366 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1367 if (oldRules == uidRules) return;
1368
1369 mUidRules.put(uid, uidRules);
1370 }
1371
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001372 // TODO: notify UID when it has requested targeted updates
1373 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001374
1375 @Override
1376 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001377 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001378 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001379 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001380 }
1381
1382 synchronized (mRulesLock) {
1383 mMeteredIfaces.clear();
1384 for (String iface : meteredIfaces) {
1385 mMeteredIfaces.add(iface);
1386 }
1387 }
1388 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001389
1390 @Override
1391 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1392 // caller is NPMS, since we only register with them
1393 if (LOGD_RULES) {
1394 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1395 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001396 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001397 };
1398
Robin Lee3b3dd942015-05-12 18:14:58 +01001399 /**
1400 * Require that the caller is either in the same user or has appropriate permission to interact
1401 * across users.
1402 *
1403 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1404 */
1405 private void enforceCrossUserPermission(int userId) {
1406 if (userId == UserHandle.getCallingUserId()) {
1407 // Not a cross-user call.
1408 return;
1409 }
1410 mContext.enforceCallingOrSelfPermission(
1411 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1412 "ConnectivityService");
1413 }
1414
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001415 private void enforceInternetPermission() {
1416 mContext.enforceCallingOrSelfPermission(
1417 android.Manifest.permission.INTERNET,
1418 "ConnectivityService");
1419 }
1420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001422 mContext.enforceCallingOrSelfPermission(
1423 android.Manifest.permission.ACCESS_NETWORK_STATE,
1424 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 }
1426
1427 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001428 mContext.enforceCallingOrSelfPermission(
1429 android.Manifest.permission.CHANGE_NETWORK_STATE,
1430 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 }
1432
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001433 private void enforceTetherAccessPermission() {
1434 mContext.enforceCallingOrSelfPermission(
1435 android.Manifest.permission.ACCESS_NETWORK_STATE,
1436 "ConnectivityService");
1437 }
1438
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001439 private void enforceConnectivityInternalPermission() {
1440 mContext.enforceCallingOrSelfPermission(
1441 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1442 "ConnectivityService");
1443 }
1444
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001445 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001446 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001447 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001448 }
1449
1450 private void sendInetConditionBroadcast(NetworkInfo info) {
1451 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1452 }
1453
Wink Saville628b0852011-08-04 15:01:58 -07001454 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001455 if (mLockdownTracker != null) {
1456 info = mLockdownTracker.augmentNetworkInfo(info);
1457 }
1458
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001459 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001460 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001461 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 if (info.isFailover()) {
1463 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1464 info.setFailover(false);
1465 }
1466 if (info.getReason() != null) {
1467 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1468 }
1469 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001470 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1471 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001473 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001474 return intent;
1475 }
1476
1477 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1478 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1479 }
1480
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001481 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001482 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1483 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1484 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001485 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001486 final long ident = Binder.clearCallingIdentity();
1487 try {
1488 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1489 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1490 } finally {
1491 Binder.restoreCallingIdentity(ident);
1492 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001493 }
1494
Mike Lockwood0f79b542009-08-14 14:18:49 -04001495 private void sendStickyBroadcast(Intent intent) {
1496 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001497 if (!mSystemReady) {
1498 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001499 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001500 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001501 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001502 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001503 }
1504
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001505 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001506 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1507 final IBatteryStats bs = BatteryStatsService.getService();
1508 try {
1509 NetworkInfo ni = intent.getParcelableExtra(
1510 ConnectivityManager.EXTRA_NETWORK_INFO);
1511 bs.noteConnectivityChanged(intent.getIntExtra(
1512 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1513 ni != null ? ni.getState().toString() : "?");
1514 } catch (RemoteException e) {
1515 }
1516 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001517 try {
1518 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1519 } finally {
1520 Binder.restoreCallingIdentity(ident);
1521 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001522 }
1523 }
1524
1525 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001526 loadGlobalProxy();
1527
Mike Lockwood0f79b542009-08-14 14:18:49 -04001528 synchronized(this) {
1529 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001530 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001531 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001532 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001533 }
1534 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001535 // load the global proxy at startup
1536 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001537
1538 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1539 // for user to unlock device.
1540 if (!updateLockdownVpn()) {
1541 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1542 mContext.registerReceiver(mUserPresentReceiver, filter);
1543 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001544
Erik Klineda4bfa82015-04-30 12:58:40 +09001545 // Configure whether mobile data is always on.
1546 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1547
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001548 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001549
1550 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 }
1552
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001553 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1554 @Override
1555 public void onReceive(Context context, Intent intent) {
1556 // Try creating lockdown tracker, since user present usually means
1557 // unlocked keystore.
1558 if (updateLockdownVpn()) {
1559 mContext.unregisterReceiver(this);
1560 }
1561 }
1562 };
1563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001565 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001566 *
1567 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001568 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001569 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001570 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1571 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001572
1573 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001574 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001575
Robert Greenwalt7b816022014-04-18 15:25:25 -07001576 if (networkAgent.networkCapabilities.hasTransport(
1577 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001578 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1579 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001580 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001581 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001582 } else if (networkAgent.networkCapabilities.hasTransport(
1583 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001584 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1585 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001586 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001587 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001588 } else {
1589 // do not track any other networks
1590 timeout = 0;
1591 }
1592
Robert Greenwalt7b816022014-04-18 15:25:25 -07001593 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001594 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001595 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001596 } catch (Exception e) {
1597 // You shall not crash!
1598 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001599 }
1600 }
1601 }
1602
1603 /**
1604 * Remove data activity tracking when network disconnects.
1605 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001606 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1607 final String iface = networkAgent.linkProperties.getInterfaceName();
1608 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001609
Robert Greenwalt7b816022014-04-18 15:25:25 -07001610 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1611 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001612 try {
1613 // the call fails silently if no idletimer setup for this interface
1614 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001615 } catch (Exception e) {
1616 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001617 }
1618 }
1619 }
1620
1621 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001622 * Reads the network specific MTU size from reources.
1623 * and set it on it's iface.
1624 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001625 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1626 final String iface = newLp.getInterfaceName();
1627 final int mtu = newLp.getMtu();
1628 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1629 if (VDBG) log("identical MTU - not setting");
1630 return;
1631 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001632
Robert Greenwalt43074032014-08-15 17:53:05 -07001633 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001634 loge("Unexpected mtu value: " + mtu + ", " + iface);
1635 return;
1636 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001637
w1997615afd812014-08-05 15:18:11 -07001638 // Cannot set MTU without interface name
1639 if (TextUtils.isEmpty(iface)) {
1640 loge("Setting MTU size with null iface.");
1641 return;
1642 }
1643
Robert Greenwalt7b816022014-04-18 15:25:25 -07001644 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001645 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001646 mNetd.setMtu(iface, mtu);
1647 } catch (Exception e) {
1648 Slog.e(TAG, "exception in setMtu()" + e);
1649 }
1650 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001651
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001652 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001653 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1654
1655 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001656 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001657 protected int getDefaultTcpRwnd() {
1658 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1659 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001660
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001661 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1662 if (isDefaultNetwork(nai) == false) {
1663 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001664 }
1665
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001666 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1667 String[] values = null;
1668 if (tcpBufferSizes != null) {
1669 values = tcpBufferSizes.split(",");
1670 }
1671
1672 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001673 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001674 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1675 values = tcpBufferSizes.split(",");
1676 }
1677
1678 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1679
1680 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001681 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001682
1683 final String prefix = "/sys/kernel/ipv4/tcp_";
1684 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1685 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1686 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1687 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1688 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1689 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1690 mCurrentTcpBufferSizes = tcpBufferSizes;
1691 } catch (IOException e) {
1692 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001693 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001694
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001695 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001696 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001697 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1698 if (rwndValue != 0) {
1699 SystemProperties.set(sysctlKey, rwndValue.toString());
1700 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001701 }
1702
Mattias Falk8b47b362011-08-23 14:15:13 +02001703 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001704 /*
1705 * Tell the VMs to toss their DNS caches
1706 */
1707 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1708 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001709 /*
1710 * Connectivity events can happen before boot has completed ...
1711 */
1712 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001713 final long ident = Binder.clearCallingIdentity();
1714 try {
1715 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1716 } finally {
1717 Binder.restoreCallingIdentity(ident);
1718 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001719 }
1720
Robert Greenwalt562cc542014-05-15 18:07:26 -07001721 @Override
1722 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001723 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1724 NETWORK_RESTORE_DELAY_PROP_NAME);
1725 if(restoreDefaultNetworkDelayStr != null &&
1726 restoreDefaultNetworkDelayStr.length() != 0) {
1727 try {
1728 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1729 } catch (NumberFormatException e) {
1730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001732 // if the system property isn't set, use the value for the apn type
1733 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1734
1735 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1736 (mNetConfigs[networkType] != null)) {
1737 ret = mNetConfigs[networkType].restoreTime;
1738 }
1739 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
1741
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001742 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001743 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001744 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001745 }
1746 return false;
1747 }
1748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001750 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1751 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001752 if (mContext.checkCallingOrSelfPermission(
1753 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001755 pw.println("Permission Denial: can't dump ConnectivityService " +
1756 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1757 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 return;
1759 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001760
Erik Kline379747a2015-06-05 17:47:34 +09001761 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001762 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001763 final long DIAG_TIME_MS = 5000;
1764 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1765 // Start gathering diagnostic information.
1766 netDiags.add(new NetworkDiagnostics(
1767 nai.network,
1768 new LinkProperties(nai.linkProperties),
1769 DIAG_TIME_MS));
1770 }
1771
1772 for (NetworkDiagnostics netDiag : netDiags) {
1773 pw.println();
1774 netDiag.waitForMeasurements();
1775 netDiag.dump(pw);
1776 }
1777
1778 return;
1779 }
1780
Lorenzo Colittie3805462015-06-03 11:18:24 +09001781 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001782 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001783 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001784 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001785 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001786 pw.println();
1787
Paul Jensen85cf78e2015-06-25 13:25:07 -04001788 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001789 pw.print("Active default network: ");
1790 if (defaultNai == null) {
1791 pw.println("none");
1792 } else {
1793 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001795 pw.println();
1796
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001797 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001798 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001799 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1800 pw.println(nai.toString());
1801 pw.increaseIndent();
1802 pw.println("Requests:");
1803 pw.increaseIndent();
1804 for (int i = 0; i < nai.networkRequests.size(); i++) {
1805 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001806 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001807 pw.decreaseIndent();
1808 pw.println("Lingered:");
1809 pw.increaseIndent();
1810 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1811 pw.decreaseIndent();
1812 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001813 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001814 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001815 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001816
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001817 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001818 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001819 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1820 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001821 }
1822 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001823 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001824
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001825 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001826
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001827 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001828 pw.print("mNetTransitionWakeLock: currently " +
1829 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1830 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1831 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1832 } else {
1833 pw.println(", last requested never");
1834 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001835 }
1836 pw.println();
1837
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001838 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001839
Lorenzo Colittie3805462015-06-03 11:18:24 +09001840 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001841 pw.println();
1842 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001843 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001844 for(int i = 0; i < mInetLog.size(); i++) {
1845 pw.println(mInetLog.get(i));
1846 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001847 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001848 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001849
1850 if (argsContain(args, "--short") == false) {
1851 pw.println();
1852 synchronized (mValidationLogs) {
1853 pw.println("mValidationLogs (most recent first):");
1854 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1855 pw.println(p.first);
1856 pw.increaseIndent();
1857 p.second.dump(fd, pw, args);
1858 pw.decreaseIndent();
1859 }
1860 }
1861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 }
1863
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001864 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001865 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001866 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001867 if (officialNai != null && officialNai.equals(nai)) return true;
1868 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001869 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001870 " - " + nai);
1871 }
1872 return false;
1873 }
1874
Paul Jensenc8b9a742014-09-30 15:37:41 -04001875 private boolean isRequest(NetworkRequest request) {
1876 return mNetworkRequests.get(request).isRequest;
1877 }
1878
Robert Greenwalt42acef32009-08-12 16:08:25 -07001879 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001880 private class NetworkStateTrackerHandler extends Handler {
1881 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001882 super(looper);
1883 }
1884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 @Override
1886 public void handleMessage(Message msg) {
1887 NetworkInfo info;
1888 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001889 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001890 handleAsyncChannelHalfConnect(msg);
1891 break;
1892 }
1893 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1894 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1895 if (nai != null) nai.asyncChannel.disconnect();
1896 break;
1897 }
1898 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1899 handleAsyncChannelDisconnected(msg);
1900 break;
1901 }
1902 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1903 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1904 if (nai == null) {
1905 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1906 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001907 final NetworkCapabilities networkCapabilities =
1908 (NetworkCapabilities)msg.obj;
1909 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1910 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1911 Slog.wtf(TAG, "BUG: " + nai + " has stateful capability.");
1912 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001913 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001914 }
1915 break;
1916 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001917 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1918 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1919 if (nai == null) {
1920 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1921 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001922 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001923 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001924 "; created=" + nai.created);
1925 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001926 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001927 synchronized (nai) {
1928 nai.linkProperties = (LinkProperties)msg.obj;
1929 }
Paul Jenseneec75412014-08-04 12:21:19 -04001930 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001931 }
1932 break;
1933 }
1934 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1935 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1936 if (nai == null) {
1937 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1938 break;
1939 }
1940 info = (NetworkInfo) msg.obj;
1941 updateNetworkInfo(nai, info);
1942 break;
1943 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001944 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1945 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1946 if (nai == null) {
1947 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1948 break;
1949 }
1950 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001951 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001952 break;
1953 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001954 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1955 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1956 if (nai == null) {
1957 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1958 break;
1959 }
1960 try {
1961 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001962 } catch (Exception e) {
1963 // Never crash!
1964 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001965 }
1966 break;
1967 }
1968 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1969 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1970 if (nai == null) {
1971 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1972 break;
1973 }
1974 try {
1975 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001976 } catch (Exception e) {
1977 // Never crash!
1978 loge("Exception in removeVpnUidRanges: " + e);
1979 }
1980 break;
1981 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001982 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1983 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1984 if (nai == null) {
1985 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1986 break;
1987 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001988 if (nai.created && !nai.networkMisc.explicitlySelected) {
1989 loge("ERROR: created network explicitly selected.");
1990 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001991 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001992 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001993 break;
1994 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001995 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001996 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001997 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1998 final boolean valid =
1999 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002000 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2001 if (valid != nai.lastValidated) {
2002 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002003 nai.lastValidated = valid;
2004 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002005 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002006 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2007 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002008 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002009 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002010 // Let the NetworkAgent know the state of its network
2011 nai.asyncChannel.sendMessage(
2012 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2013 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2014 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002015 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002016 break;
2017 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002018 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002019 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002020 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2021 handleLingerComplete(nai);
2022 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002023 break;
2024 }
Paul Jensen869868be2014-05-15 10:33:05 -04002025 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002026 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002027 final boolean visible = (msg.arg1 != 0);
2028 final NetworkAgentInfo nai;
2029 synchronized (mNetworkForNetId) {
2030 nai = mNetworkForNetId.get(netId);
2031 }
2032 // If captive portal status has changed, update capabilities.
2033 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2034 nai.lastCaptivePortalDetected = visible;
2035 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002036 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002037 }
2038 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002039 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002040 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002041 if (nai == null) {
2042 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2043 break;
2044 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002045 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002046 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2047 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002048 }
Paul Jensen869868be2014-05-15 10:33:05 -04002049 break;
2050 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002051 }
2052 }
2053 }
2054
Paul Jensen85cf78e2015-06-25 13:25:07 -04002055 private void linger(NetworkAgentInfo nai) {
2056 nai.lingering = true;
2057 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2058 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2059 }
2060
Paul Jensen0cc17322014-11-25 15:26:53 -05002061 // Cancel any lingering so the linger timeout doesn't teardown a network.
2062 // This should be called when a network begins satisfying a NetworkRequest.
2063 // Note: depending on what state the NetworkMonitor is in (e.g.,
2064 // if it's awaiting captive portal login, or if validation failed), this
2065 // may trigger a re-evaluation of the network.
2066 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002067 nai.networkLingered.clear();
2068 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002069 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002070 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002071 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2072 }
2073
Robert Greenwalt7b816022014-04-18 15:25:25 -07002074 private void handleAsyncChannelHalfConnect(Message msg) {
2075 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002076 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002077 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2078 if (VDBG) log("NetworkFactory connected");
2079 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002080 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002081 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002082 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002083 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002084 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002085 }
2086 } else {
2087 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002088 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002089 }
2090 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2091 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2092 if (VDBG) log("NetworkAgent connected");
2093 // A network agent has requested a connection. Establish the connection.
2094 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2095 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2096 } else {
2097 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002098 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002099 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002100 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002101 synchronized (mNetworkForNetId) {
2102 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002103 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002104 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002105 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002106 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002107 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002108 }
2109 }
2110 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002111
Robert Greenwalt7b816022014-04-18 15:25:25 -07002112 private void handleAsyncChannelDisconnected(Message msg) {
2113 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2114 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002115 if (DBG) {
2116 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2117 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002118 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002119 // TODO - if we move the logic to the network agent (have them disconnect
2120 // because they lost all their requests or because their score isn't good)
2121 // then they would disconnect organically, report their new state and then
2122 // disconnect the channel.
2123 if (nai.networkInfo.isConnected()) {
2124 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2125 null, null);
2126 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002127 final boolean wasDefault = isDefaultNetwork(nai);
2128 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002129 mDefaultInetConditionPublished = 0;
2130 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002131 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002132 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002133 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002134 mNetworkAgentInfos.remove(msg.replyTo);
2135 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002136 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002137 // Remove the NetworkAgent, but don't mark the netId as
2138 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002139 mNetworkForNetId.remove(nai.network.netId);
2140 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002141 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002142 for (int i = 0; i < nai.networkRequests.size(); i++) {
2143 NetworkRequest request = nai.networkRequests.valueAt(i);
2144 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2145 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2146 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002147 sendUpdatedScoreToFactories(request, 0);
2148 }
2149 }
2150 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2151 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002152 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002153 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002154 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002155 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002156 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002157 if (nai.created) {
2158 // Tell netd to clean up the configuration for this network
2159 // (routing rules, DNS, etc).
2160 // This may be slow as it requires a lot of netd shelling out to ip and
2161 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2162 // after we've rematched networks with requests which should make a potential
2163 // fallback network the default or requested a new network from the
2164 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2165 // long time.
2166 try {
2167 mNetd.removeNetwork(nai.network.netId);
2168 } catch (Exception e) {
2169 loge("Exception removing network: " + e);
2170 }
2171 }
2172 synchronized (mNetworkForNetId) {
2173 mNetIdInUse.delete(nai.network.netId);
2174 }
2175 } else {
2176 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2177 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002178 }
2179 }
2180
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002181 // If this method proves to be too slow then we can maintain a separate
2182 // pendingIntent => NetworkRequestInfo map.
2183 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2184 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2185 Intent intent = pendingIntent.getIntent();
2186 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2187 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2188 if (existingPendingIntent != null &&
2189 existingPendingIntent.getIntent().filterEquals(intent)) {
2190 return entry.getValue();
2191 }
2192 }
2193 return null;
2194 }
2195
2196 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2197 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2198
2199 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2200 if (existingRequest != null) { // remove the existing request.
2201 if (DBG) log("Replacing " + existingRequest.request + " with "
2202 + nri.request + " because their intents matched.");
2203 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2204 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002205 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002206 }
2207
Erik Klineda4bfa82015-04-30 12:58:40 +09002208 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002209 mNetworkRequests.put(nri.request, nri);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002210 rematchAllNetworksAndRequests(null, 0);
2211 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2212 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002213 }
2214 }
2215
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002216 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2217 int callingUid) {
2218 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2219 if (nri != null) {
2220 handleReleaseNetworkRequest(nri.request, callingUid);
2221 }
2222 }
2223
Paul Jensen99364842014-12-09 11:43:45 -05002224 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002225 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2226 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002227 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002228 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002229 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2230 // If this Network is already the highest scoring Network for a request, or if
2231 // there is hope for it to become one if it validated, then it is needed.
2232 if (nri.isRequest && nai.satisfies(nri.request) &&
2233 (nai.networkRequests.get(nri.request.requestId) != null ||
2234 // Note that this catches two important cases:
2235 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2236 // is currently satisfying the request. This is desirable when
2237 // cellular ends up validating but WiFi does not.
2238 // 2. Unvalidated WiFi will not be reaped when validated cellular
2239 // is currently satsifying the request. This is desirable when
2240 // WiFi ends up validating and out scoring cellular.
2241 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2242 nai.getCurrentScoreAsValidated())) {
2243 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002244 }
2245 }
Paul Jensene0988542015-06-25 15:30:08 -04002246 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002247 }
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 Jensencee9b512015-05-06 07:32:40 -04002665 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002666 // this information is already available as a world read/writable jvm property
2667 // so this API change wouldn't have a benifit. It also breaks the passing
2668 // of proxy info to all the JVMs.
2669 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002670 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002671 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002672 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2673 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002674 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002675 }
2676
Paul Jensencee9b512015-05-06 07:32:40 -04002677 public ProxyInfo getProxyForNetwork(Network network) {
2678 if (network == null) return getDefaultProxy();
2679 final ProxyInfo globalProxy = getGlobalProxy();
2680 if (globalProxy != null) return globalProxy;
2681 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2682 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2683 // caller may not have.
2684 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2685 if (nai == null) return null;
2686 synchronized (nai) {
2687 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2688 if (proxyInfo == null) return null;
2689 return new ProxyInfo(proxyInfo);
2690 }
2691 }
2692
Paul Jensene0bef712014-12-10 15:12:18 -05002693 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2694 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2695 // proxy is null then there is no proxy in place).
2696 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2697 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2698 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2699 proxy = null;
2700 }
2701 return proxy;
2702 }
2703
2704 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2705 // better for determining if a new proxy broadcast is necessary:
2706 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2707 // avoid unnecessary broadcasts.
2708 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2709 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2710 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2711 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2712 // all set.
2713 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2714 a = canonicalizeProxyInfo(a);
2715 b = canonicalizeProxyInfo(b);
2716 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2717 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2718 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2719 }
2720
Jason Monk207900c2014-04-25 15:00:09 -04002721 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002722 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002723
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002724 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002725 if (proxyProperties == mGlobalProxy) return;
2726 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2727 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2728
2729 String host = "";
2730 int port = 0;
2731 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002732 String pacFileUrl = "";
2733 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002734 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002735 if (!proxyProperties.isValid()) {
2736 if (DBG)
2737 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2738 return;
2739 }
Jason Monk207900c2014-04-25 15:00:09 -04002740 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002741 host = mGlobalProxy.getHost();
2742 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002743 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002744 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002745 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002746 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002747 } else {
2748 mGlobalProxy = null;
2749 }
2750 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002751 final long token = Binder.clearCallingIdentity();
2752 try {
2753 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2754 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2755 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2756 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002757 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002758 } finally {
2759 Binder.restoreCallingIdentity(token);
2760 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002761
Jason Monkcf0f97a2014-10-02 15:39:38 -04002762 if (mGlobalProxy == null) {
2763 proxyProperties = mDefaultProxy;
2764 }
2765 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002766 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002767 }
2768
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002769 private void loadGlobalProxy() {
2770 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002771 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2772 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2773 String exclList = Settings.Global.getString(res,
2774 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002775 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2776 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002777 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002778 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002779 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002780 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002781 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002782 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002783 if (!proxyProperties.isValid()) {
2784 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2785 return;
2786 }
2787
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002788 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002789 mGlobalProxy = proxyProperties;
2790 }
2791 }
2792 }
2793
Jason Monk207900c2014-04-25 15:00:09 -04002794 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002795 // this information is already available as a world read/writable jvm property
2796 // so this API change wouldn't have a benifit. It also breaks the passing
2797 // of proxy info to all the JVMs.
2798 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002799 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002800 return mGlobalProxy;
2801 }
2802 }
2803
Jason Monk207900c2014-04-25 15:00:09 -04002804 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002805 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002806 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002807 proxy = null;
2808 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002809 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002810 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002811 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002812 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002813 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2814 return;
2815 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002816
2817 // This call could be coming from the PacManager, containing the port of the local
2818 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2819 // global (to get the correct local port), and send a broadcast.
2820 // TODO: Switch PacManager to have its own message to send back rather than
2821 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002822 if ((mGlobalProxy != null) && (proxy != null)
2823 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002824 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2825 mGlobalProxy = proxy;
2826 sendProxyBroadcast(mGlobalProxy);
2827 return;
2828 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002829 mDefaultProxy = proxy;
2830
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002831 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002832 if (!mDefaultProxyDisabled) {
2833 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002834 }
2835 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002836 }
2837
Paul Jensene0bef712014-12-10 15:12:18 -05002838 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2839 // This method gets called when any network changes proxy, but the broadcast only ever contains
2840 // the default proxy (even if it hasn't changed).
2841 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2842 // world where an app might be bound to a non-default network.
2843 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2844 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2845 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2846
2847 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2848 sendProxyBroadcast(getDefaultProxy());
2849 }
2850 }
2851
Robert Greenwalt434203a2010-10-11 16:00:27 -07002852 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002853 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2854 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002855 if (!TextUtils.isEmpty(proxy)) {
2856 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002857 if (data.length == 0) {
2858 return;
2859 }
2860
Robert Greenwalt434203a2010-10-11 16:00:27 -07002861 String proxyHost = data[0];
2862 int proxyPort = 8080;
2863 if (data.length > 1) {
2864 try {
2865 proxyPort = Integer.parseInt(data[1]);
2866 } catch (NumberFormatException e) {
2867 return;
2868 }
2869 }
Jason Monk207900c2014-04-25 15:00:09 -04002870 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002871 setGlobalProxy(p);
2872 }
2873 }
2874
Jason Monk207900c2014-04-25 15:00:09 -04002875 private void sendProxyBroadcast(ProxyInfo proxy) {
2876 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002877 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002878 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002879 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002880 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2881 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002882 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002883 final long ident = Binder.clearCallingIdentity();
2884 try {
2885 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2886 } finally {
2887 Binder.restoreCallingIdentity(ident);
2888 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002889 }
2890
2891 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002892 final private HashMap<Uri, Integer> mUriEventMap;
2893 final private Context mContext;
2894 final private Handler mHandler;
2895
2896 SettingsObserver(Context context, Handler handler) {
2897 super(null);
2898 mUriEventMap = new HashMap<Uri, Integer>();
2899 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002900 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002901 }
2902
Erik Klineda4bfa82015-04-30 12:58:40 +09002903 void observe(Uri uri, int what) {
2904 mUriEventMap.put(uri, what);
2905 final ContentResolver resolver = mContext.getContentResolver();
2906 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002907 }
2908
2909 @Override
2910 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002911 Slog.wtf(TAG, "Should never be reached.");
2912 }
2913
2914 @Override
2915 public void onChange(boolean selfChange, Uri uri) {
2916 final Integer what = mUriEventMap.get(uri);
2917 if (what != null) {
2918 mHandler.obtainMessage(what.intValue()).sendToTarget();
2919 } else {
2920 loge("No matching event to send for URI=" + uri);
2921 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002922 }
2923 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002924
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002925 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002926 Slog.d(TAG, s);
2927 }
2928
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002929 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002930 Slog.e(TAG, s);
2931 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002932
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002933 private static <T> T checkNotNull(T value, String message) {
2934 if (value == null) {
2935 throw new NullPointerException(message);
2936 }
2937 return value;
2938 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002939
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002940 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002941 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002942 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2943 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2944 *
2945 * @param oldPackage Package name of the application which currently controls VPN, which will
2946 * be replaced. If there is no such application, this should should either be
2947 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2948 * @param newPackage Package name of the application which should gain control of VPN, or
2949 * {@code null} to disable.
2950 * @param userId User for whom to prepare the new VPN.
2951 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002952 * @hide
2953 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002954 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002955 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2956 int userId) {
2957 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002958 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01002959
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002960 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07002961 Vpn vpn = mVpns.get(userId);
2962 if (vpn != null) {
2963 return vpn.prepare(oldPackage, newPackage);
2964 } else {
2965 return false;
2966 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002967 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002968 }
2969
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002970 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01002971 * Set whether the VPN package has the ability to launch VPNs without user intervention.
2972 * This method is used by system-privileged apps.
2973 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2974 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2975 *
2976 * @param packageName The package for which authorization state should change.
2977 * @param userId User for whom {@code packageName} is installed.
2978 * @param authorized {@code true} if this app should be able to start a VPN connection without
2979 * explicit user approval, {@code false} if not.
2980 *
Jeff Davidson05542602014-08-11 14:07:27 -07002981 * @hide
2982 */
2983 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002984 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
2985 enforceCrossUserPermission(userId);
2986
Jeff Davidson05542602014-08-11 14:07:27 -07002987 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07002988 Vpn vpn = mVpns.get(userId);
2989 if (vpn != null) {
2990 vpn.setPackageAuthorization(packageName, authorized);
2991 }
Jeff Davidson05542602014-08-11 14:07:27 -07002992 }
2993 }
2994
2995 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002996 * Configure a TUN interface and return its file descriptor. Parameters
2997 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002998 * and not available in ConnectivityManager. Permissions are checked in
2999 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003000 * @hide
3001 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003002 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003003 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003004 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003005 int user = UserHandle.getUserId(Binder.getCallingUid());
3006 synchronized(mVpns) {
3007 return mVpns.get(user).establish(config);
3008 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003009 }
3010
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003011 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003012 * Start legacy VPN, controlling native daemons as needed. Creates a
3013 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003014 */
3015 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003016 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003017 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003018 final LinkProperties egress = getActiveLinkProperties();
3019 if (egress == null) {
3020 throw new IllegalStateException("Missing active network connection");
3021 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003022 int user = UserHandle.getUserId(Binder.getCallingUid());
3023 synchronized(mVpns) {
3024 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3025 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003026 }
3027
3028 /**
3029 * Return the information of the ongoing legacy VPN. This method is used
3030 * by VpnSettings and not available in ConnectivityManager. Permissions
3031 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003032 */
3033 @Override
3034 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003035 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003036 int user = UserHandle.getUserId(Binder.getCallingUid());
3037 synchronized(mVpns) {
3038 return mVpns.get(user).getLegacyVpnInfo();
3039 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003040 }
3041
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003042 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003043 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3044 * and not available in ConnectivityManager.
3045 */
3046 @Override
3047 public VpnInfo[] getAllVpnInfo() {
3048 enforceConnectivityInternalPermission();
3049 if (mLockdownEnabled) {
3050 return new VpnInfo[0];
3051 }
3052
3053 synchronized(mVpns) {
3054 List<VpnInfo> infoList = new ArrayList<>();
3055 for (int i = 0; i < mVpns.size(); i++) {
3056 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3057 if (info != null) {
3058 infoList.add(info);
3059 }
3060 }
3061 return infoList.toArray(new VpnInfo[infoList.size()]);
3062 }
3063 }
3064
3065 /**
3066 * @return VPN information for accounting, or null if we can't retrieve all required
3067 * information, e.g primary underlying iface.
3068 */
3069 @Nullable
3070 private VpnInfo createVpnInfo(Vpn vpn) {
3071 VpnInfo info = vpn.getVpnInfo();
3072 if (info == null) {
3073 return null;
3074 }
3075 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3076 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3077 // the underlyingNetworks list.
3078 if (underlyingNetworks == null) {
3079 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3080 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3081 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3082 }
3083 } else if (underlyingNetworks.length > 0) {
3084 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3085 if (linkProperties != null) {
3086 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3087 }
3088 }
3089 return info.primaryUnderlyingIface == null ? null : info;
3090 }
3091
3092 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003093 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3094 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003095 * Permissions are checked in Vpn class.
3096 * @hide
3097 */
3098 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003099 public VpnConfig getVpnConfig(int userId) {
3100 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003101 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003102 Vpn vpn = mVpns.get(userId);
3103 if (vpn != null) {
3104 return vpn.getVpnConfig();
3105 } else {
3106 return null;
3107 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003108 }
3109 }
3110
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003111 @Override
3112 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003113 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3114 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3115 return false;
3116 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003117
3118 // Tear down existing lockdown if profile was removed
3119 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3120 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003121 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003122 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3123 return false;
3124 }
3125
3126 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3127 final VpnProfile profile = VpnProfile.decode(
3128 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003129 int user = UserHandle.getUserId(Binder.getCallingUid());
3130 synchronized(mVpns) {
3131 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3132 profile));
3133 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003134 } else {
3135 setLockdownTracker(null);
3136 }
3137
3138 return true;
3139 }
3140
3141 /**
3142 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3143 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3144 */
3145 private void setLockdownTracker(LockdownVpnTracker tracker) {
3146 // Shutdown any existing tracker
3147 final LockdownVpnTracker existing = mLockdownTracker;
3148 mLockdownTracker = null;
3149 if (existing != null) {
3150 existing.shutdown();
3151 }
3152
3153 try {
3154 if (tracker != null) {
3155 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003156 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003157 mLockdownTracker = tracker;
3158 mLockdownTracker.init();
3159 } else {
3160 mNetd.setFirewallEnabled(false);
3161 }
3162 } catch (RemoteException e) {
3163 // ignored; NMS lives inside system_server
3164 }
3165 }
3166
3167 private void throwIfLockdownEnabled() {
3168 if (mLockdownEnabled) {
3169 throw new IllegalStateException("Unavailable in lockdown mode");
3170 }
3171 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003172
Wink Savilleab9321d2013-06-29 21:10:57 -07003173 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003174 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003175 // TODO: Remove? Any reason to trigger a provisioning check?
3176 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003177 }
3178
3179 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003180 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003181
Paul Jensen89e0f092014-09-15 15:59:36 -04003182 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003183 if (DBG) {
3184 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003185 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003186 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003187 Intent intent = new Intent(action);
3188 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003189 // Concatenate the range of types onto the range of NetIDs.
3190 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003191 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003192 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003193 }
3194
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003195 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003196 * Show or hide network provisioning notifications.
3197 *
3198 * We use notifications for two purposes: to notify that a network requires sign in
3199 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3200 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3201 * particular network we can display the notification type that was most recently requested.
3202 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3203 * might first display NO_INTERNET, and then when the captive portal check completes, display
3204 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003205 *
3206 * @param id an identifier that uniquely identifies this notification. This must match
3207 * between show and hide calls. We use the NetID value but for legacy callers
3208 * we concatenate the range of types with the range of NetIDs.
3209 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003210 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003211 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3212 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003213 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003214 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3215 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003216 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003217 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003218
3219 Resources r = Resources.getSystem();
3220 NotificationManager notificationManager = (NotificationManager) mContext
3221 .getSystemService(Context.NOTIFICATION_SERVICE);
3222
3223 if (visible) {
3224 CharSequence title;
3225 CharSequence details;
3226 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003227 if (notifyType == NotificationType.NO_INTERNET &&
3228 networkType == ConnectivityManager.TYPE_WIFI) {
3229 title = r.getString(R.string.wifi_no_internet, 0);
3230 details = r.getString(R.string.wifi_no_internet_detailed);
3231 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3232 } else if (notifyType == NotificationType.SIGN_IN) {
3233 switch (networkType) {
3234 case ConnectivityManager.TYPE_WIFI:
3235 title = r.getString(R.string.wifi_available_sign_in, 0);
3236 details = r.getString(R.string.network_available_sign_in_detailed,
3237 extraInfo);
3238 icon = R.drawable.stat_notify_wifi_in_range;
3239 break;
3240 case ConnectivityManager.TYPE_MOBILE:
3241 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3242 title = r.getString(R.string.network_available_sign_in, 0);
3243 // TODO: Change this to pull from NetworkInfo once a printable
3244 // name has been added to it
3245 details = mTelephonyManager.getNetworkOperatorName();
3246 icon = R.drawable.stat_notify_rssi_in_range;
3247 break;
3248 default:
3249 title = r.getString(R.string.network_available_sign_in, 0);
3250 details = r.getString(R.string.network_available_sign_in_detailed,
3251 extraInfo);
3252 icon = R.drawable.stat_notify_rssi_in_range;
3253 break;
3254 }
3255 } else {
3256 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3257 + getNetworkTypeName(networkType));
3258 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003259 }
3260
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003261 Notification notification = new Notification.Builder(mContext)
3262 .setWhen(0)
3263 .setSmallIcon(icon)
3264 .setAutoCancel(true)
3265 .setTicker(title)
3266 .setColor(mContext.getColor(
3267 com.android.internal.R.color.system_notification_accent_color))
3268 .setContentTitle(title)
3269 .setContentText(details)
3270 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003271 .setLocalOnly(true)
3272 .setPriority(highPriority ?
3273 Notification.PRIORITY_HIGH :
3274 Notification.PRIORITY_DEFAULT)
3275 .setDefaults(Notification.DEFAULT_ALL)
3276 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003277 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003278
Wink Saville948282b2013-08-29 08:55:16 -07003279 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003280 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003281 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003282 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003283 npe.printStackTrace();
3284 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003285 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003286 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003287 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003288 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003289 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003290 npe.printStackTrace();
3291 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003292 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003293 }
3294
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003295 /** Location to an updatable file listing carrier provisioning urls.
3296 * An example:
3297 *
3298 * <?xml version="1.0" encoding="utf-8"?>
3299 * <provisioningUrls>
3300 * <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 -07003301 * </provisioningUrls>
3302 */
3303 private static final String PROVISIONING_URL_PATH =
3304 "/data/misc/radio/provisioning_urls.xml";
3305 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003306
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003307 /** XML tag for root element. */
3308 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3309 /** XML tag for individual url */
3310 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003311 /** XML attribute for mcc */
3312 private static final String ATTR_MCC = "mcc";
3313 /** XML attribute for mnc */
3314 private static final String ATTR_MNC = "mnc";
3315
Paul Jensen434dde82015-06-11 09:43:30 -04003316 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003317 FileReader fileReader = null;
3318 XmlPullParser parser = null;
3319 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003320
3321 try {
3322 fileReader = new FileReader(mProvisioningUrlFile);
3323 parser = Xml.newPullParser();
3324 parser.setInput(fileReader);
3325 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3326
3327 while (true) {
3328 XmlUtils.nextElement(parser);
3329
3330 String element = parser.getName();
3331 if (element == null) break;
3332
Paul Jensen434dde82015-06-11 09:43:30 -04003333 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003334 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3335 try {
3336 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3337 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3338 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3339 parser.next();
3340 if (parser.getEventType() == XmlPullParser.TEXT) {
3341 return parser.getText();
3342 }
3343 }
3344 }
3345 } catch (NumberFormatException e) {
3346 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3347 }
3348 }
3349 }
3350 return null;
3351 } catch (FileNotFoundException e) {
3352 loge("Carrier Provisioning Urls file not found");
3353 } catch (XmlPullParserException e) {
3354 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3355 } catch (IOException e) {
3356 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3357 } finally {
3358 if (fileReader != null) {
3359 try {
3360 fileReader.close();
3361 } catch (IOException e) {}
3362 }
3363 }
3364 return null;
3365 }
3366
Wink Saville42d4f082013-07-20 20:31:59 -07003367 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003368 public String getMobileProvisioningUrl() {
3369 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003370 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003371 if (TextUtils.isEmpty(url)) {
3372 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003373 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003374 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003375 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003376 }
Wink Saville8cf35602013-07-10 23:00:07 -07003377 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003378 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003379 String phoneNumber = mTelephonyManager.getLine1Number();
3380 if (TextUtils.isEmpty(phoneNumber)) {
3381 phoneNumber = "0000000000";
3382 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003383 url = String.format(url,
3384 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3385 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003386 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003387 }
3388
Wink Savilleab9321d2013-06-29 21:10:57 -07003389 return url;
3390 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003391
Wink Saville948282b2013-08-29 08:55:16 -07003392 @Override
3393 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003394 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003395 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003396 final long ident = Binder.clearCallingIdentity();
3397 try {
3398 setProvNotificationVisible(visible, networkType, action);
3399 } finally {
3400 Binder.restoreCallingIdentity(ident);
3401 }
Wink Saville948282b2013-08-29 08:55:16 -07003402 }
Wink Saville7788c612013-08-29 14:57:08 -07003403
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003404 @Override
3405 public void setAirplaneMode(boolean enable) {
3406 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003407 final long ident = Binder.clearCallingIdentity();
3408 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003409 final ContentResolver cr = mContext.getContentResolver();
3410 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3411 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3412 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003413 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003414 } finally {
3415 Binder.restoreCallingIdentity(ident);
3416 }
3417 }
3418
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003419 private void onUserStart(int userId) {
3420 synchronized(mVpns) {
3421 Vpn userVpn = mVpns.get(userId);
3422 if (userVpn != null) {
3423 loge("Starting user already has a VPN");
3424 return;
3425 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003426 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003427 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003428 }
3429 }
3430
3431 private void onUserStop(int userId) {
3432 synchronized(mVpns) {
3433 Vpn userVpn = mVpns.get(userId);
3434 if (userVpn == null) {
3435 loge("Stopping user has no VPN");
3436 return;
3437 }
3438 mVpns.delete(userId);
3439 }
3440 }
3441
3442 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3443 @Override
3444 public void onReceive(Context context, Intent intent) {
3445 final String action = intent.getAction();
3446 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3447 if (userId == UserHandle.USER_NULL) return;
3448
3449 if (Intent.ACTION_USER_STARTING.equals(action)) {
3450 onUserStart(userId);
3451 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3452 onUserStop(userId);
3453 }
3454 }
3455 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003456
Robert Greenwalta67be032014-05-16 15:49:14 -07003457 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3458 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003459 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3460 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003461
Robert Greenwalta67be032014-05-16 15:49:14 -07003462 private static class NetworkFactoryInfo {
3463 public final String name;
3464 public final Messenger messenger;
3465 public final AsyncChannel asyncChannel;
3466
3467 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3468 this.name = name;
3469 this.messenger = messenger;
3470 this.asyncChannel = asyncChannel;
3471 }
3472 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003473
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003474 /**
3475 * Tracks info about the requester.
3476 * Also used to notice when the calling process dies so we can self-expire
3477 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003478 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3479 static final boolean REQUEST = true;
3480 static final boolean LISTEN = false;
3481
3482 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003483 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003484 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003485 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003486 final int mPid;
3487 final int mUid;
3488 final Messenger messenger;
3489 final boolean isRequest;
3490
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003491 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3492 request = r;
3493 mPendingIntent = pi;
3494 messenger = null;
3495 mBinder = null;
3496 mPid = getCallingPid();
3497 mUid = getCallingUid();
3498 this.isRequest = isRequest;
3499 }
3500
Robert Greenwalt9258c642014-03-26 16:47:06 -07003501 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3502 super();
3503 messenger = m;
3504 request = r;
3505 mBinder = binder;
3506 mPid = getCallingPid();
3507 mUid = getCallingUid();
3508 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003509 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003510
3511 try {
3512 mBinder.linkToDeath(this, 0);
3513 } catch (RemoteException e) {
3514 binderDied();
3515 }
3516 }
3517
3518 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003519 if (mBinder != null) {
3520 mBinder.unlinkToDeath(this, 0);
3521 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003522 }
3523
3524 public void binderDied() {
3525 log("ConnectivityService NetworkRequestInfo binderDied(" +
3526 request + ", " + mBinder + ")");
3527 releaseNetworkRequest(request);
3528 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003529
3530 public String toString() {
3531 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003532 mPid + " for " + request +
3533 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003534 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003535 }
3536
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003537 private void ensureImmutableCapabilities(NetworkCapabilities networkCapabilities) {
3538 if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
3539 throw new IllegalArgumentException(
3540 "Cannot request network with NET_CAPABILITY_VALIDATED");
3541 }
3542 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
3543 throw new IllegalArgumentException(
3544 "Cannot request network with NET_CAPABILITY_CAPTIVE_PORTAL");
3545 }
3546 }
3547
Robert Greenwalt9258c642014-03-26 16:47:06 -07003548 @Override
3549 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003550 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003551 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003552 enforceNetworkRequestPermissions(networkCapabilities);
3553 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003554 ensureImmutableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003555
Robert Greenwalt6078b502014-06-11 16:05:07 -07003556 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003557 throw new IllegalArgumentException("Bad timeout specified");
3558 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003559
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003560 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3561 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003562 if (DBG) log("requestNetwork for " + networkRequest);
3563 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3564 NetworkRequestInfo.REQUEST);
3565
3566 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003567 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003568 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003569 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003570 }
3571 return networkRequest;
3572 }
3573
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003574 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003575 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003576 enforceConnectivityInternalPermission();
3577 } else {
3578 enforceChangePermission();
3579 }
3580 }
3581
fenglub15e72b2015-03-20 11:29:56 -07003582 @Override
fengludb571472015-04-21 17:12:05 -07003583 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003584 enforceAccessPermission();
3585 NetworkAgentInfo nai = null;
3586 if (network == null) {
3587 return false;
3588 }
3589 synchronized (mNetworkForNetId) {
3590 nai = mNetworkForNetId.get(network.netId);
3591 }
3592 if (nai != null) {
3593 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3594 return true;
3595 }
3596 return false;
3597 }
3598
3599
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003600 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3601 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003602 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003603 final int uidRules;
3604 final int uid = Binder.getCallingUid();
3605 synchronized(mRulesLock) {
3606 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3607 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003608 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003609 // we could silently fail or we can filter the available nets to only give
3610 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003611 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003612 }
3613 }
3614 }
3615
Robert Greenwalt9258c642014-03-26 16:47:06 -07003616 @Override
3617 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3618 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003619 checkNotNull(operation, "PendingIntent cannot be null.");
3620 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3621 enforceNetworkRequestPermissions(networkCapabilities);
3622 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003623 ensureImmutableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003624
3625 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3626 nextNetworkRequestId());
3627 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3628 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3629 NetworkRequestInfo.REQUEST);
3630 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3631 nri));
3632 return networkRequest;
3633 }
3634
Jeremy Joslin79294842014-12-03 17:15:28 -08003635 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3636 mHandler.sendMessageDelayed(
3637 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3638 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3639 }
3640
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003641 @Override
3642 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003643 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003644 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3645 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003646 }
3647
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003648 // In order to implement the compatibility measure for pre-M apps that call
3649 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3650 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3651 // This ensures it has permission to do so.
3652 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3653 if (nc == null) {
3654 return false;
3655 }
3656 int[] transportTypes = nc.getTransportTypes();
3657 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3658 return false;
3659 }
3660 try {
3661 mContext.enforceCallingOrSelfPermission(
3662 android.Manifest.permission.ACCESS_WIFI_STATE,
3663 "ConnectivityService");
3664 } catch (SecurityException e) {
3665 return false;
3666 }
3667 return true;
3668 }
3669
Robert Greenwalt9258c642014-03-26 16:47:06 -07003670 @Override
3671 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3672 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003673 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3674 enforceAccessPermission();
3675 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003676
3677 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003678 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003679 if (DBG) log("listenForNetwork for " + networkRequest);
3680 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3681 NetworkRequestInfo.LISTEN);
3682
3683 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3684 return networkRequest;
3685 }
3686
3687 @Override
3688 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3689 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003690 checkNotNull(operation, "PendingIntent cannot be null.");
3691 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3692 enforceAccessPermission();
3693 }
3694
3695 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3696 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3697 if (DBG) log("pendingListenForNetwork for " + networkRequest + " to trigger " + operation);
3698 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3699 NetworkRequestInfo.LISTEN);
3700
3701 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003702 }
3703
3704 @Override
3705 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003706 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3707 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003708 }
3709
3710 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003711 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003712 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003713 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3714 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003715 }
3716
Robert Greenwalta67be032014-05-16 15:49:14 -07003717 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003718 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003719 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3720 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3721 }
3722
3723 @Override
3724 public void unregisterNetworkFactory(Messenger messenger) {
3725 enforceConnectivityInternalPermission();
3726 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3727 }
3728
3729 private void handleUnregisterNetworkFactory(Messenger messenger) {
3730 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3731 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003732 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003733 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003734 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003735 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003736 }
3737
Robert Greenwalt7b816022014-04-18 15:25:25 -07003738 /**
3739 * NetworkAgentInfo supporting a request by requestId.
3740 * These have already been vetted (their Capabilities satisfy the request)
3741 * and the are the highest scored network available.
3742 * the are keyed off the Requests requestId.
3743 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003744 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003745 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3746 new SparseArray<NetworkAgentInfo>();
3747
Paul Jensen31a94f42015-02-13 14:18:39 -05003748 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3749 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003750 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3751 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003752 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3753 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3754 // there may not be a strict 1:1 correlation between the two.
3755 @GuardedBy("mNetworkForNetId")
3756 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003757
Robert Greenwalt7b816022014-04-18 15:25:25 -07003758 // NetworkAgentInfo keyed off its connecting messenger
3759 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003760 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003761 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3762 new HashMap<Messenger, NetworkAgentInfo>();
3763
Paul Jensen2c311d62014-11-17 12:34:51 -05003764 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003765 private final NetworkRequest mDefaultRequest;
3766
Erik Klineda4bfa82015-04-30 12:58:40 +09003767 // Request used to optionally keep mobile data active even when higher
3768 // priority networks like Wi-Fi are active.
3769 private final NetworkRequest mDefaultMobileDataRequest;
3770
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003771 private NetworkAgentInfo getDefaultNetwork() {
3772 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3773 }
3774
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003775 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003776 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003777 }
3778
Paul Jensen31a94f42015-02-13 14:18:39 -05003779 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003780 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003781 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003782 enforceConnectivityInternalPermission();
3783
Paul Jensen2c311d62014-11-17 12:34:51 -05003784 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3785 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003786 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003787 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3788 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3789 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003790 synchronized (this) {
3791 nai.networkMonitor.systemReady = mSystemReady;
3792 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003793 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003794 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003795 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003796 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003797 }
3798
3799 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3800 if (VDBG) log("Got NetworkAgent Messenger");
3801 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003802 synchronized (mNetworkForNetId) {
3803 mNetworkForNetId.put(na.network.netId, na);
3804 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003805 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3806 NetworkInfo networkInfo = na.networkInfo;
3807 na.networkInfo = null;
3808 updateNetworkInfo(na, networkInfo);
3809 }
3810
3811 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3812 LinkProperties newLp = networkAgent.linkProperties;
3813 int netId = networkAgent.network.netId;
3814
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003815 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3816 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003817 if (networkAgent.clatd != null) {
3818 networkAgent.clatd.fixupLinkProperties(oldLp);
3819 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003820
Paul Jensen992f2522014-04-28 10:33:11 -04003821 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003822 updateMtu(newLp, oldLp);
3823 // TODO - figure out what to do for clat
3824// for (LinkProperties lp : newLp.getStackedLinks()) {
3825// updateMtu(lp, null);
3826// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003827 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003828
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003829 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3830 // In L, we used it only when the network had Internet access but provided no DNS servers.
3831 // For now, just disable it, and if disabling it doesn't break things, remove it.
3832 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3833 // NET_CAPABILITY_INTERNET);
3834 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003835 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003836 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3837
Paul Jensen3b759822014-05-13 11:44:01 -04003838 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003839 if (isDefaultNetwork(networkAgent)) {
3840 handleApplyDefaultProxy(newLp.getHttpProxy());
3841 } else {
3842 updateProxy(newLp, oldLp, networkAgent);
3843 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003844 // TODO - move this check to cover the whole function
3845 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003846 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003847 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3848 }
Paul Jensen3b759822014-05-13 11:44:01 -04003849 }
3850
Lorenzo Colitti95439462014-10-09 13:44:48 +09003851 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3852 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3853 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003854
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003855 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003856 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3857 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003858 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003859 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003860 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003861 }
Paul Jensen992f2522014-04-28 10:33:11 -04003862
3863 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3864 CompareResult<String> interfaceDiff = new CompareResult<String>();
3865 if (oldLp != null) {
3866 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3867 } else if (newLp != null) {
3868 interfaceDiff.added = newLp.getAllInterfaceNames();
3869 }
3870 for (String iface : interfaceDiff.added) {
3871 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003872 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003873 mNetd.addInterfaceToNetwork(iface, netId);
3874 } catch (Exception e) {
3875 loge("Exception adding interface: " + e);
3876 }
3877 }
3878 for (String iface : interfaceDiff.removed) {
3879 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003880 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003881 mNetd.removeInterfaceFromNetwork(iface, netId);
3882 } catch (Exception e) {
3883 loge("Exception removing interface: " + e);
3884 }
3885 }
3886 }
3887
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003888 /**
3889 * Have netd update routes from oldLp to newLp.
3890 * @return true if routes changed between oldLp and newLp
3891 */
3892 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003893 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3894 if (oldLp != null) {
3895 routeDiff = oldLp.compareAllRoutes(newLp);
3896 } else if (newLp != null) {
3897 routeDiff.added = newLp.getAllRoutes();
3898 }
3899
3900 // add routes before removing old in case it helps with continuous connectivity
3901
3902 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3903 for (RouteInfo route : routeDiff.added) {
3904 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003905 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003906 try {
3907 mNetd.addRoute(netId, route);
3908 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003909 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3910 loge("Exception in addRoute for non-gateway: " + e);
3911 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003912 }
3913 }
3914 for (RouteInfo route : routeDiff.added) {
3915 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003916 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003917 try {
3918 mNetd.addRoute(netId, route);
3919 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003920 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3921 loge("Exception in addRoute for gateway: " + e);
3922 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003923 }
3924 }
3925
3926 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003927 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003928 try {
3929 mNetd.removeRoute(netId, route);
3930 } catch (Exception e) {
3931 loge("Exception in removeRoute: " + e);
3932 }
3933 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003934 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003935 }
Erik Kline41368502015-06-17 13:19:54 +09003936
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003937 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3938 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003939 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09003940 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003941 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003942 dnses = new ArrayList();
3943 dnses.add(mDefaultDns);
3944 if (DBG) {
3945 loge("no dns provided for netId " + netId + ", so using defaults");
3946 }
3947 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003948 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003949 try {
3950 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3951 newLp.getDomains());
3952 } catch (Exception e) {
3953 loge("Exception in setDnsServersForNetwork: " + e);
3954 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003955 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003956 if (defaultNai != null && defaultNai.network.netId == netId) {
3957 setDefaultDnsSystemProperties(dnses);
3958 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003959 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003960 } else if (flush) {
3961 try {
3962 mNetd.flushNetworkDnsCache(netId);
3963 } catch (Exception e) {
3964 loge("Exception in flushNetworkDnsCache: " + e);
3965 }
3966 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003967 }
3968 }
3969
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003970 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3971 int last = 0;
3972 for (InetAddress dns : dnses) {
3973 ++last;
3974 String key = "net.dns" + last;
3975 String value = dns.getHostAddress();
3976 SystemProperties.set(key, value);
3977 }
3978 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3979 String key = "net.dns" + i;
3980 SystemProperties.set(key, "");
3981 }
3982 mNumDnsEntries = last;
3983 }
3984
Paul Jensen3d194ea2015-06-16 14:27:36 -04003985 /**
3986 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
3987 * augmented with any stateful capabilities implied from {@code networkAgent}
3988 * (e.g., validated status and captive portal status).
3989 *
Paul Jensene0988542015-06-25 15:30:08 -04003990 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04003991 * @param networkCapabilities the new network capabilities.
3992 */
Paul Jensene0988542015-06-25 15:30:08 -04003993 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04003994 // Don't modify caller's NetworkCapabilities.
3995 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04003996 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04003997 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
3998 } else {
3999 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4000 }
Paul Jensene0988542015-06-25 15:30:08 -04004001 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004002 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4003 } else {
4004 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4005 }
Paul Jensene0988542015-06-25 15:30:08 -04004006 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4007 final int oldScore = nai.getCurrentScore();
4008 synchronized (nai) {
4009 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004010 }
Paul Jensene0988542015-06-25 15:30:08 -04004011 rematchAllNetworksAndRequests(nai, oldScore);
4012 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004013 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004014 }
4015
Paul Jensenc8b9a742014-09-30 15:37:41 -04004016 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4017 for (int i = 0; i < nai.networkRequests.size(); i++) {
4018 NetworkRequest nr = nai.networkRequests.valueAt(i);
4019 // Don't send listening requests to factories. b/17393458
4020 if (!isRequest(nr)) continue;
4021 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4022 }
4023 }
4024
Robert Greenwalt7b816022014-04-18 15:25:25 -07004025 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4026 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004027 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004028 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4029 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004030 }
4031 }
4032
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004033 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4034 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004035 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004036 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004037 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4038 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004039 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004040 sendIntent(nri.mPendingIntent, intent);
4041 }
4042 // else not handled
4043 }
4044
4045 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4046 mPendingIntentWakeLock.acquire();
4047 try {
4048 if (DBG) log("Sending " + pendingIntent);
4049 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4050 } catch (PendingIntent.CanceledException e) {
4051 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4052 mPendingIntentWakeLock.release();
4053 releasePendingNetworkRequest(pendingIntent);
4054 }
4055 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4056 }
4057
4058 @Override
4059 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4060 String resultData, Bundle resultExtras) {
4061 if (DBG) log("Finished sending " + pendingIntent);
4062 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004063 // Release with a delay so the receiving client has an opportunity to put in its
4064 // own request.
4065 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004066 }
4067
Robert Greenwalt9258c642014-03-26 16:47:06 -07004068 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004069 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004070 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004071 Bundle bundle = new Bundle();
4072 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4073 new NetworkRequest(nri.request));
4074 Message msg = Message.obtain();
4075 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4076 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4077 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4078 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004080 case ConnectivityManager.CALLBACK_LOSING: {
4081 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4082 break;
4083 }
4084 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4085 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4086 new NetworkCapabilities(networkAgent.networkCapabilities));
4087 break;
4088 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004089 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004090 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4091 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004092 break;
4093 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004094 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004095 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004096 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004097 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004098 if (VDBG) {
4099 log("sending notification " + notifyTypeToName(notificationType) +
4100 " for " + nri.request);
4101 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004102 nri.messenger.send(msg);
4103 } catch (RemoteException e) {
4104 // may occur naturally in the race of binder death.
4105 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4106 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004107 }
4108
Paul Jensenc8b9a742014-09-30 15:37:41 -04004109 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4110 for (int i = 0; i < nai.networkRequests.size(); i++) {
4111 NetworkRequest nr = nai.networkRequests.valueAt(i);
4112 // Ignore listening requests.
4113 if (!isRequest(nr)) continue;
4114 loge("Dead network still had at least " + nr);
4115 break;
4116 }
4117 nai.asyncChannel.disconnect();
4118 }
4119
Robert Greenwalt7b816022014-04-18 15:25:25 -07004120 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4121 if (oldNetwork == null) {
4122 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4123 return;
4124 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004125 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4126 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004127 }
4128
Paul Jensen27b02b72014-07-14 12:03:33 -04004129 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004130 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004131 setupDataActivityTracking(newNetwork);
4132 try {
4133 mNetd.setDefaultNetId(newNetwork.network.netId);
4134 } catch (Exception e) {
4135 loge("Exception setting default network :" + e);
4136 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004137 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004138 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004139 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004140 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004141 }
4142
Paul Jensen2161a8e2014-09-11 11:00:39 -04004143 // Handles a network appearing or improving its score.
4144 //
4145 // - Evaluates all current NetworkRequests that can be
4146 // satisfied by newNetwork, and reassigns to newNetwork
4147 // any such requests for which newNetwork is the best.
4148 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004149 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004150 // needed. A network is needed if it is the best network for
4151 // one or more NetworkRequests, or if it is a VPN.
4152 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004153 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004154 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004155 //
4156 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4157 // networks that have no chance (i.e. even if validated)
4158 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004159 //
4160 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4161 // it does not remove NetworkRequests that other Networks could better satisfy.
4162 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4163 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4164 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004165 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004166 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004167 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4168 // performed to tear down unvalidated networks that have no chance (i.e. even if
4169 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004170 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004171 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004172 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004173 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004174 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004175 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004176 if (DBG) log("rematching " + newNetwork.name());
4177 // Find and migrate to this Network any NetworkRequests for
4178 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004179 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004180 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004181 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004182 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004183 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4184 if (newNetwork == currentNetwork) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004185 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004186 log("Network " + newNetwork.name() + " was already satisfying" +
4187 " request " + nri.request.requestId + ". No change.");
4188 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004189 keep = true;
4190 continue;
4191 }
4192
4193 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004195 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004196 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004197 // This is not a request, it's a callback listener.
4198 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004199 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004200 continue;
4201 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004202
Robert Greenwalt7b816022014-04-18 15:25:25 -07004203 // next check if it's better than any current network we're using for
4204 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004205 if (VDBG) {
4206 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004207 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4208 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004209 }
4210 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004211 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004212 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004213 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004214 currentNetwork.networkRequests.remove(nri.request.requestId);
4215 currentNetwork.networkLingered.add(nri.request);
4216 affectedNetworks.add(currentNetwork);
4217 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004218 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004219 }
Paul Jensen573a0352015-01-08 10:49:34 -05004220 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004221 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004222 if (!newNetwork.addRequest(nri.request)) {
4223 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4224 }
4225 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004226 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004227 // Tell NetworkFactories about the new score, so they can stop
4228 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004229 // TODO - this could get expensive if we have alot of requests for this
4230 // network. Think about if there is a way to reduce this. Push
4231 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004232 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004233 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004234 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004235 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004236 }
4237 }
4238 }
4239 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004240 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004241 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004242 if (nai.lingering) {
4243 // Already lingered. Nothing to do. This can only happen if "nai" is in
4244 // "affectedNetworks" twice. The reasoning being that to get added to
4245 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4246 // (i.e. not lingered) so it could have only been lingered by this loop.
4247 // unneeded(nai) will be false and we'll call unlinger() below which would
4248 // be bad, so handle it here.
4249 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004250 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004251 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004252 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004253 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004254 }
4255 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004256 if (keep) {
4257 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004258 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004259 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004260 synchronized (ConnectivityService.this) {
4261 // have a new default network, release the transition wakelock in
4262 // a second if it's held. The second pause is to allow apps
4263 // to reconnect over the new network
4264 if (mNetTransitionWakeLock.isHeld()) {
4265 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4266 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4267 mNetTransitionWakeLockSerialNumber, 0),
4268 1000);
4269 }
4270 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004271 }
4272
4273 // do this after the default net is switched, but
4274 // before LegacyTypeTracker sends legacy broadcasts
Paul Jensen3d911462015-06-12 06:40:24 -04004275 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
Robert Greenwalt152ed372014-12-17 17:19:53 -08004276
4277 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004278 // Maintain the illusion: since the legacy API only
4279 // understands one network at a time, we must pretend
4280 // that the current default network disconnected before
4281 // the new one connected.
4282 if (oldDefaultNetwork != null) {
4283 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004284 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004285 }
Paul Jensene0988542015-06-25 15:30:08 -04004286 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004287 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4288 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004289 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004290
4291 // Notify battery stats service about this network, both the normal
4292 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004293 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004294 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004295 final IBatteryStats bs = BatteryStatsService.getService();
4296 final int type = newNetwork.networkInfo.getType();
4297
4298 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4299 bs.noteNetworkInterfaceType(baseIface, type);
4300 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4301 final String stackedIface = stacked.getInterfaceName();
4302 bs.noteNetworkInterfaceType(stackedIface, type);
4303 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4304 }
4305 } catch (RemoteException ignored) {
4306 }
4307
Robert Greenwalt152ed372014-12-17 17:19:53 -08004308 // This has to happen after the notifyNetworkCallbacks as that tickles each
4309 // ConnectivityManager instance so that legacy requests correctly bind dns
4310 // requests to this network. The legacy users are listening for this bcast
4311 // and will generally do a dns request so they can ensureRouteToHost and if
4312 // they do that before the callbacks happen they'll use the default network.
4313 //
4314 // TODO: Is there still a race here? We send the broadcast
4315 // after sending the callback, but if the app can receive the
4316 // broadcast before the callback, it might still break.
4317 //
4318 // This *does* introduce a race where if the user uses the new api
4319 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4320 // they may get old info. Reverse this after the old startUsing api is removed.
4321 // This is on top of the multiple intent sequencing referenced in the todo above.
4322 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4323 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4324 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4325 // legacy type tracker filters out repeat adds
4326 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4327 }
4328 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004329
4330 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4331 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4332 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4333 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4334 if (newNetwork.isVPN()) {
4335 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4336 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004337 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004338 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4339 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004340 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004341 if (DBG) log("Reaping " + nai.name());
4342 teardownUnneededNetwork(nai);
4343 }
4344 }
4345 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004346 }
4347
Paul Jensen1c7ba022015-06-16 14:27:36 -04004348 /**
4349 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4350 * being disconnected.
4351 * @param changed If only one Network's score or capabilities have been modified since the last
4352 * time this function was called, pass this Network in this argument, otherwise pass
4353 * null.
4354 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4355 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4356 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4357 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4358 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004359 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004360 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004361 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4362 // to avoid the slowness. It is not simply enough to process just "changed", for
4363 // example in the case where "changed"'s score decreases and another network should begin
4364 // satifying a NetworkRequest that "changed" currently satisfies.
4365
4366 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4367 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4368 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004369 if (changed != null && oldScore < changed.getCurrentScore()) {
4370 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004371 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004372 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4373 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4374 // Rematch higher scoring networks first to prevent requests first matching a lower
4375 // scoring network and then a higher scoring network, which could produce multiple
4376 // callbacks and inadvertently unlinger networks.
4377 Arrays.sort(nais);
4378 for (NetworkAgentInfo nai : nais) {
4379 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004380 // Only reap the last time through the loop. Reaping before all rematching
4381 // is complete could incorrectly teardown a network that hasn't yet been
4382 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004383 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004384 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004385 }
4386 }
4387 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004388
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004389 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004390 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004391 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004392 // For now only update icons for default connection.
4393 // TODO: Update WiFi and cellular icons separately. b/17237507
4394 if (!isDefaultNetwork(nai)) return;
4395
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004396 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004397 // Don't repeat publish.
4398 if (newInetCondition == mDefaultInetConditionPublished) return;
4399
4400 mDefaultInetConditionPublished = newInetCondition;
4401 sendInetConditionBroadcast(nai.networkInfo);
4402 }
4403
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004404 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4405 if (mLockdownTracker != null) {
4406 if (nai != null && nai.isVPN()) {
4407 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4408 } else {
4409 mLockdownTracker.onNetworkInfoChanged();
4410 }
4411 }
4412 }
4413
Robert Greenwalt7b816022014-04-18 15:25:25 -07004414 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4415 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004416 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004417 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004418 synchronized (networkAgent) {
4419 oldInfo = networkAgent.networkInfo;
4420 networkAgent.networkInfo = newInfo;
4421 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004422 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004423
4424 if (oldInfo != null && oldInfo.getState() == state) {
4425 if (VDBG) log("ignoring duplicate network state non-change");
4426 return;
4427 }
4428 if (DBG) {
4429 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4430 (oldInfo == null ? "null" : oldInfo.getState()) +
4431 " to " + state);
4432 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004433
Paul Jenseneec75412014-08-04 12:21:19 -04004434 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004435 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004436 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004437 if (networkAgent.isVPN()) {
4438 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004439 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4440 (networkAgent.networkMisc == null ||
4441 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004442 } else {
4443 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4444 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004445 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004446 loge("Error creating network " + networkAgent.network.netId + ": "
4447 + e.getMessage());
4448 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004449 }
Paul Jenseneec75412014-08-04 12:21:19 -04004450 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004451 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004452 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004453
Paul Jensenca8f16a2014-05-09 12:47:55 -04004454 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004455 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004456
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004457 if (networkAgent.isVPN()) {
4458 // Temporarily disable the default proxy (not global).
4459 synchronized (mProxyLock) {
4460 if (!mDefaultProxyDisabled) {
4461 mDefaultProxyDisabled = true;
4462 if (mGlobalProxy == null && mDefaultProxy != null) {
4463 sendProxyBroadcast(null);
4464 }
4465 }
4466 }
4467 // TODO: support proxy per network.
4468 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004469
Paul Jensen2161a8e2014-09-11 11:00:39 -04004470 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004471 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004472
4473 // This has to happen after matching the requests, because callbacks are just requests.
4474 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004475 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004476 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004477 if (networkAgent.isVPN()) {
4478 synchronized (mProxyLock) {
4479 if (mDefaultProxyDisabled) {
4480 mDefaultProxyDisabled = false;
4481 if (mGlobalProxy == null && mDefaultProxy != null) {
4482 sendProxyBroadcast(mDefaultProxy);
4483 }
4484 }
4485 }
4486 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004487 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4488 state == NetworkInfo.State.SUSPENDED) {
4489 // going into or coming out of SUSPEND: rescore and notify
4490 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004491 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004492 }
4493 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4494 ConnectivityManager.CALLBACK_SUSPENDED :
4495 ConnectivityManager.CALLBACK_RESUMED));
4496 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004497 }
4498 }
4499
Robert Greenwaltac96c522014-06-03 16:43:57 -07004500 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4501 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004502 if (score < 0) {
4503 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4504 "). Bumping score to min of 0");
4505 score = 0;
4506 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004507
Paul Jensen2161a8e2014-09-11 11:00:39 -04004508 final int oldScore = nai.getCurrentScore();
4509 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004510
Paul Jensen85cf78e2015-06-25 13:25:07 -04004511 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004512
Paul Jensenc8b9a742014-09-30 15:37:41 -04004513 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004514 }
4515
Robert Greenwalt9258c642014-03-26 16:47:06 -07004516 // notify only this one new request of the current state
4517 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4518 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4519 // TODO - read state from monitor to decide what to send.
4520// if (nai.networkMonitor.isLingering()) {
4521// notifyType = NetworkCallbacks.LOSING;
4522// } else if (nai.networkMonitor.isEvaluating()) {
4523// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4524// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004525 if (nri.mPendingIntent == null) {
4526 callCallbackForRequest(nri, nai, notifyType);
4527 } else {
4528 sendPendingIntentForRequest(nri, nai, notifyType);
4529 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004530 }
4531
Robert Greenwalt8d482522015-06-24 13:23:42 -07004532 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004533 // The NetworkInfo we actually send out has no bearing on the real
4534 // state of affairs. For example, if the default connection is mobile,
4535 // and a request for HIPRI has just gone away, we need to pretend that
4536 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4537 // the state to DISCONNECTED, even though the network is of type MOBILE
4538 // and is still connected.
4539 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4540 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004541 if (state != DetailedState.DISCONNECTED) {
4542 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004543 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004544 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004545 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004546 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4547 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4548 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4549 if (info.isFailover()) {
4550 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4551 nai.networkInfo.setFailover(false);
4552 }
4553 if (info.getReason() != null) {
4554 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4555 }
4556 if (info.getExtraInfo() != null) {
4557 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4558 }
4559 NetworkAgentInfo newDefaultAgent = null;
4560 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004561 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004562 if (newDefaultAgent != null) {
4563 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4564 newDefaultAgent.networkInfo);
4565 } else {
4566 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4567 }
4568 }
4569 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4570 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004571 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004572 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004573 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004574 }
4575 }
4576 }
4577
Robert Greenwalt7b816022014-04-18 15:25:25 -07004578 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004579 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004580 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004581 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4582 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4583 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004584 if (nri.mPendingIntent == null) {
4585 callCallbackForRequest(nri, networkAgent, notifyType);
4586 } else {
4587 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4588 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004589 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004590 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004591
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004592 private String notifyTypeToName(int notifyType) {
4593 switch (notifyType) {
4594 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4595 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4596 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4597 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4598 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4599 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4600 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4601 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4602 }
4603 return "UNKNOWN";
4604 }
4605
Jeff Sharkey69736342014-12-08 14:50:12 -08004606 /**
4607 * Notify other system services that set of active ifaces has changed.
4608 */
4609 private void notifyIfacesChanged() {
4610 try {
4611 mStatsService.forceUpdateIfaces();
4612 } catch (Exception ignored) {
4613 }
4614 }
4615
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004616 @Override
4617 public boolean addVpnAddress(String address, int prefixLength) {
4618 throwIfLockdownEnabled();
4619 int user = UserHandle.getUserId(Binder.getCallingUid());
4620 synchronized (mVpns) {
4621 return mVpns.get(user).addAddress(address, prefixLength);
4622 }
4623 }
4624
4625 @Override
4626 public boolean removeVpnAddress(String address, int prefixLength) {
4627 throwIfLockdownEnabled();
4628 int user = UserHandle.getUserId(Binder.getCallingUid());
4629 synchronized (mVpns) {
4630 return mVpns.get(user).removeAddress(address, prefixLength);
4631 }
4632 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004633
4634 @Override
4635 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4636 throwIfLockdownEnabled();
4637 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004638 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004639 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004640 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004641 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004642 if (success) {
4643 notifyIfacesChanged();
4644 }
4645 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004646 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004647
4648 @Override
4649 public void factoryReset() {
4650 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004651
4652 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4653 return;
4654 }
4655
Robin Lee3b3dd942015-05-12 18:14:58 +01004656 final int userId = UserHandle.getCallingUserId();
4657
Stuart Scottf1fb3972015-04-02 18:00:02 -07004658 // Turn airplane mode off
4659 setAirplaneMode(false);
4660
Stuart Scotte3e314d2015-04-20 14:07:45 -07004661 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4662 // Untether
4663 for (String tether : getTetheredIfaces()) {
4664 untether(tether);
4665 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004666 }
4667
Stuart Scotte3e314d2015-04-20 14:07:45 -07004668 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4669 // Turn VPN off
4670 VpnConfig vpnConfig = getVpnConfig(userId);
4671 if (vpnConfig != null) {
4672 if (vpnConfig.legacy) {
4673 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4674 } else {
4675 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4676 // in the future without user intervention.
4677 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004678
Stuart Scotte3e314d2015-04-20 14:07:45 -07004679 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4680 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004681 }
4682 }
4683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684}