blob: a79e5b16f0e5f097185a3f836c0135851c4cb34f [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
Erik Kline7523eb32015-07-09 18:24:03 +0900410 // NetworkRequest activity String log entries.
411 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
412 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
413
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700414 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
415 private static final int MAX_VALIDATION_LOGS = 10;
416 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
417 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
418
419 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
420 synchronized(mValidationLogs) {
421 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
422 mValidationLogs.removeLast();
423 }
424 mValidationLogs.addFirst(new Pair(network, log));
425 }
426 }
427
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700428 /**
429 * Implements support for the legacy "one network per network type" model.
430 *
431 * We used to have a static array of NetworkStateTrackers, one for each
432 * network type, but that doesn't work any more now that we can have,
433 * for example, more that one wifi network. This class stores all the
434 * NetworkAgentInfo objects that support a given type, but the legacy
435 * API will only see the first one.
436 *
437 * It serves two main purposes:
438 *
439 * 1. Provide information about "the network for a given type" (since this
440 * API only supports one).
441 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
442 * the first network for a given type changes, or if the default network
443 * changes.
444 */
445 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900446
447 private static final boolean DBG = true;
448 private static final boolean VDBG = false;
449 private static final String TAG = "CSLegacyTypeTracker";
450
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700451 /**
452 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
453 * Each list holds references to all NetworkAgentInfos that are used to
454 * satisfy requests for that network type.
455 *
456 * This array is built out at startup such that an unsupported network
457 * doesn't get an ArrayList instance, making this a tristate:
458 * unsupported, supported but not active and active.
459 *
460 * The actual lists are populated when we scan the network types that
461 * are supported on this device.
462 */
463 private ArrayList<NetworkAgentInfo> mTypeLists[];
464
465 public LegacyTypeTracker() {
466 mTypeLists = (ArrayList<NetworkAgentInfo>[])
467 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
468 }
469
470 public void addSupportedType(int type) {
471 if (mTypeLists[type] != null) {
472 throw new IllegalStateException(
473 "legacy list for type " + type + "already initialized");
474 }
475 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
476 }
477
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700478 public boolean isTypeSupported(int type) {
479 return isNetworkTypeValid(type) && mTypeLists[type] != null;
480 }
481
482 public NetworkAgentInfo getNetworkForType(int type) {
483 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
484 return mTypeLists[type].get(0);
485 } else {
486 return null;
487 }
488 }
489
Robert Greenwalt8d482522015-06-24 13:23:42 -0700490 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900491 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900492 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700493 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900494 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900495 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900496 }
497 }
498
499 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700500 public void add(int type, NetworkAgentInfo nai) {
501 if (!isTypeSupported(type)) {
502 return; // Invalid network type.
503 }
504 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
505
506 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
507 if (list.contains(nai)) {
508 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
509 return;
510 }
511
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900512 list.add(nai);
513
514 // 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 +0900515 final boolean isDefaultNetwork = isDefaultNetwork(nai);
516 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700517 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
518 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700519 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700520 }
521
Lorenzo Colittia793a672014-07-31 23:20:17 +0900522 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900523 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900524 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
525 if (list == null || list.isEmpty()) {
526 return;
527 }
528
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900529 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900530
531 if (!list.remove(nai)) {
532 return;
533 }
534
Robert Greenwalt8d482522015-06-24 13:23:42 -0700535 final DetailedState state = DetailedState.DISCONNECTED;
536
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900537 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700538 maybeLogBroadcast(nai, state, type, wasDefault);
539 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900540 }
541
542 if (!list.isEmpty() && wasFirstNetwork) {
543 if (DBG) log("Other network available for type " + type +
544 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900545 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700546 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
547 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900548 }
549 }
550
551 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900552 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
553 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700554 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900555 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700556 }
557 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700558
Robert Greenwalt8d482522015-06-24 13:23:42 -0700559 // send out another legacy broadcast - currently only used for suspend/unsuspend
560 // toggle
561 public void update(NetworkAgentInfo nai) {
562 final boolean isDefault = isDefaultNetwork(nai);
563 final DetailedState state = nai.networkInfo.getDetailedState();
564 for (int type = 0; type < mTypeLists.length; type++) {
565 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700566 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700567 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700568 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700569 maybeLogBroadcast(nai, state, type, isDefault);
570 sendLegacyNetworkBroadcast(nai, state, type);
571 }
572 }
573 }
574
Lorenzo Colittia793a672014-07-31 23:20:17 +0900575 private String naiToString(NetworkAgentInfo nai) {
576 String name = (nai != null) ? nai.name() : "null";
577 String state = (nai.networkInfo != null) ?
578 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
579 "???/???";
580 return name + " " + state;
581 }
582
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700583 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900584 pw.println("mLegacyTypeTracker:");
585 pw.increaseIndent();
586 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700587 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900588 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700589 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900590 pw.println();
591 pw.println("Current state:");
592 pw.increaseIndent();
593 for (int type = 0; type < mTypeLists.length; type++) {
594 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
595 for (NetworkAgentInfo nai : mTypeLists[type]) {
596 pw.println(type + " " + naiToString(nai));
597 }
598 }
599 pw.decreaseIndent();
600 pw.decreaseIndent();
601 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700602 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900603
604 // This class needs its own log method because it has a different TAG.
605 private void log(String s) {
606 Slog.d(TAG, s);
607 }
608
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700609 }
610 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
611
Jeff Sharkey899223b2012-08-04 15:24:58 -0700612 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700613 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800614 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800615
Erik Klineda4bfa82015-04-30 12:58:40 +0900616 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900617 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
618 new Binder(), NetworkRequestInfo.REQUEST);
619 mNetworkRequests.put(mDefaultRequest, defaultNRI);
620 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900621
622 mDefaultMobileDataRequest = createInternetRequestForTransport(
623 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700624
Wink Savillebb08caf2010-09-02 19:23:52 -0700625 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
626 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700627 mHandler = new InternalHandler(handlerThread.getLooper());
628 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700629
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800630 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800631 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
632 String id = Settings.Secure.getString(context.getContentResolver(),
633 Settings.Secure.ANDROID_ID);
634 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700635 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800636 SystemProperties.set("net.hostname", name);
637 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800638 }
639
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700640 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700641 String dns = Settings.Global.getString(context.getContentResolver(),
642 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700643 if (dns == null || dns.length() == 0) {
644 dns = context.getResources().getString(
645 com.android.internal.R.string.config_default_dns_server);
646 }
647 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800648 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
649 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800650 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700651 }
652
Jeremy Joslin79294842014-12-03 17:15:28 -0800653 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
654 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
655
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700656 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700657 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800658 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700659 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700660 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700661 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700662
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700663 try {
664 mPolicyManager.registerListener(mPolicyListener);
665 } catch (RemoteException e) {
666 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700667 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700668 }
669
670 final PowerManager powerManager = (PowerManager) context.getSystemService(
671 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700672 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
673 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
674 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800675 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700676
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700677 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700678
Wink Saville51f456f2013-04-23 14:26:51 -0700679 // TODO: What is the "correct" way to do determine if this is a wifi only device?
680 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
681 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700682 String[] naStrings = context.getResources().getStringArray(
683 com.android.internal.R.array.networkAttributes);
684 for (String naString : naStrings) {
685 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700686 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700687 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700688 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800689 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700690 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700691 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700692 }
Wink Saville51f456f2013-04-23 14:26:51 -0700693 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
694 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
695 n.type);
696 continue;
697 }
Wink Saville975c8482011-04-07 14:23:45 -0700698 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800699 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700700 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700701 continue;
702 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700703 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700704
Wink Saville975c8482011-04-07 14:23:45 -0700705 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700706 mNetworksDefined++;
707 } catch(Exception e) {
708 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700709 }
710 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700711
712 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
713 if (mNetConfigs[TYPE_VPN] == null) {
714 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
715 // don't need to add TYPE_VPN to mNetConfigs.
716 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
717 mNetworksDefined++; // used only in the log() statement below.
718 }
719
Wink Saville5e56bc52013-07-29 15:00:57 -0700720 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700721
Robert Greenwalt50393202011-06-21 17:26:14 -0700722 mProtectedNetworks = new ArrayList<Integer>();
723 int[] protectedNetworks = context.getResources().getIntArray(
724 com.android.internal.R.array.config_protectedNetworks);
725 for (int p : protectedNetworks) {
726 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
727 mProtectedNetworks.add(p);
728 } else {
729 if (DBG) loge("Ignoring protectedNetwork " + p);
730 }
731 }
732
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700733 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
734 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700735
Robert Greenwaltfab501672014-07-23 11:44:01 -0700736 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800737
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700738 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
739
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700740 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700741 IntentFilter intentFilter = new IntentFilter();
742 intentFilter.addAction(Intent.ACTION_USER_STARTING);
743 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
744 mContext.registerReceiverAsUser(
745 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900746
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700747 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700748 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700749 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700750 } catch (RemoteException e) {
751 loge("Error registering observer :" + e);
752 }
753
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700754 if (DBG) {
755 mInetLog = new ArrayList();
756 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700757
Erik Klineda4bfa82015-04-30 12:58:40 +0900758 mSettingsObserver = new SettingsObserver(mContext, mHandler);
759 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800760
John Spurlockbf991a82013-06-24 14:20:23 -0400761 mDataConnectionStats = new DataConnectionStats(mContext);
762 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400763
Jason Monkdecd2952013-10-10 14:02:51 -0400764 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700765
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400766 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700768
Erik Klineda4bfa82015-04-30 12:58:40 +0900769 private NetworkRequest createInternetRequestForTransport(int transportType) {
770 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900771 netCap.addCapability(NET_CAPABILITY_INTERNET);
772 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900773 if (transportType > -1) {
774 netCap.addTransportType(transportType);
775 }
776 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
777 }
778
779 private void handleMobileDataAlwaysOn() {
780 final boolean enable = (Settings.Global.getInt(
781 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
782 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
783 if (enable == isEnabled) {
784 return; // Nothing to do.
785 }
786
787 if (enable) {
788 handleRegisterNetworkRequest(new NetworkRequestInfo(
789 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
790 } else {
791 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
792 }
793 }
794
795 private void registerSettingsCallbacks() {
796 // Watch for global HTTP proxy changes.
797 mSettingsObserver.observe(
798 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
799 EVENT_APPLY_GLOBAL_HTTP_PROXY);
800
801 // Watch for whether or not to keep mobile data always on.
802 mSettingsObserver.observe(
803 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
804 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
805 }
806
Robert Greenwalt34524f02014-05-18 16:22:10 -0700807 private synchronized int nextNetworkRequestId() {
808 return mNextNetworkRequestId++;
809 }
810
Paul Jensen67b0b072015-06-10 11:22:17 -0400811 @VisibleForTesting
812 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400813 synchronized (mNetworkForNetId) {
814 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
815 int netId = mNextNetId;
816 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
817 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500818 if (!mNetIdInUse.get(netId)) {
819 mNetIdInUse.put(netId, true);
820 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400821 }
822 }
823 }
824 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700825 }
826
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800827 private NetworkState getFilteredNetworkState(int networkType, int uid) {
828 NetworkInfo info = null;
829 LinkProperties lp = null;
830 NetworkCapabilities nc = null;
831 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800832 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800833
834 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
835 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
836 if (nai != null) {
837 synchronized (nai) {
838 info = new NetworkInfo(nai.networkInfo);
839 lp = new LinkProperties(nai.linkProperties);
840 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400841 // Network objects are outwardly immutable so there is no point to duplicating.
842 // Duplicating also precludes sharing socket factories and connection pools.
843 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800844 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800845 }
846 info.setType(networkType);
847 } else {
848 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
849 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
850 info.setIsAvailable(true);
851 lp = new LinkProperties();
852 nc = new NetworkCapabilities();
853 network = null;
854 }
855 info = getFilteredNetworkInfo(info, lp, uid);
856 }
857
Jeff Sharkey32566012014-12-02 18:30:14 -0800858 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400859 }
860
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800861 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
862 if (network == null) {
863 return null;
864 }
865 synchronized (mNetworkForNetId) {
866 return mNetworkForNetId.get(network.netId);
867 }
868 };
869
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900870 private Network[] getVpnUnderlyingNetworks(int uid) {
871 if (!mLockdownEnabled) {
872 int user = UserHandle.getUserId(uid);
873 synchronized (mVpns) {
874 Vpn vpn = mVpns.get(user);
875 if (vpn != null && vpn.appliesToUid(uid)) {
876 return vpn.getUnderlyingNetworks();
877 }
878 }
879 }
880 return null;
881 }
882
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800883 private NetworkState getUnfilteredActiveNetworkState(int uid) {
884 NetworkInfo info = null;
885 LinkProperties lp = null;
886 NetworkCapabilities nc = null;
887 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800888 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800889
Paul Jensen85cf78e2015-06-25 13:25:07 -0400890 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800891
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900892 final Network[] networks = getVpnUnderlyingNetworks(uid);
893 if (networks != null) {
894 // getUnderlyingNetworks() returns:
895 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
896 // empty array => the VPN explicitly said "no default network".
897 // non-empty array => the VPN specified one or more default networks; we use the
898 // first one.
899 if (networks.length > 0) {
900 nai = getNetworkAgentInfoForNetwork(networks[0]);
901 } else {
902 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800903 }
904 }
905
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800906 if (nai != null) {
907 synchronized (nai) {
908 info = new NetworkInfo(nai.networkInfo);
909 lp = new LinkProperties(nai.linkProperties);
910 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400911 // Network objects are outwardly immutable so there is no point to duplicating.
912 // Duplicating also precludes sharing socket factories and connection pools.
913 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800914 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800915 }
916 }
917
Jeff Sharkey32566012014-12-02 18:30:14 -0800918 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400919 }
920
921 /**
922 * Check if UID should be blocked from using the network with the given LinkProperties.
923 */
924 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700925 final boolean networkCostly;
926 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700927
Robert Greenwalt12e67352014-05-13 21:41:06 -0700928 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700929 synchronized (mRulesLock) {
930 networkCostly = mMeteredIfaces.contains(iface);
931 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700932 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700933
Amith Yamasani15e472352015-04-24 19:06:07 -0700934 if ((uidRules & RULE_REJECT_ALL) != 0
935 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700936 return true;
937 }
938
939 // no restrictive rules; network is visible
940 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700941 }
942
943 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700944 * Return a filtered {@link NetworkInfo}, potentially marked
945 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800946 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700947 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800948 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
949 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400950 // network is blocked; clone and override state
951 info = new NetworkInfo(info);
952 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900953 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900954 log("returning Blocked NetworkInfo for ifname=" +
955 lp.getInterfaceName() + ", uid=" + uid);
956 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700957 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800958 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700959 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900960 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700961 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700962 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700963 }
964
965 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 * Return NetworkInfo for the active (i.e., connected) network interface.
967 * It is assumed that at most one network is active at a time. If more
968 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700969 * @return the info for the active network, or {@code null} if none is
970 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700972 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700974 enforceAccessPermission();
975 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800976 NetworkState state = getUnfilteredActiveNetworkState(uid);
977 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 }
979
Paul Jensen31a94f42015-02-13 14:18:39 -0500980 @Override
981 public Network getActiveNetwork() {
982 enforceAccessPermission();
983 final int uid = Binder.getCallingUid();
984 final int user = UserHandle.getUserId(uid);
985 int vpnNetId = NETID_UNSET;
986 synchronized (mVpns) {
987 final Vpn vpn = mVpns.get(user);
988 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
989 }
990 NetworkAgentInfo nai;
991 if (vpnNetId != NETID_UNSET) {
992 synchronized (mNetworkForNetId) {
993 nai = mNetworkForNetId.get(vpnNetId);
994 }
995 if (nai != null) return nai.network;
996 }
997 nai = getDefaultNetwork();
998 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
999 return nai != null ? nai.network : null;
1000 }
1001
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001002 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1003 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001004 final int uid = Binder.getCallingUid();
1005 NetworkState state = getUnfilteredActiveNetworkState(uid);
1006 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001007 }
1008
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001009 @Override
1010 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1011 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001012 NetworkState state = getUnfilteredActiveNetworkState(uid);
1013 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001014 }
1015
1016 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 public NetworkInfo getNetworkInfo(int networkType) {
1018 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001020 if (getVpnUnderlyingNetworks(uid) != null) {
1021 // A VPN is active, so we may need to return one of its underlying networks. This
1022 // information is not available in LegacyTypeTracker, so we have to get it from
1023 // getUnfilteredActiveNetworkState.
1024 NetworkState state = getUnfilteredActiveNetworkState(uid);
1025 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1026 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1027 }
1028 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001029 NetworkState state = getFilteredNetworkState(networkType, uid);
1030 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
1032
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001033 @Override
1034 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1035 enforceAccessPermission();
1036 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001037 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001038 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1039 if (nai != null) {
1040 synchronized (nai) {
1041 info = new NetworkInfo(nai.networkInfo);
1042 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001043 }
1044 }
1045 return info;
1046 }
1047
1048 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 public NetworkInfo[] getAllNetworkInfo() {
1050 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001051 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001052 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1053 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001054 NetworkInfo info = getNetworkInfo(networkType);
1055 if (info != null) {
1056 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001059 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 }
1061
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001062 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001063 public Network getNetworkForType(int networkType) {
1064 enforceAccessPermission();
1065 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001066 NetworkState state = getFilteredNetworkState(networkType, uid);
1067 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1068 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001069 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001070 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001071 }
1072
1073 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001074 public Network[] getAllNetworks() {
1075 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001076 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001077 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001078 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001079 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001080 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001081 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001082 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001083 }
1084
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001085 @Override
1086 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1087 // The basic principle is: if an app's traffic could possibly go over a
1088 // network, without the app doing anything multinetwork-specific,
1089 // (hence, by "default"), then include that network's capabilities in
1090 // the array.
1091 //
1092 // In the normal case, app traffic only goes over the system's default
1093 // network connection, so that's the only network returned.
1094 //
1095 // With a VPN in force, some app traffic may go into the VPN, and thus
1096 // over whatever underlying networks the VPN specifies, while other app
1097 // traffic may go over the system default network (e.g.: a split-tunnel
1098 // VPN, or an app disallowed by the VPN), so the set of networks
1099 // returned includes the VPN's underlying networks and the system
1100 // default.
1101 enforceAccessPermission();
1102
1103 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1104
1105 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001106 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001107 if (nc != null) {
1108 result.put(nai.network, nc);
1109 }
1110
1111 if (!mLockdownEnabled) {
1112 synchronized (mVpns) {
1113 Vpn vpn = mVpns.get(userId);
1114 if (vpn != null) {
1115 Network[] networks = vpn.getUnderlyingNetworks();
1116 if (networks != null) {
1117 for (Network network : networks) {
1118 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001119 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001120 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001121 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001122 }
1123 }
1124 }
1125 }
1126 }
1127 }
1128
1129 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1130 out = result.values().toArray(out);
1131 return out;
1132 }
1133
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001134 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001135 public boolean isNetworkSupported(int networkType) {
1136 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001137 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001138 }
1139
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001140 /**
1141 * Return LinkProperties for the active (i.e., connected) default
1142 * network interface. It is assumed that at most one default network
1143 * is active at a time. If more than one is active, it is indeterminate
1144 * which will be returned.
1145 * @return the ip properties for the active network, or {@code null} if
1146 * none is active
1147 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001148 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001149 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001150 enforceAccessPermission();
1151 final int uid = Binder.getCallingUid();
1152 NetworkState state = getUnfilteredActiveNetworkState(uid);
1153 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001154 }
1155
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001156 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001157 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001158 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001159 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1160 if (nai != null) {
1161 synchronized (nai) {
1162 return new LinkProperties(nai.linkProperties);
1163 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001164 }
1165 return null;
1166 }
1167
Robert Greenwalt12e67352014-05-13 21:41:06 -07001168 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001169 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001170 public LinkProperties getLinkProperties(Network network) {
1171 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001173 if (nai != null) {
1174 synchronized (nai) {
1175 return new LinkProperties(nai.linkProperties);
1176 }
1177 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001178 return null;
1179 }
1180
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001181 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001182 if (nai != null) {
1183 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001184 if (nai.networkCapabilities != null) {
1185 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001186 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001187 }
1188 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001189 return null;
1190 }
1191
1192 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001193 public NetworkCapabilities getNetworkCapabilities(Network network) {
1194 enforceAccessPermission();
1195 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1196 }
1197
1198 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001199 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001200 // Require internal since we're handing out IMSI details
1201 enforceConnectivityInternalPermission();
1202
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001203 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001204 for (Network network : getAllNetworks()) {
1205 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1206 if (nai != null) {
1207 synchronized (nai) {
1208 final String subscriberId = (nai.networkMisc != null)
1209 ? nai.networkMisc.subscriberId : null;
1210 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1211 nai.networkCapabilities, network, subscriberId, null));
1212 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001213 }
1214 }
1215 return result.toArray(new NetworkState[result.size()]);
1216 }
1217
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001218 @Override
1219 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1220 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001221 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001222 final long token = Binder.clearCallingIdentity();
1223 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001224 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1225 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001226 try {
1227 return mPolicyManager.getNetworkQuotaInfo(state);
1228 } catch (RemoteException e) {
1229 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001230 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001231 return null;
1232 } finally {
1233 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001234 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001235 }
1236
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001237 @Override
1238 public boolean isActiveNetworkMetered() {
1239 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001240 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001241 final long token = Binder.clearCallingIdentity();
1242 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001244 } finally {
1245 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001246 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001247 }
1248
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001249 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1250 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1251 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001252 try {
1253 return mPolicyManager.isNetworkMetered(state);
1254 } catch (RemoteException e) {
1255 }
1256 }
1257 return false;
1258 }
1259
Jeff Sharkey216c1812012-08-05 14:29:23 -07001260 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1261 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001262 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001263 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001264 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001265 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001266 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001267
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001268 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 * Ensure that a network route exists to deliver traffic to the specified
1270 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001271 * @param networkType the type of the network over which traffic to the
1272 * specified host is to be routed
1273 * @param hostAddress the IP address of the host to which the route is
1274 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 * @return {@code true} on success, {@code false} on failure
1276 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001277 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001279 if (mProtectedNetworks.contains(networkType)) {
1280 enforceConnectivityInternalPermission();
1281 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001282
Chad Brubakerc0234532014-02-14 13:24:29 -08001283 InetAddress addr;
1284 try {
1285 addr = InetAddress.getByAddress(hostAddress);
1286 } catch (UnknownHostException e) {
1287 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1288 return false;
1289 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001292 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 return false;
1294 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001295
1296 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1297 if (nai == null) {
1298 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1299 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1300 } else {
1301 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1302 }
1303 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001304 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001305
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001306 DetailedState netState;
1307 synchronized (nai) {
1308 netState = nai.networkInfo.getDetailedState();
1309 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001310
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001311 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001312 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001313 log("requestRouteToHostAddress on down network "
1314 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001315 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001316 }
1317 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001319
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001320 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001321 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001322 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001323 LinkProperties lp;
1324 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001325 synchronized (nai) {
1326 lp = nai.linkProperties;
1327 netId = nai.network.netId;
1328 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001329 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001330 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1331 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001332 } finally {
1333 Binder.restoreCallingIdentity(token);
1334 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001335 }
1336
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001337 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001338 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001339 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001340 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001341 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001342 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001343 if (bestRoute.getGateway().equals(addr)) {
1344 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001345 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001346 } else {
1347 // if we will connect to this through another route, add a direct route
1348 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001349 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001350 }
1351 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001352 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001353 try {
1354 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1355 } catch (Exception e) {
1356 // never crash - catch them all
1357 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001358 return false;
1359 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001360 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 }
1362
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001363 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1364 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001365 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001366 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001367 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001368 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001369 }
1370
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001371 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001372 // skip update when we've already applied rules
1373 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1374 if (oldRules == uidRules) return;
1375
1376 mUidRules.put(uid, uidRules);
1377 }
1378
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001379 // TODO: notify UID when it has requested targeted updates
1380 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001381
1382 @Override
1383 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001384 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001385 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001386 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001387 }
1388
1389 synchronized (mRulesLock) {
1390 mMeteredIfaces.clear();
1391 for (String iface : meteredIfaces) {
1392 mMeteredIfaces.add(iface);
1393 }
1394 }
1395 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001396
1397 @Override
1398 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1399 // caller is NPMS, since we only register with them
1400 if (LOGD_RULES) {
1401 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1402 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001403 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001404 };
1405
Robin Lee3b3dd942015-05-12 18:14:58 +01001406 /**
1407 * Require that the caller is either in the same user or has appropriate permission to interact
1408 * across users.
1409 *
1410 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1411 */
1412 private void enforceCrossUserPermission(int userId) {
1413 if (userId == UserHandle.getCallingUserId()) {
1414 // Not a cross-user call.
1415 return;
1416 }
1417 mContext.enforceCallingOrSelfPermission(
1418 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1419 "ConnectivityService");
1420 }
1421
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001422 private void enforceInternetPermission() {
1423 mContext.enforceCallingOrSelfPermission(
1424 android.Manifest.permission.INTERNET,
1425 "ConnectivityService");
1426 }
1427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001429 mContext.enforceCallingOrSelfPermission(
1430 android.Manifest.permission.ACCESS_NETWORK_STATE,
1431 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
1433
1434 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001435 mContext.enforceCallingOrSelfPermission(
1436 android.Manifest.permission.CHANGE_NETWORK_STATE,
1437 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001440 private void enforceTetherAccessPermission() {
1441 mContext.enforceCallingOrSelfPermission(
1442 android.Manifest.permission.ACCESS_NETWORK_STATE,
1443 "ConnectivityService");
1444 }
1445
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001446 private void enforceConnectivityInternalPermission() {
1447 mContext.enforceCallingOrSelfPermission(
1448 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1449 "ConnectivityService");
1450 }
1451
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001452 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001453 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001454 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001455 }
1456
1457 private void sendInetConditionBroadcast(NetworkInfo info) {
1458 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1459 }
1460
Wink Saville628b0852011-08-04 15:01:58 -07001461 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001462 if (mLockdownTracker != null) {
1463 info = mLockdownTracker.augmentNetworkInfo(info);
1464 }
1465
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001466 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001467 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001468 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 if (info.isFailover()) {
1470 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1471 info.setFailover(false);
1472 }
1473 if (info.getReason() != null) {
1474 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1475 }
1476 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001477 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1478 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001480 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001481 return intent;
1482 }
1483
1484 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1485 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1486 }
1487
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001488 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001489 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1490 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1491 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001492 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001493 final long ident = Binder.clearCallingIdentity();
1494 try {
1495 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1496 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1497 } finally {
1498 Binder.restoreCallingIdentity(ident);
1499 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001500 }
1501
Mike Lockwood0f79b542009-08-14 14:18:49 -04001502 private void sendStickyBroadcast(Intent intent) {
1503 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001504 if (!mSystemReady) {
1505 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001506 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001507 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001508 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001509 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001510 }
1511
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001512 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001513 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1514 final IBatteryStats bs = BatteryStatsService.getService();
1515 try {
1516 NetworkInfo ni = intent.getParcelableExtra(
1517 ConnectivityManager.EXTRA_NETWORK_INFO);
1518 bs.noteConnectivityChanged(intent.getIntExtra(
1519 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1520 ni != null ? ni.getState().toString() : "?");
1521 } catch (RemoteException e) {
1522 }
1523 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001524 try {
1525 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1526 } finally {
1527 Binder.restoreCallingIdentity(ident);
1528 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001529 }
1530 }
1531
1532 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001533 loadGlobalProxy();
1534
Mike Lockwood0f79b542009-08-14 14:18:49 -04001535 synchronized(this) {
1536 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001537 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001538 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001539 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001540 }
1541 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001542 // load the global proxy at startup
1543 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001544
1545 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1546 // for user to unlock device.
1547 if (!updateLockdownVpn()) {
1548 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1549 mContext.registerReceiver(mUserPresentReceiver, filter);
1550 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001551
Erik Klineda4bfa82015-04-30 12:58:40 +09001552 // Configure whether mobile data is always on.
1553 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1554
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001555 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001556
1557 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001560 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1561 @Override
1562 public void onReceive(Context context, Intent intent) {
1563 // Try creating lockdown tracker, since user present usually means
1564 // unlocked keystore.
1565 if (updateLockdownVpn()) {
1566 mContext.unregisterReceiver(this);
1567 }
1568 }
1569 };
1570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001572 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001573 *
1574 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001575 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001576 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001577 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1578 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001579
1580 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001581 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001582
Robert Greenwalt7b816022014-04-18 15:25:25 -07001583 if (networkAgent.networkCapabilities.hasTransport(
1584 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001585 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1586 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001587 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001588 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001589 } else if (networkAgent.networkCapabilities.hasTransport(
1590 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001591 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1592 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001593 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001594 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001595 } else {
1596 // do not track any other networks
1597 timeout = 0;
1598 }
1599
Robert Greenwalt7b816022014-04-18 15:25:25 -07001600 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001601 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001602 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001603 } catch (Exception e) {
1604 // You shall not crash!
1605 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001606 }
1607 }
1608 }
1609
1610 /**
1611 * Remove data activity tracking when network disconnects.
1612 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001613 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1614 final String iface = networkAgent.linkProperties.getInterfaceName();
1615 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001616
Robert Greenwalt7b816022014-04-18 15:25:25 -07001617 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1618 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001619 try {
1620 // the call fails silently if no idletimer setup for this interface
1621 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001622 } catch (Exception e) {
1623 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001624 }
1625 }
1626 }
1627
1628 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001629 * Reads the network specific MTU size from reources.
1630 * and set it on it's iface.
1631 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001632 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1633 final String iface = newLp.getInterfaceName();
1634 final int mtu = newLp.getMtu();
1635 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1636 if (VDBG) log("identical MTU - not setting");
1637 return;
1638 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001639
Robert Greenwalt43074032014-08-15 17:53:05 -07001640 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001641 loge("Unexpected mtu value: " + mtu + ", " + iface);
1642 return;
1643 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001644
w1997615afd812014-08-05 15:18:11 -07001645 // Cannot set MTU without interface name
1646 if (TextUtils.isEmpty(iface)) {
1647 loge("Setting MTU size with null iface.");
1648 return;
1649 }
1650
Robert Greenwalt7b816022014-04-18 15:25:25 -07001651 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001652 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001653 mNetd.setMtu(iface, mtu);
1654 } catch (Exception e) {
1655 Slog.e(TAG, "exception in setMtu()" + e);
1656 }
1657 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001658
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001659 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001660 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1661
1662 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001663 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001664 protected int getDefaultTcpRwnd() {
1665 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1666 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001667
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001668 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1669 if (isDefaultNetwork(nai) == false) {
1670 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001671 }
1672
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001673 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1674 String[] values = null;
1675 if (tcpBufferSizes != null) {
1676 values = tcpBufferSizes.split(",");
1677 }
1678
1679 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001680 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001681 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1682 values = tcpBufferSizes.split(",");
1683 }
1684
1685 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1686
1687 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001688 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001689
1690 final String prefix = "/sys/kernel/ipv4/tcp_";
1691 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1692 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1693 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1694 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1695 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1696 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1697 mCurrentTcpBufferSizes = tcpBufferSizes;
1698 } catch (IOException e) {
1699 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001700 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001701
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001702 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001703 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001704 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1705 if (rwndValue != 0) {
1706 SystemProperties.set(sysctlKey, rwndValue.toString());
1707 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001708 }
1709
Mattias Falk8b47b362011-08-23 14:15:13 +02001710 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001711 /*
1712 * Tell the VMs to toss their DNS caches
1713 */
1714 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1715 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001716 /*
1717 * Connectivity events can happen before boot has completed ...
1718 */
1719 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001720 final long ident = Binder.clearCallingIdentity();
1721 try {
1722 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1723 } finally {
1724 Binder.restoreCallingIdentity(ident);
1725 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001726 }
1727
Robert Greenwalt562cc542014-05-15 18:07:26 -07001728 @Override
1729 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001730 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1731 NETWORK_RESTORE_DELAY_PROP_NAME);
1732 if(restoreDefaultNetworkDelayStr != null &&
1733 restoreDefaultNetworkDelayStr.length() != 0) {
1734 try {
1735 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1736 } catch (NumberFormatException e) {
1737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001739 // if the system property isn't set, use the value for the apn type
1740 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1741
1742 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1743 (mNetConfigs[networkType] != null)) {
1744 ret = mNetConfigs[networkType].restoreTime;
1745 }
1746 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
1748
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001749 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001750 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001751 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001752 }
1753 return false;
1754 }
1755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001757 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1758 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001759 if (mContext.checkCallingOrSelfPermission(
1760 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001762 pw.println("Permission Denial: can't dump ConnectivityService " +
1763 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1764 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 return;
1766 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001767
Erik Kline379747a2015-06-05 17:47:34 +09001768 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001769 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001770 final long DIAG_TIME_MS = 5000;
1771 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1772 // Start gathering diagnostic information.
1773 netDiags.add(new NetworkDiagnostics(
1774 nai.network,
Lorenzo Colitti87cfc702015-07-27 16:35:33 +09001775 new LinkProperties(nai.linkProperties), // Must be a copy.
Erik Kline379747a2015-06-05 17:47:34 +09001776 DIAG_TIME_MS));
1777 }
1778
1779 for (NetworkDiagnostics netDiag : netDiags) {
1780 pw.println();
1781 netDiag.waitForMeasurements();
1782 netDiag.dump(pw);
1783 }
1784
1785 return;
1786 }
1787
Lorenzo Colittie3805462015-06-03 11:18:24 +09001788 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001789 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001790 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001791 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001792 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001793 pw.println();
1794
Paul Jensen85cf78e2015-06-25 13:25:07 -04001795 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001796 pw.print("Active default network: ");
1797 if (defaultNai == null) {
1798 pw.println("none");
1799 } else {
1800 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001802 pw.println();
1803
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001804 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001805 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001806 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1807 pw.println(nai.toString());
1808 pw.increaseIndent();
1809 pw.println("Requests:");
1810 pw.increaseIndent();
1811 for (int i = 0; i < nai.networkRequests.size(); i++) {
1812 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001813 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001814 pw.decreaseIndent();
1815 pw.println("Lingered:");
1816 pw.increaseIndent();
1817 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1818 pw.decreaseIndent();
1819 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001820 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001821 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001822 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001823
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001824 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001825 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001826 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1827 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001828 }
1829 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001830 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001831
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001832 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001833
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001834 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001835 pw.print("mNetTransitionWakeLock: currently " +
1836 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1837 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1838 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1839 } else {
1840 pw.println(", last requested never");
1841 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001842 }
1843 pw.println();
1844
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001845 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001846
Lorenzo Colittie3805462015-06-03 11:18:24 +09001847 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001848 pw.println();
1849 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001850 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001851 for(int i = 0; i < mInetLog.size(); i++) {
1852 pw.println(mInetLog.get(i));
1853 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001854 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001855 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001856
1857 if (argsContain(args, "--short") == false) {
1858 pw.println();
1859 synchronized (mValidationLogs) {
1860 pw.println("mValidationLogs (most recent first):");
1861 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1862 pw.println(p.first);
1863 pw.increaseIndent();
1864 p.second.dump(fd, pw, args);
1865 pw.decreaseIndent();
1866 }
1867 }
Erik Kline7523eb32015-07-09 18:24:03 +09001868
1869 pw.println();
1870 pw.println("mNetworkRequestInfoLogs (most recent first):");
1871 pw.increaseIndent();
1872 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1873 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 }
1876
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001877 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001878 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001879 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001880 if (officialNai != null && officialNai.equals(nai)) return true;
1881 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001882 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001883 " - " + nai);
1884 }
1885 return false;
1886 }
1887
Paul Jensenc8b9a742014-09-30 15:37:41 -04001888 private boolean isRequest(NetworkRequest request) {
1889 return mNetworkRequests.get(request).isRequest;
1890 }
1891
Robert Greenwalt42acef32009-08-12 16:08:25 -07001892 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001893 private class NetworkStateTrackerHandler extends Handler {
1894 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001895 super(looper);
1896 }
1897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 @Override
1899 public void handleMessage(Message msg) {
1900 NetworkInfo info;
1901 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001902 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001903 handleAsyncChannelHalfConnect(msg);
1904 break;
1905 }
1906 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1907 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1908 if (nai != null) nai.asyncChannel.disconnect();
1909 break;
1910 }
1911 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1912 handleAsyncChannelDisconnected(msg);
1913 break;
1914 }
1915 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1916 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1917 if (nai == null) {
1918 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1919 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001920 final NetworkCapabilities networkCapabilities =
1921 (NetworkCapabilities)msg.obj;
1922 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1923 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1924 Slog.wtf(TAG, "BUG: " + nai + " has stateful capability.");
1925 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001926 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001927 }
1928 break;
1929 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001930 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1931 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1932 if (nai == null) {
1933 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1934 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001935 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001936 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001937 "; created=" + nai.created);
1938 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001939 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001940 synchronized (nai) {
1941 nai.linkProperties = (LinkProperties)msg.obj;
1942 }
Paul Jenseneec75412014-08-04 12:21:19 -04001943 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001944 }
1945 break;
1946 }
1947 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1948 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1949 if (nai == null) {
1950 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1951 break;
1952 }
1953 info = (NetworkInfo) msg.obj;
1954 updateNetworkInfo(nai, info);
1955 break;
1956 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001957 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1958 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1959 if (nai == null) {
1960 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1961 break;
1962 }
1963 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001964 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001965 break;
1966 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001967 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1968 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1969 if (nai == null) {
1970 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1971 break;
1972 }
1973 try {
1974 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001975 } catch (Exception e) {
1976 // Never crash!
1977 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001978 }
1979 break;
1980 }
1981 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1982 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1983 if (nai == null) {
1984 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1985 break;
1986 }
1987 try {
1988 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001989 } catch (Exception e) {
1990 // Never crash!
1991 loge("Exception in removeVpnUidRanges: " + e);
1992 }
1993 break;
1994 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001995 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1996 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1997 if (nai == null) {
1998 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1999 break;
2000 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002001 if (nai.created && !nai.networkMisc.explicitlySelected) {
2002 loge("ERROR: created network explicitly selected.");
2003 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002004 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002005 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002006 break;
2007 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002008 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002009 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002010 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2011 final boolean valid =
2012 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002013 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2014 if (valid != nai.lastValidated) {
2015 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002016 nai.lastValidated = valid;
2017 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002018 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002019 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2020 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002021 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002022 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002023 // Let the NetworkAgent know the state of its network
2024 nai.asyncChannel.sendMessage(
2025 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2026 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2027 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002028 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002029 break;
2030 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002031 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002032 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002033 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2034 handleLingerComplete(nai);
2035 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002036 break;
2037 }
Paul Jensen869868be2014-05-15 10:33:05 -04002038 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002039 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002040 final boolean visible = (msg.arg1 != 0);
2041 final NetworkAgentInfo nai;
2042 synchronized (mNetworkForNetId) {
2043 nai = mNetworkForNetId.get(netId);
2044 }
2045 // If captive portal status has changed, update capabilities.
2046 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2047 nai.lastCaptivePortalDetected = visible;
2048 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002049 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002050 }
2051 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002052 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002053 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002054 if (nai == null) {
2055 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2056 break;
2057 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002058 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002059 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2060 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002061 }
Paul Jensen869868be2014-05-15 10:33:05 -04002062 break;
2063 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002064 }
2065 }
2066 }
2067
Paul Jensen85cf78e2015-06-25 13:25:07 -04002068 private void linger(NetworkAgentInfo nai) {
2069 nai.lingering = true;
2070 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2071 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2072 }
2073
Paul Jensen0cc17322014-11-25 15:26:53 -05002074 // Cancel any lingering so the linger timeout doesn't teardown a network.
2075 // This should be called when a network begins satisfying a NetworkRequest.
2076 // Note: depending on what state the NetworkMonitor is in (e.g.,
2077 // if it's awaiting captive portal login, or if validation failed), this
2078 // may trigger a re-evaluation of the network.
2079 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002080 nai.networkLingered.clear();
2081 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002082 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002083 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002084 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2085 }
2086
Robert Greenwalt7b816022014-04-18 15:25:25 -07002087 private void handleAsyncChannelHalfConnect(Message msg) {
2088 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002089 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002090 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2091 if (VDBG) log("NetworkFactory connected");
2092 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002093 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002094 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002095 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002096 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002097 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002098 }
2099 } else {
2100 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002101 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002102 }
2103 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2104 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2105 if (VDBG) log("NetworkAgent connected");
2106 // A network agent has requested a connection. Establish the connection.
2107 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2108 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2109 } else {
2110 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002111 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002112 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002113 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002114 synchronized (mNetworkForNetId) {
2115 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002116 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002117 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002118 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002119 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002120 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002121 }
2122 }
2123 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002124
Robert Greenwalt7b816022014-04-18 15:25:25 -07002125 private void handleAsyncChannelDisconnected(Message msg) {
2126 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2127 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002128 if (DBG) {
2129 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2130 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002131 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002132 // TODO - if we move the logic to the network agent (have them disconnect
2133 // because they lost all their requests or because their score isn't good)
2134 // then they would disconnect organically, report their new state and then
2135 // disconnect the channel.
2136 if (nai.networkInfo.isConnected()) {
2137 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2138 null, null);
2139 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002140 final boolean wasDefault = isDefaultNetwork(nai);
2141 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002142 mDefaultInetConditionPublished = 0;
2143 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002144 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002145 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002146 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002147 mNetworkAgentInfos.remove(msg.replyTo);
2148 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002149 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002150 // Remove the NetworkAgent, but don't mark the netId as
2151 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002152 mNetworkForNetId.remove(nai.network.netId);
2153 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002154 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002155 for (int i = 0; i < nai.networkRequests.size(); i++) {
2156 NetworkRequest request = nai.networkRequests.valueAt(i);
2157 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2158 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2159 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002160 sendUpdatedScoreToFactories(request, 0);
2161 }
2162 }
2163 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2164 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002165 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002166 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002167 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002168 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002169 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002170 if (nai.created) {
2171 // Tell netd to clean up the configuration for this network
2172 // (routing rules, DNS, etc).
2173 // This may be slow as it requires a lot of netd shelling out to ip and
2174 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2175 // after we've rematched networks with requests which should make a potential
2176 // fallback network the default or requested a new network from the
2177 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2178 // long time.
2179 try {
2180 mNetd.removeNetwork(nai.network.netId);
2181 } catch (Exception e) {
2182 loge("Exception removing network: " + e);
2183 }
2184 }
2185 synchronized (mNetworkForNetId) {
2186 mNetIdInUse.delete(nai.network.netId);
2187 }
2188 } else {
2189 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2190 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002191 }
2192 }
2193
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002194 // If this method proves to be too slow then we can maintain a separate
2195 // pendingIntent => NetworkRequestInfo map.
2196 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2197 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2198 Intent intent = pendingIntent.getIntent();
2199 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2200 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2201 if (existingPendingIntent != null &&
2202 existingPendingIntent.getIntent().filterEquals(intent)) {
2203 return entry.getValue();
2204 }
2205 }
2206 return null;
2207 }
2208
2209 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2210 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2211
2212 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2213 if (existingRequest != null) { // remove the existing request.
2214 if (DBG) log("Replacing " + existingRequest.request + " with "
2215 + nri.request + " because their intents matched.");
2216 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2217 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002218 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002219 }
2220
Erik Klineda4bfa82015-04-30 12:58:40 +09002221 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002222 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002223 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002224 rematchAllNetworksAndRequests(null, 0);
2225 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2226 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002227 }
2228 }
2229
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002230 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2231 int callingUid) {
2232 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2233 if (nri != null) {
2234 handleReleaseNetworkRequest(nri.request, callingUid);
2235 }
2236 }
2237
Paul Jensen99364842014-12-09 11:43:45 -05002238 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002239 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2240 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002241 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002242 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002243 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2244 // If this Network is already the highest scoring Network for a request, or if
2245 // there is hope for it to become one if it validated, then it is needed.
2246 if (nri.isRequest && nai.satisfies(nri.request) &&
2247 (nai.networkRequests.get(nri.request.requestId) != null ||
2248 // Note that this catches two important cases:
2249 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2250 // is currently satisfying the request. This is desirable when
2251 // cellular ends up validating but WiFi does not.
2252 // 2. Unvalidated WiFi will not be reaped when validated cellular
2253 // is currently satsifying the request. This is desirable when
2254 // WiFi ends up validating and out scoring cellular.
2255 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2256 nai.getCurrentScoreAsValidated())) {
2257 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002258 }
2259 }
Paul Jensene0988542015-06-25 15:30:08 -04002260 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002261 }
2262
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002263 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2264 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002265 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002266 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002267 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2268 return;
2269 }
2270 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002271 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002272 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002273 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002274 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002275 // Find all networks that are satisfying this request and remove the request
2276 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002277 // TODO - it's my understanding that for a request there is only a single
2278 // network satisfying it, so this loop is wasteful
2279 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002280 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2281 if (nai.networkRequests.get(nri.request.requestId) != null) {
2282 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002283 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002284 log(" Removing from current network " + nai.name() +
2285 ", leaving " + nai.networkRequests.size() +
2286 " requests.");
2287 }
Paul Jensen99364842014-12-09 11:43:45 -05002288 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002289 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002290 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002291 } else {
2292 // suspect there should only be one pass through here
2293 // but if any were kept do the check below
2294 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002295 }
2296 }
2297 }
2298
Robert Greenwalt51481852015-01-08 14:43:31 -08002299 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2300 if (nai != null) {
2301 mNetworkForRequestId.remove(nri.request.requestId);
2302 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002303 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002304 // that a network connected to serve it, even though the network was already
2305 // connected. Now that this request has gone away, we might have to pretend
2306 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002307 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002308 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2309 boolean doRemove = true;
2310 if (wasKept) {
2311 // check if any of the remaining requests for this network are for the
2312 // same legacy type - if so, don't remove the nai
2313 for (int i = 0; i < nai.networkRequests.size(); i++) {
2314 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2315 if (otherRequest.legacyType == nri.request.legacyType &&
2316 isRequest(otherRequest)) {
2317 if (DBG) log(" still have other legacy request - leaving");
2318 doRemove = false;
2319 }
2320 }
2321 }
2322
2323 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002324 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002325 }
2326 }
2327
Robert Greenwalta67be032014-05-16 15:49:14 -07002328 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002329 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2330 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002331 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002332 } else {
2333 // listens don't have a singular affectedNetwork. Check all networks to see
2334 // if this listen request applies and remove it.
2335 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2336 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002337 }
2338 }
2339 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2340 }
2341 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002342
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002343 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2344 enforceConnectivityInternalPermission();
2345 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2346 accept ? 1 : 0, always ? 1: 0, network));
2347 }
2348
2349 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2350 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2351 " accept=" + accept + " always=" + always);
2352
2353 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2354 if (nai == null) {
2355 // Nothing to do.
2356 return;
2357 }
2358
2359 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002360 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002361 return;
2362 }
2363
2364 if (!nai.networkMisc.explicitlySelected) {
2365 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2366 }
2367
2368 if (accept != nai.networkMisc.acceptUnvalidated) {
2369 int oldScore = nai.getCurrentScore();
2370 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002371 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002372 sendUpdatedScoreToFactories(nai);
2373 }
2374
2375 if (always) {
2376 nai.asyncChannel.sendMessage(
2377 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2378 }
2379
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002380 if (!accept) {
2381 // Tell the NetworkAgent that the network does not have Internet access (because that's
2382 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2383 // the future. We do this now because NetworkMonitor might not yet have finished
2384 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2385 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2386 NetworkAgent.INVALID_NETWORK, 0, null);
2387 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2388 // to reconnect to it immediately. http://b/20739299
2389 }
2390
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002391 }
2392
2393 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002394 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002395 mHandler.sendMessageDelayed(
2396 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2397 PROMPT_UNVALIDATED_DELAY_MS);
2398 }
2399
2400 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002401 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002402 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2403
2404 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2405 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002406 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002407 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002408 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2409 return;
2410 }
2411
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002412 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002413 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002414 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2415 intent.setClassName("com.android.settings",
2416 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002417
2418 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2419 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2420 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002421 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002422 }
2423
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002424 private class InternalHandler extends Handler {
2425 public InternalHandler(Looper looper) {
2426 super(looper);
2427 }
2428
2429 @Override
2430 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002431 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002432 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002433 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002434 String causedBy = null;
2435 synchronized (ConnectivityService.this) {
2436 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2437 mNetTransitionWakeLock.isHeld()) {
2438 mNetTransitionWakeLock.release();
2439 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002440 } else {
2441 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002442 }
2443 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002444 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2445 log("Failed to find a new network - expiring NetTransition Wakelock");
2446 } else {
2447 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2448 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002449 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002450 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002451 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002452 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002453 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002454 break;
2455 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002456 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002457 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002458 sendStickyBroadcast(intent);
2459 break;
2460 }
Jason Monkdecd2952013-10-10 14:02:51 -04002461 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002462 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002463 break;
2464 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002465 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002466 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2467 break;
2468 }
2469 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2470 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002471 break;
2472 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002473 case EVENT_REGISTER_NETWORK_AGENT: {
2474 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2475 break;
2476 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002477 case EVENT_REGISTER_NETWORK_REQUEST:
2478 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002479 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002480 break;
2481 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002482 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2483 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002484 handleRegisterNetworkRequestWithIntent(msg);
2485 break;
2486 }
2487 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2488 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2489 break;
2490 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002491 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002492 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002493 break;
2494 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002495 case EVENT_SET_ACCEPT_UNVALIDATED: {
2496 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2497 break;
2498 }
2499 case EVENT_PROMPT_UNVALIDATED: {
2500 handlePromptUnvalidated((Network) msg.obj);
2501 break;
2502 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002503 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2504 handleMobileDataAlwaysOn();
2505 break;
2506 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002507 case EVENT_SYSTEM_READY: {
2508 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2509 nai.networkMonitor.systemReady = true;
2510 }
2511 break;
2512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 }
2514 }
2515 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002516
2517 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002518 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002519 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002520 if (isTetheringSupported()) {
2521 return mTethering.tether(iface);
2522 } else {
2523 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2524 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002525 }
2526
2527 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002528 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002529 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002530
2531 if (isTetheringSupported()) {
2532 return mTethering.untether(iface);
2533 } else {
2534 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2535 }
2536 }
2537
2538 // javadoc from interface
2539 public int getLastTetherError(String iface) {
2540 enforceTetherAccessPermission();
2541
2542 if (isTetheringSupported()) {
2543 return mTethering.getLastTetherError(iface);
2544 } else {
2545 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2546 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002547 }
2548
2549 // TODO - proper iface API for selection by property, inspection, etc
2550 public String[] getTetherableUsbRegexs() {
2551 enforceTetherAccessPermission();
2552 if (isTetheringSupported()) {
2553 return mTethering.getTetherableUsbRegexs();
2554 } else {
2555 return new String[0];
2556 }
2557 }
2558
2559 public String[] getTetherableWifiRegexs() {
2560 enforceTetherAccessPermission();
2561 if (isTetheringSupported()) {
2562 return mTethering.getTetherableWifiRegexs();
2563 } else {
2564 return new String[0];
2565 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002566 }
2567
Danica Chang6fdd0c62010-08-11 14:54:43 -07002568 public String[] getTetherableBluetoothRegexs() {
2569 enforceTetherAccessPermission();
2570 if (isTetheringSupported()) {
2571 return mTethering.getTetherableBluetoothRegexs();
2572 } else {
2573 return new String[0];
2574 }
2575 }
2576
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002577 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002578 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002579 if (isTetheringSupported()) {
2580 return mTethering.setUsbTethering(enable);
2581 } else {
2582 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2583 }
2584 }
2585
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002586 // TODO - move iface listing, queries, etc to new module
2587 // javadoc from interface
2588 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002589 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002590 return mTethering.getTetherableIfaces();
2591 }
2592
2593 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002594 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002595 return mTethering.getTetheredIfaces();
2596 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002597
Robert Greenwalt5a735062010-03-02 17:25:02 -08002598 public String[] getTetheringErroredIfaces() {
2599 enforceTetherAccessPermission();
2600 return mTethering.getErroredIfaces();
2601 }
2602
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002603 public String[] getTetheredDhcpRanges() {
2604 enforceConnectivityInternalPermission();
2605 return mTethering.getTetheredDhcpRanges();
2606 }
2607
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002608 // if ro.tether.denied = true we default to no tethering
2609 // gservices could set the secure setting to 1 though to enable it on a build where it
2610 // had previously been turned off.
2611 public boolean isTetheringSupported() {
2612 enforceTetherAccessPermission();
2613 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002614 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002615 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2616 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002617 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2618 mTethering.getTetherableWifiRegexs().length != 0 ||
2619 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2620 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002621 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002622
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002623 // Called when we lose the default network and have no replacement yet.
2624 // This will automatically be cleared after X seconds or a new default network
2625 // becomes CONNECTED, whichever happens first. The timer is started by the
2626 // first caller and not restarted by subsequent callers.
2627 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002628 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002629 synchronized (this) {
2630 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002631 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002632 mNetTransitionWakeLock.acquire();
2633 mNetTransitionWakeLockCausedBy = forWhom;
2634 }
2635 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002636 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002637 mNetTransitionWakeLockTimeout);
2638 return;
2639 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002640
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002641 // 100 percent is full good, 0 is full bad.
2642 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002643 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002644 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002645 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002646 }
2647
Paul Jensenbfd17b72015-04-07 12:43:13 -04002648 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002649 enforceAccessPermission();
2650 enforceInternetPermission();
2651
Paul Jensenbfd17b72015-04-07 12:43:13 -04002652 NetworkAgentInfo nai;
2653 if (network == null) {
2654 nai = getDefaultNetwork();
2655 } else {
2656 nai = getNetworkAgentInfoForNetwork(network);
2657 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002658 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2659 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2660 return;
2661 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002662 // Revalidate if the app report does not match our current validated state.
2663 if (hasConnectivity == nai.lastValidated) return;
2664 final int uid = Binder.getCallingUid();
2665 if (DBG) {
2666 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2667 ") by " + uid);
2668 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002669 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002670 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2671 // which isn't meant to work on uncreated networks.
2672 if (!nai.created) return;
2673
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002674 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002675
2676 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2677 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002678 }
2679
Paul Jensencee9b512015-05-06 07:32:40 -04002680 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002681 // this information is already available as a world read/writable jvm property
2682 // so this API change wouldn't have a benifit. It also breaks the passing
2683 // of proxy info to all the JVMs.
2684 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002685 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002686 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002687 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2688 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002689 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002690 }
2691
Paul Jensencee9b512015-05-06 07:32:40 -04002692 public ProxyInfo getProxyForNetwork(Network network) {
2693 if (network == null) return getDefaultProxy();
2694 final ProxyInfo globalProxy = getGlobalProxy();
2695 if (globalProxy != null) return globalProxy;
2696 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2697 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2698 // caller may not have.
2699 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2700 if (nai == null) return null;
2701 synchronized (nai) {
2702 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2703 if (proxyInfo == null) return null;
2704 return new ProxyInfo(proxyInfo);
2705 }
2706 }
2707
Paul Jensene0bef712014-12-10 15:12:18 -05002708 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2709 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2710 // proxy is null then there is no proxy in place).
2711 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2712 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2713 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2714 proxy = null;
2715 }
2716 return proxy;
2717 }
2718
2719 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2720 // better for determining if a new proxy broadcast is necessary:
2721 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2722 // avoid unnecessary broadcasts.
2723 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2724 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2725 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2726 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2727 // all set.
2728 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2729 a = canonicalizeProxyInfo(a);
2730 b = canonicalizeProxyInfo(b);
2731 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2732 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2733 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2734 }
2735
Jason Monk207900c2014-04-25 15:00:09 -04002736 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002737 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002738
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002739 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002740 if (proxyProperties == mGlobalProxy) return;
2741 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2742 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2743
2744 String host = "";
2745 int port = 0;
2746 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002747 String pacFileUrl = "";
2748 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002749 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002750 if (!proxyProperties.isValid()) {
2751 if (DBG)
2752 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2753 return;
2754 }
Jason Monk207900c2014-04-25 15:00:09 -04002755 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002756 host = mGlobalProxy.getHost();
2757 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002758 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002759 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002760 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002761 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002762 } else {
2763 mGlobalProxy = null;
2764 }
2765 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002766 final long token = Binder.clearCallingIdentity();
2767 try {
2768 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2769 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2770 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2771 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002772 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002773 } finally {
2774 Binder.restoreCallingIdentity(token);
2775 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002776
Jason Monkcf0f97a2014-10-02 15:39:38 -04002777 if (mGlobalProxy == null) {
2778 proxyProperties = mDefaultProxy;
2779 }
2780 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002781 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002782 }
2783
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002784 private void loadGlobalProxy() {
2785 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002786 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2787 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2788 String exclList = Settings.Global.getString(res,
2789 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002790 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2791 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002792 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002793 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002794 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002795 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002796 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002797 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002798 if (!proxyProperties.isValid()) {
2799 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2800 return;
2801 }
2802
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002803 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002804 mGlobalProxy = proxyProperties;
2805 }
2806 }
2807 }
2808
Jason Monk207900c2014-04-25 15:00:09 -04002809 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002810 // this information is already available as a world read/writable jvm property
2811 // so this API change wouldn't have a benifit. It also breaks the passing
2812 // of proxy info to all the JVMs.
2813 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002814 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002815 return mGlobalProxy;
2816 }
2817 }
2818
Jason Monk207900c2014-04-25 15:00:09 -04002819 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002820 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002821 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002822 proxy = null;
2823 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002824 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002825 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002826 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002827 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002828 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2829 return;
2830 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002831
2832 // This call could be coming from the PacManager, containing the port of the local
2833 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2834 // global (to get the correct local port), and send a broadcast.
2835 // TODO: Switch PacManager to have its own message to send back rather than
2836 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002837 if ((mGlobalProxy != null) && (proxy != null)
2838 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002839 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2840 mGlobalProxy = proxy;
2841 sendProxyBroadcast(mGlobalProxy);
2842 return;
2843 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002844 mDefaultProxy = proxy;
2845
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002846 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002847 if (!mDefaultProxyDisabled) {
2848 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002849 }
2850 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002851 }
2852
Paul Jensene0bef712014-12-10 15:12:18 -05002853 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2854 // This method gets called when any network changes proxy, but the broadcast only ever contains
2855 // the default proxy (even if it hasn't changed).
2856 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2857 // world where an app might be bound to a non-default network.
2858 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2859 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2860 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2861
2862 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2863 sendProxyBroadcast(getDefaultProxy());
2864 }
2865 }
2866
Robert Greenwalt434203a2010-10-11 16:00:27 -07002867 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002868 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2869 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002870 if (!TextUtils.isEmpty(proxy)) {
2871 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002872 if (data.length == 0) {
2873 return;
2874 }
2875
Robert Greenwalt434203a2010-10-11 16:00:27 -07002876 String proxyHost = data[0];
2877 int proxyPort = 8080;
2878 if (data.length > 1) {
2879 try {
2880 proxyPort = Integer.parseInt(data[1]);
2881 } catch (NumberFormatException e) {
2882 return;
2883 }
2884 }
Jason Monk207900c2014-04-25 15:00:09 -04002885 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002886 setGlobalProxy(p);
2887 }
2888 }
2889
Jason Monk207900c2014-04-25 15:00:09 -04002890 private void sendProxyBroadcast(ProxyInfo proxy) {
2891 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002892 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002893 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002894 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002895 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2896 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002897 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002898 final long ident = Binder.clearCallingIdentity();
2899 try {
2900 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2901 } finally {
2902 Binder.restoreCallingIdentity(ident);
2903 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002904 }
2905
2906 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002907 final private HashMap<Uri, Integer> mUriEventMap;
2908 final private Context mContext;
2909 final private Handler mHandler;
2910
2911 SettingsObserver(Context context, Handler handler) {
2912 super(null);
2913 mUriEventMap = new HashMap<Uri, Integer>();
2914 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002915 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002916 }
2917
Erik Klineda4bfa82015-04-30 12:58:40 +09002918 void observe(Uri uri, int what) {
2919 mUriEventMap.put(uri, what);
2920 final ContentResolver resolver = mContext.getContentResolver();
2921 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002922 }
2923
2924 @Override
2925 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002926 Slog.wtf(TAG, "Should never be reached.");
2927 }
2928
2929 @Override
2930 public void onChange(boolean selfChange, Uri uri) {
2931 final Integer what = mUriEventMap.get(uri);
2932 if (what != null) {
2933 mHandler.obtainMessage(what.intValue()).sendToTarget();
2934 } else {
2935 loge("No matching event to send for URI=" + uri);
2936 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002937 }
2938 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002939
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002940 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002941 Slog.d(TAG, s);
2942 }
2943
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002944 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002945 Slog.e(TAG, s);
2946 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002947
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002948 private static <T> T checkNotNull(T value, String message) {
2949 if (value == null) {
2950 throw new NullPointerException(message);
2951 }
2952 return value;
2953 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002954
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002955 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002956 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002957 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2958 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2959 *
2960 * @param oldPackage Package name of the application which currently controls VPN, which will
2961 * be replaced. If there is no such application, this should should either be
2962 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2963 * @param newPackage Package name of the application which should gain control of VPN, or
2964 * {@code null} to disable.
2965 * @param userId User for whom to prepare the new VPN.
2966 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002967 * @hide
2968 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002969 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002970 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2971 int userId) {
2972 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002973 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01002974
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002975 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07002976 Vpn vpn = mVpns.get(userId);
2977 if (vpn != null) {
2978 return vpn.prepare(oldPackage, newPackage);
2979 } else {
2980 return false;
2981 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002982 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002983 }
2984
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002985 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01002986 * Set whether the VPN package has the ability to launch VPNs without user intervention.
2987 * This method is used by system-privileged apps.
2988 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2989 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2990 *
2991 * @param packageName The package for which authorization state should change.
2992 * @param userId User for whom {@code packageName} is installed.
2993 * @param authorized {@code true} if this app should be able to start a VPN connection without
2994 * explicit user approval, {@code false} if not.
2995 *
Jeff Davidson05542602014-08-11 14:07:27 -07002996 * @hide
2997 */
2998 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002999 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3000 enforceCrossUserPermission(userId);
3001
Jeff Davidson05542602014-08-11 14:07:27 -07003002 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003003 Vpn vpn = mVpns.get(userId);
3004 if (vpn != null) {
3005 vpn.setPackageAuthorization(packageName, authorized);
3006 }
Jeff Davidson05542602014-08-11 14:07:27 -07003007 }
3008 }
3009
3010 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003011 * Configure a TUN interface and return its file descriptor. Parameters
3012 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003013 * and not available in ConnectivityManager. Permissions are checked in
3014 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003015 * @hide
3016 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003017 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003018 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003019 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003020 int user = UserHandle.getUserId(Binder.getCallingUid());
3021 synchronized(mVpns) {
3022 return mVpns.get(user).establish(config);
3023 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003024 }
3025
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003026 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003027 * Start legacy VPN, controlling native daemons as needed. Creates a
3028 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003029 */
3030 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003031 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003032 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003033 final LinkProperties egress = getActiveLinkProperties();
3034 if (egress == null) {
3035 throw new IllegalStateException("Missing active network connection");
3036 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003037 int user = UserHandle.getUserId(Binder.getCallingUid());
3038 synchronized(mVpns) {
3039 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3040 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003041 }
3042
3043 /**
3044 * Return the information of the ongoing legacy VPN. This method is used
3045 * by VpnSettings and not available in ConnectivityManager. Permissions
3046 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003047 */
3048 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003049 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3050 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003051 if (mLockdownEnabled) {
3052 return null;
3053 }
3054
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003055 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003056 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003057 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003058 }
3059
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003060 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003061 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3062 * and not available in ConnectivityManager.
3063 */
3064 @Override
3065 public VpnInfo[] getAllVpnInfo() {
3066 enforceConnectivityInternalPermission();
3067 if (mLockdownEnabled) {
3068 return new VpnInfo[0];
3069 }
3070
3071 synchronized(mVpns) {
3072 List<VpnInfo> infoList = new ArrayList<>();
3073 for (int i = 0; i < mVpns.size(); i++) {
3074 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3075 if (info != null) {
3076 infoList.add(info);
3077 }
3078 }
3079 return infoList.toArray(new VpnInfo[infoList.size()]);
3080 }
3081 }
3082
3083 /**
3084 * @return VPN information for accounting, or null if we can't retrieve all required
3085 * information, e.g primary underlying iface.
3086 */
3087 @Nullable
3088 private VpnInfo createVpnInfo(Vpn vpn) {
3089 VpnInfo info = vpn.getVpnInfo();
3090 if (info == null) {
3091 return null;
3092 }
3093 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3094 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3095 // the underlyingNetworks list.
3096 if (underlyingNetworks == null) {
3097 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3098 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3099 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3100 }
3101 } else if (underlyingNetworks.length > 0) {
3102 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3103 if (linkProperties != null) {
3104 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3105 }
3106 }
3107 return info.primaryUnderlyingIface == null ? null : info;
3108 }
3109
3110 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003111 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3112 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003113 * Permissions are checked in Vpn class.
3114 * @hide
3115 */
3116 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003117 public VpnConfig getVpnConfig(int userId) {
3118 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003119 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003120 Vpn vpn = mVpns.get(userId);
3121 if (vpn != null) {
3122 return vpn.getVpnConfig();
3123 } else {
3124 return null;
3125 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003126 }
3127 }
3128
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003129 @Override
3130 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003131 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3132 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3133 return false;
3134 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003135
3136 // Tear down existing lockdown if profile was removed
3137 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3138 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003139 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003140 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3141 return false;
3142 }
3143
3144 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3145 final VpnProfile profile = VpnProfile.decode(
3146 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003147 int user = UserHandle.getUserId(Binder.getCallingUid());
3148 synchronized(mVpns) {
3149 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3150 profile));
3151 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003152 } else {
3153 setLockdownTracker(null);
3154 }
3155
3156 return true;
3157 }
3158
3159 /**
3160 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3161 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3162 */
3163 private void setLockdownTracker(LockdownVpnTracker tracker) {
3164 // Shutdown any existing tracker
3165 final LockdownVpnTracker existing = mLockdownTracker;
3166 mLockdownTracker = null;
3167 if (existing != null) {
3168 existing.shutdown();
3169 }
3170
3171 try {
3172 if (tracker != null) {
3173 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003174 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003175 mLockdownTracker = tracker;
3176 mLockdownTracker.init();
3177 } else {
3178 mNetd.setFirewallEnabled(false);
3179 }
3180 } catch (RemoteException e) {
3181 // ignored; NMS lives inside system_server
3182 }
3183 }
3184
3185 private void throwIfLockdownEnabled() {
3186 if (mLockdownEnabled) {
3187 throw new IllegalStateException("Unavailable in lockdown mode");
3188 }
3189 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003190
Wink Savilleab9321d2013-06-29 21:10:57 -07003191 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003192 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003193 // TODO: Remove? Any reason to trigger a provisioning check?
3194 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003195 }
3196
3197 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003198 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003199
Paul Jensen89e0f092014-09-15 15:59:36 -04003200 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003201 if (DBG) {
3202 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003203 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003204 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003205 Intent intent = new Intent(action);
3206 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003207 // Concatenate the range of types onto the range of NetIDs.
3208 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003209 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003210 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003211 }
3212
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003213 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003214 * Show or hide network provisioning notifications.
3215 *
3216 * We use notifications for two purposes: to notify that a network requires sign in
3217 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3218 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3219 * particular network we can display the notification type that was most recently requested.
3220 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3221 * might first display NO_INTERNET, and then when the captive portal check completes, display
3222 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003223 *
3224 * @param id an identifier that uniquely identifies this notification. This must match
3225 * between show and hide calls. We use the NetID value but for legacy callers
3226 * we concatenate the range of types with the range of NetIDs.
3227 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003228 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003229 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3230 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003231 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003232 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3233 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003234 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003235 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003236
3237 Resources r = Resources.getSystem();
3238 NotificationManager notificationManager = (NotificationManager) mContext
3239 .getSystemService(Context.NOTIFICATION_SERVICE);
3240
3241 if (visible) {
3242 CharSequence title;
3243 CharSequence details;
3244 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003245 if (notifyType == NotificationType.NO_INTERNET &&
3246 networkType == ConnectivityManager.TYPE_WIFI) {
3247 title = r.getString(R.string.wifi_no_internet, 0);
3248 details = r.getString(R.string.wifi_no_internet_detailed);
3249 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3250 } else if (notifyType == NotificationType.SIGN_IN) {
3251 switch (networkType) {
3252 case ConnectivityManager.TYPE_WIFI:
3253 title = r.getString(R.string.wifi_available_sign_in, 0);
3254 details = r.getString(R.string.network_available_sign_in_detailed,
3255 extraInfo);
3256 icon = R.drawable.stat_notify_wifi_in_range;
3257 break;
3258 case ConnectivityManager.TYPE_MOBILE:
3259 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3260 title = r.getString(R.string.network_available_sign_in, 0);
3261 // TODO: Change this to pull from NetworkInfo once a printable
3262 // name has been added to it
3263 details = mTelephonyManager.getNetworkOperatorName();
3264 icon = R.drawable.stat_notify_rssi_in_range;
3265 break;
3266 default:
3267 title = r.getString(R.string.network_available_sign_in, 0);
3268 details = r.getString(R.string.network_available_sign_in_detailed,
3269 extraInfo);
3270 icon = R.drawable.stat_notify_rssi_in_range;
3271 break;
3272 }
3273 } else {
3274 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3275 + getNetworkTypeName(networkType));
3276 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003277 }
3278
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003279 Notification notification = new Notification.Builder(mContext)
3280 .setWhen(0)
3281 .setSmallIcon(icon)
3282 .setAutoCancel(true)
3283 .setTicker(title)
3284 .setColor(mContext.getColor(
3285 com.android.internal.R.color.system_notification_accent_color))
3286 .setContentTitle(title)
3287 .setContentText(details)
3288 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003289 .setLocalOnly(true)
3290 .setPriority(highPriority ?
3291 Notification.PRIORITY_HIGH :
3292 Notification.PRIORITY_DEFAULT)
3293 .setDefaults(Notification.DEFAULT_ALL)
3294 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003295 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003296
Wink Saville948282b2013-08-29 08:55:16 -07003297 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003298 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003299 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003300 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003301 npe.printStackTrace();
3302 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003303 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003304 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003305 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003306 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003307 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003308 npe.printStackTrace();
3309 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003310 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003311 }
3312
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003313 /** Location to an updatable file listing carrier provisioning urls.
3314 * An example:
3315 *
3316 * <?xml version="1.0" encoding="utf-8"?>
3317 * <provisioningUrls>
3318 * <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 -07003319 * </provisioningUrls>
3320 */
3321 private static final String PROVISIONING_URL_PATH =
3322 "/data/misc/radio/provisioning_urls.xml";
3323 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003324
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003325 /** XML tag for root element. */
3326 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3327 /** XML tag for individual url */
3328 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003329 /** XML attribute for mcc */
3330 private static final String ATTR_MCC = "mcc";
3331 /** XML attribute for mnc */
3332 private static final String ATTR_MNC = "mnc";
3333
Paul Jensen434dde82015-06-11 09:43:30 -04003334 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003335 FileReader fileReader = null;
3336 XmlPullParser parser = null;
3337 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003338
3339 try {
3340 fileReader = new FileReader(mProvisioningUrlFile);
3341 parser = Xml.newPullParser();
3342 parser.setInput(fileReader);
3343 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3344
3345 while (true) {
3346 XmlUtils.nextElement(parser);
3347
3348 String element = parser.getName();
3349 if (element == null) break;
3350
Paul Jensen434dde82015-06-11 09:43:30 -04003351 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003352 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3353 try {
3354 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3355 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3356 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3357 parser.next();
3358 if (parser.getEventType() == XmlPullParser.TEXT) {
3359 return parser.getText();
3360 }
3361 }
3362 }
3363 } catch (NumberFormatException e) {
3364 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3365 }
3366 }
3367 }
3368 return null;
3369 } catch (FileNotFoundException e) {
3370 loge("Carrier Provisioning Urls file not found");
3371 } catch (XmlPullParserException e) {
3372 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3373 } catch (IOException e) {
3374 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3375 } finally {
3376 if (fileReader != null) {
3377 try {
3378 fileReader.close();
3379 } catch (IOException e) {}
3380 }
3381 }
3382 return null;
3383 }
3384
Wink Saville42d4f082013-07-20 20:31:59 -07003385 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003386 public String getMobileProvisioningUrl() {
3387 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003388 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003389 if (TextUtils.isEmpty(url)) {
3390 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003391 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003392 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003393 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003394 }
Wink Saville8cf35602013-07-10 23:00:07 -07003395 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003396 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003397 String phoneNumber = mTelephonyManager.getLine1Number();
3398 if (TextUtils.isEmpty(phoneNumber)) {
3399 phoneNumber = "0000000000";
3400 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003401 url = String.format(url,
3402 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3403 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003404 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003405 }
3406
Wink Savilleab9321d2013-06-29 21:10:57 -07003407 return url;
3408 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003409
Wink Saville948282b2013-08-29 08:55:16 -07003410 @Override
3411 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003412 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003413 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003414 final long ident = Binder.clearCallingIdentity();
3415 try {
3416 setProvNotificationVisible(visible, networkType, action);
3417 } finally {
3418 Binder.restoreCallingIdentity(ident);
3419 }
Wink Saville948282b2013-08-29 08:55:16 -07003420 }
Wink Saville7788c612013-08-29 14:57:08 -07003421
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003422 @Override
3423 public void setAirplaneMode(boolean enable) {
3424 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003425 final long ident = Binder.clearCallingIdentity();
3426 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003427 final ContentResolver cr = mContext.getContentResolver();
3428 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3429 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3430 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003431 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003432 } finally {
3433 Binder.restoreCallingIdentity(ident);
3434 }
3435 }
3436
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003437 private void onUserStart(int userId) {
3438 synchronized(mVpns) {
3439 Vpn userVpn = mVpns.get(userId);
3440 if (userVpn != null) {
3441 loge("Starting user already has a VPN");
3442 return;
3443 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003444 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003445 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003446 }
3447 }
3448
3449 private void onUserStop(int userId) {
3450 synchronized(mVpns) {
3451 Vpn userVpn = mVpns.get(userId);
3452 if (userVpn == null) {
3453 loge("Stopping user has no VPN");
3454 return;
3455 }
3456 mVpns.delete(userId);
3457 }
3458 }
3459
3460 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3461 @Override
3462 public void onReceive(Context context, Intent intent) {
3463 final String action = intent.getAction();
3464 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3465 if (userId == UserHandle.USER_NULL) return;
3466
3467 if (Intent.ACTION_USER_STARTING.equals(action)) {
3468 onUserStart(userId);
3469 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3470 onUserStop(userId);
3471 }
3472 }
3473 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003474
Robert Greenwalta67be032014-05-16 15:49:14 -07003475 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3476 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003477 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3478 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003479
Robert Greenwalta67be032014-05-16 15:49:14 -07003480 private static class NetworkFactoryInfo {
3481 public final String name;
3482 public final Messenger messenger;
3483 public final AsyncChannel asyncChannel;
3484
3485 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3486 this.name = name;
3487 this.messenger = messenger;
3488 this.asyncChannel = asyncChannel;
3489 }
3490 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003491
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003492 /**
3493 * Tracks info about the requester.
3494 * Also used to notice when the calling process dies so we can self-expire
3495 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003496 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3497 static final boolean REQUEST = true;
3498 static final boolean LISTEN = false;
3499
3500 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003501 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003502 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003503 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003504 final int mPid;
3505 final int mUid;
3506 final Messenger messenger;
3507 final boolean isRequest;
3508
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003509 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3510 request = r;
3511 mPendingIntent = pi;
3512 messenger = null;
3513 mBinder = null;
3514 mPid = getCallingPid();
3515 mUid = getCallingUid();
3516 this.isRequest = isRequest;
3517 }
3518
Robert Greenwalt9258c642014-03-26 16:47:06 -07003519 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3520 super();
3521 messenger = m;
3522 request = r;
3523 mBinder = binder;
3524 mPid = getCallingPid();
3525 mUid = getCallingUid();
3526 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003527 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003528
3529 try {
3530 mBinder.linkToDeath(this, 0);
3531 } catch (RemoteException e) {
3532 binderDied();
3533 }
3534 }
3535
3536 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003537 if (mBinder != null) {
3538 mBinder.unlinkToDeath(this, 0);
3539 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003540 }
3541
3542 public void binderDied() {
3543 log("ConnectivityService NetworkRequestInfo binderDied(" +
3544 request + ", " + mBinder + ")");
3545 releaseNetworkRequest(request);
3546 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003547
3548 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003549 return (isRequest ? "Request" : "Listen") +
3550 " from uid/pid:" + mUid + "/" + mPid +
3551 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003552 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003553 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003554 }
3555
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003556 private void ensureImmutableCapabilities(NetworkCapabilities networkCapabilities) {
3557 if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
3558 throw new IllegalArgumentException(
3559 "Cannot request network with NET_CAPABILITY_VALIDATED");
3560 }
3561 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
3562 throw new IllegalArgumentException(
3563 "Cannot request network with NET_CAPABILITY_CAPTIVE_PORTAL");
3564 }
3565 }
3566
Robert Greenwalt9258c642014-03-26 16:47:06 -07003567 @Override
3568 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003569 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003570 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003571 enforceNetworkRequestPermissions(networkCapabilities);
3572 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003573 ensureImmutableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003574
Robert Greenwalt6078b502014-06-11 16:05:07 -07003575 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003576 throw new IllegalArgumentException("Bad timeout specified");
3577 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003578
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003579 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3580 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003581 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3582 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003583 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003584
3585 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003586 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003587 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003588 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003589 }
3590 return networkRequest;
3591 }
3592
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003593 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003594 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003595 enforceConnectivityInternalPermission();
3596 } else {
3597 enforceChangePermission();
3598 }
3599 }
3600
fenglub15e72b2015-03-20 11:29:56 -07003601 @Override
fengludb571472015-04-21 17:12:05 -07003602 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003603 enforceAccessPermission();
3604 NetworkAgentInfo nai = null;
3605 if (network == null) {
3606 return false;
3607 }
3608 synchronized (mNetworkForNetId) {
3609 nai = mNetworkForNetId.get(network.netId);
3610 }
3611 if (nai != null) {
3612 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3613 return true;
3614 }
3615 return false;
3616 }
3617
3618
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003619 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3620 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003621 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003622 final int uidRules;
3623 final int uid = Binder.getCallingUid();
3624 synchronized(mRulesLock) {
3625 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3626 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003627 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003628 // we could silently fail or we can filter the available nets to only give
3629 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003630 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003631 }
3632 }
3633 }
3634
Robert Greenwalt9258c642014-03-26 16:47:06 -07003635 @Override
3636 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3637 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003638 checkNotNull(operation, "PendingIntent cannot be null.");
3639 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3640 enforceNetworkRequestPermissions(networkCapabilities);
3641 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003642 ensureImmutableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003643
3644 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3645 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003646 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3647 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003648 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003649 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3650 nri));
3651 return networkRequest;
3652 }
3653
Jeremy Joslin79294842014-12-03 17:15:28 -08003654 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3655 mHandler.sendMessageDelayed(
3656 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3657 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3658 }
3659
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003660 @Override
3661 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003662 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003663 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3664 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003665 }
3666
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003667 // In order to implement the compatibility measure for pre-M apps that call
3668 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3669 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3670 // This ensures it has permission to do so.
3671 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3672 if (nc == null) {
3673 return false;
3674 }
3675 int[] transportTypes = nc.getTransportTypes();
3676 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3677 return false;
3678 }
3679 try {
3680 mContext.enforceCallingOrSelfPermission(
3681 android.Manifest.permission.ACCESS_WIFI_STATE,
3682 "ConnectivityService");
3683 } catch (SecurityException e) {
3684 return false;
3685 }
3686 return true;
3687 }
3688
Robert Greenwalt9258c642014-03-26 16:47:06 -07003689 @Override
3690 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3691 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003692 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3693 enforceAccessPermission();
3694 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003695
Erik Kline7523eb32015-07-09 18:24:03 +09003696 NetworkRequest networkRequest = new NetworkRequest(
3697 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003698 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3699 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003700 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003701
3702 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3703 return networkRequest;
3704 }
3705
3706 @Override
3707 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3708 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003709 checkNotNull(operation, "PendingIntent cannot be null.");
3710 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3711 enforceAccessPermission();
3712 }
3713
Erik Kline7523eb32015-07-09 18:24:03 +09003714 NetworkRequest networkRequest = new NetworkRequest(
3715 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003716 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3717 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003718 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003719
3720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003721 }
3722
3723 @Override
3724 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003725 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3726 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003727 }
3728
3729 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003730 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003731 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003732 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3733 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003734 }
3735
Robert Greenwalta67be032014-05-16 15:49:14 -07003736 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003737 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003738 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3739 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3740 }
3741
3742 @Override
3743 public void unregisterNetworkFactory(Messenger messenger) {
3744 enforceConnectivityInternalPermission();
3745 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3746 }
3747
3748 private void handleUnregisterNetworkFactory(Messenger messenger) {
3749 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3750 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003751 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003752 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003753 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003754 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003755 }
3756
Robert Greenwalt7b816022014-04-18 15:25:25 -07003757 /**
3758 * NetworkAgentInfo supporting a request by requestId.
3759 * These have already been vetted (their Capabilities satisfy the request)
3760 * and the are the highest scored network available.
3761 * the are keyed off the Requests requestId.
3762 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003763 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003764 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3765 new SparseArray<NetworkAgentInfo>();
3766
Paul Jensen31a94f42015-02-13 14:18:39 -05003767 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3768 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003769 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3770 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003771 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3772 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3773 // there may not be a strict 1:1 correlation between the two.
3774 @GuardedBy("mNetworkForNetId")
3775 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003776
Robert Greenwalt7b816022014-04-18 15:25:25 -07003777 // NetworkAgentInfo keyed off its connecting messenger
3778 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003779 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003780 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3781 new HashMap<Messenger, NetworkAgentInfo>();
3782
Paul Jensen2c311d62014-11-17 12:34:51 -05003783 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003784 private final NetworkRequest mDefaultRequest;
3785
Erik Klineda4bfa82015-04-30 12:58:40 +09003786 // Request used to optionally keep mobile data active even when higher
3787 // priority networks like Wi-Fi are active.
3788 private final NetworkRequest mDefaultMobileDataRequest;
3789
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003790 private NetworkAgentInfo getDefaultNetwork() {
3791 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3792 }
3793
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003794 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003795 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003796 }
3797
Paul Jensen31a94f42015-02-13 14:18:39 -05003798 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003799 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003800 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003801 enforceConnectivityInternalPermission();
3802
Paul Jensen2c311d62014-11-17 12:34:51 -05003803 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3804 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003805 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003806 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3807 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3808 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003809 synchronized (this) {
3810 nai.networkMonitor.systemReady = mSystemReady;
3811 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003812 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003813 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003814 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003815 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003816 }
3817
3818 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3819 if (VDBG) log("Got NetworkAgent Messenger");
3820 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003821 synchronized (mNetworkForNetId) {
3822 mNetworkForNetId.put(na.network.netId, na);
3823 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003824 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3825 NetworkInfo networkInfo = na.networkInfo;
3826 na.networkInfo = null;
3827 updateNetworkInfo(na, networkInfo);
3828 }
3829
3830 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3831 LinkProperties newLp = networkAgent.linkProperties;
3832 int netId = networkAgent.network.netId;
3833
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003834 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3835 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003836 if (networkAgent.clatd != null) {
3837 networkAgent.clatd.fixupLinkProperties(oldLp);
3838 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003839
Paul Jensen992f2522014-04-28 10:33:11 -04003840 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003841 updateMtu(newLp, oldLp);
3842 // TODO - figure out what to do for clat
3843// for (LinkProperties lp : newLp.getStackedLinks()) {
3844// updateMtu(lp, null);
3845// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003846 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003847
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003848 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3849 // In L, we used it only when the network had Internet access but provided no DNS servers.
3850 // For now, just disable it, and if disabling it doesn't break things, remove it.
3851 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3852 // NET_CAPABILITY_INTERNET);
3853 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003854 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003855 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3856
Paul Jensen3b759822014-05-13 11:44:01 -04003857 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003858 if (isDefaultNetwork(networkAgent)) {
3859 handleApplyDefaultProxy(newLp.getHttpProxy());
3860 } else {
3861 updateProxy(newLp, oldLp, networkAgent);
3862 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003863 // TODO - move this check to cover the whole function
3864 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003865 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003866 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3867 }
Paul Jensen3b759822014-05-13 11:44:01 -04003868 }
3869
Lorenzo Colitti95439462014-10-09 13:44:48 +09003870 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3871 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3872 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003873
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003874 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003875 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3876 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003877 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003878 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003879 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003880 }
Paul Jensen992f2522014-04-28 10:33:11 -04003881
3882 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3883 CompareResult<String> interfaceDiff = new CompareResult<String>();
3884 if (oldLp != null) {
3885 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3886 } else if (newLp != null) {
3887 interfaceDiff.added = newLp.getAllInterfaceNames();
3888 }
3889 for (String iface : interfaceDiff.added) {
3890 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003891 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003892 mNetd.addInterfaceToNetwork(iface, netId);
3893 } catch (Exception e) {
3894 loge("Exception adding interface: " + e);
3895 }
3896 }
3897 for (String iface : interfaceDiff.removed) {
3898 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003899 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003900 mNetd.removeInterfaceFromNetwork(iface, netId);
3901 } catch (Exception e) {
3902 loge("Exception removing interface: " + e);
3903 }
3904 }
3905 }
3906
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003907 /**
3908 * Have netd update routes from oldLp to newLp.
3909 * @return true if routes changed between oldLp and newLp
3910 */
3911 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003912 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3913 if (oldLp != null) {
3914 routeDiff = oldLp.compareAllRoutes(newLp);
3915 } else if (newLp != null) {
3916 routeDiff.added = newLp.getAllRoutes();
3917 }
3918
3919 // add routes before removing old in case it helps with continuous connectivity
3920
3921 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3922 for (RouteInfo route : routeDiff.added) {
3923 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003924 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003925 try {
3926 mNetd.addRoute(netId, route);
3927 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003928 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3929 loge("Exception in addRoute for non-gateway: " + e);
3930 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003931 }
3932 }
3933 for (RouteInfo route : routeDiff.added) {
3934 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003935 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003936 try {
3937 mNetd.addRoute(netId, route);
3938 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003939 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3940 loge("Exception in addRoute for gateway: " + e);
3941 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003942 }
3943 }
3944
3945 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003946 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003947 try {
3948 mNetd.removeRoute(netId, route);
3949 } catch (Exception e) {
3950 loge("Exception in removeRoute: " + e);
3951 }
3952 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003953 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003954 }
Erik Kline41368502015-06-17 13:19:54 +09003955
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003956 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3957 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003958 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09003959 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003960 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003961 dnses = new ArrayList();
3962 dnses.add(mDefaultDns);
3963 if (DBG) {
3964 loge("no dns provided for netId " + netId + ", so using defaults");
3965 }
3966 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003967 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003968 try {
3969 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3970 newLp.getDomains());
3971 } catch (Exception e) {
3972 loge("Exception in setDnsServersForNetwork: " + e);
3973 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003974 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003975 if (defaultNai != null && defaultNai.network.netId == netId) {
3976 setDefaultDnsSystemProperties(dnses);
3977 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003978 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003979 } else if (flush) {
3980 try {
3981 mNetd.flushNetworkDnsCache(netId);
3982 } catch (Exception e) {
3983 loge("Exception in flushNetworkDnsCache: " + e);
3984 }
3985 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003986 }
3987 }
3988
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003989 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3990 int last = 0;
3991 for (InetAddress dns : dnses) {
3992 ++last;
3993 String key = "net.dns" + last;
3994 String value = dns.getHostAddress();
3995 SystemProperties.set(key, value);
3996 }
3997 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3998 String key = "net.dns" + i;
3999 SystemProperties.set(key, "");
4000 }
4001 mNumDnsEntries = last;
4002 }
4003
Paul Jensen3d194ea2015-06-16 14:27:36 -04004004 /**
4005 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4006 * augmented with any stateful capabilities implied from {@code networkAgent}
4007 * (e.g., validated status and captive portal status).
4008 *
Paul Jensene0988542015-06-25 15:30:08 -04004009 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004010 * @param networkCapabilities the new network capabilities.
4011 */
Paul Jensene0988542015-06-25 15:30:08 -04004012 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004013 // Don't modify caller's NetworkCapabilities.
4014 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004015 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004016 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4017 } else {
4018 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4019 }
Paul Jensene0988542015-06-25 15:30:08 -04004020 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004021 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4022 } else {
4023 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4024 }
Paul Jensene0988542015-06-25 15:30:08 -04004025 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4026 final int oldScore = nai.getCurrentScore();
4027 synchronized (nai) {
4028 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004029 }
Paul Jensene0988542015-06-25 15:30:08 -04004030 rematchAllNetworksAndRequests(nai, oldScore);
4031 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004032 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004033 }
4034
Paul Jensenc8b9a742014-09-30 15:37:41 -04004035 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4036 for (int i = 0; i < nai.networkRequests.size(); i++) {
4037 NetworkRequest nr = nai.networkRequests.valueAt(i);
4038 // Don't send listening requests to factories. b/17393458
4039 if (!isRequest(nr)) continue;
4040 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4041 }
4042 }
4043
Robert Greenwalt7b816022014-04-18 15:25:25 -07004044 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4045 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004046 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004047 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4048 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004049 }
4050 }
4051
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004052 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4053 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004054 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004055 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004056 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4057 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004058 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004059 sendIntent(nri.mPendingIntent, intent);
4060 }
4061 // else not handled
4062 }
4063
4064 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4065 mPendingIntentWakeLock.acquire();
4066 try {
4067 if (DBG) log("Sending " + pendingIntent);
4068 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4069 } catch (PendingIntent.CanceledException e) {
4070 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4071 mPendingIntentWakeLock.release();
4072 releasePendingNetworkRequest(pendingIntent);
4073 }
4074 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4075 }
4076
4077 @Override
4078 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4079 String resultData, Bundle resultExtras) {
4080 if (DBG) log("Finished sending " + pendingIntent);
4081 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004082 // Release with a delay so the receiving client has an opportunity to put in its
4083 // own request.
4084 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004085 }
4086
Robert Greenwalt9258c642014-03-26 16:47:06 -07004087 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004088 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004089 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004090 Bundle bundle = new Bundle();
4091 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4092 new NetworkRequest(nri.request));
4093 Message msg = Message.obtain();
4094 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4095 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4096 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4097 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004098 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004099 case ConnectivityManager.CALLBACK_LOSING: {
4100 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4101 break;
4102 }
4103 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4104 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4105 new NetworkCapabilities(networkAgent.networkCapabilities));
4106 break;
4107 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004108 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004109 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4110 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004111 break;
4112 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004113 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004114 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004115 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004116 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004117 if (VDBG) {
4118 log("sending notification " + notifyTypeToName(notificationType) +
4119 " for " + nri.request);
4120 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004121 nri.messenger.send(msg);
4122 } catch (RemoteException e) {
4123 // may occur naturally in the race of binder death.
4124 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4125 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004126 }
4127
Paul Jensenc8b9a742014-09-30 15:37:41 -04004128 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4129 for (int i = 0; i < nai.networkRequests.size(); i++) {
4130 NetworkRequest nr = nai.networkRequests.valueAt(i);
4131 // Ignore listening requests.
4132 if (!isRequest(nr)) continue;
4133 loge("Dead network still had at least " + nr);
4134 break;
4135 }
4136 nai.asyncChannel.disconnect();
4137 }
4138
Robert Greenwalt7b816022014-04-18 15:25:25 -07004139 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4140 if (oldNetwork == null) {
4141 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4142 return;
4143 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004144 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4145 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004146 }
4147
Paul Jensen27b02b72014-07-14 12:03:33 -04004148 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004149 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004150 setupDataActivityTracking(newNetwork);
4151 try {
4152 mNetd.setDefaultNetId(newNetwork.network.netId);
4153 } catch (Exception e) {
4154 loge("Exception setting default network :" + e);
4155 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004156 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004157 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004158 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004159 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004160 }
4161
Paul Jensen2161a8e2014-09-11 11:00:39 -04004162 // Handles a network appearing or improving its score.
4163 //
4164 // - Evaluates all current NetworkRequests that can be
4165 // satisfied by newNetwork, and reassigns to newNetwork
4166 // any such requests for which newNetwork is the best.
4167 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004168 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004169 // needed. A network is needed if it is the best network for
4170 // one or more NetworkRequests, or if it is a VPN.
4171 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004172 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004173 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004174 //
4175 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4176 // networks that have no chance (i.e. even if validated)
4177 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004178 //
4179 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4180 // it does not remove NetworkRequests that other Networks could better satisfy.
4181 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4182 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4183 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004184 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004185 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004186 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4187 // performed to tear down unvalidated networks that have no chance (i.e. even if
4188 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004189 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004190 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004191 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004192 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004193 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004194 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004195 if (DBG) log("rematching " + newNetwork.name());
4196 // Find and migrate to this Network any NetworkRequests for
4197 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004198 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004199 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004200 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004201 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004202 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4203 if (newNetwork == currentNetwork) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004204 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004205 log("Network " + newNetwork.name() + " was already satisfying" +
4206 " request " + nri.request.requestId + ". No change.");
4207 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004208 keep = true;
4209 continue;
4210 }
4211
4212 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004213 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004214 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004215 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004216 // This is not a request, it's a callback listener.
4217 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004218 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004219 continue;
4220 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004221
Robert Greenwalt7b816022014-04-18 15:25:25 -07004222 // next check if it's better than any current network we're using for
4223 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004224 if (VDBG) {
4225 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004226 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4227 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004228 }
4229 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004230 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004231 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004232 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004233 currentNetwork.networkRequests.remove(nri.request.requestId);
4234 currentNetwork.networkLingered.add(nri.request);
4235 affectedNetworks.add(currentNetwork);
4236 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004237 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004238 }
Paul Jensen573a0352015-01-08 10:49:34 -05004239 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004240 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004241 if (!newNetwork.addRequest(nri.request)) {
4242 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4243 }
4244 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004245 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004246 // Tell NetworkFactories about the new score, so they can stop
4247 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004248 // TODO - this could get expensive if we have alot of requests for this
4249 // network. Think about if there is a way to reduce this. Push
4250 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004251 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004252 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004253 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004254 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004255 }
4256 }
4257 }
4258 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004259 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004260 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004261 if (nai.lingering) {
4262 // Already lingered. Nothing to do. This can only happen if "nai" is in
4263 // "affectedNetworks" twice. The reasoning being that to get added to
4264 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4265 // (i.e. not lingered) so it could have only been lingered by this loop.
4266 // unneeded(nai) will be false and we'll call unlinger() below which would
4267 // be bad, so handle it here.
4268 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004269 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004270 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004271 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004272 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004273 }
4274 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004275 if (keep) {
4276 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004277 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004278 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004279 synchronized (ConnectivityService.this) {
4280 // have a new default network, release the transition wakelock in
4281 // a second if it's held. The second pause is to allow apps
4282 // to reconnect over the new network
4283 if (mNetTransitionWakeLock.isHeld()) {
4284 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4285 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4286 mNetTransitionWakeLockSerialNumber, 0),
4287 1000);
4288 }
4289 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004290 }
4291
4292 // do this after the default net is switched, but
4293 // before LegacyTypeTracker sends legacy broadcasts
Paul Jensen3d911462015-06-12 06:40:24 -04004294 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
Robert Greenwalt152ed372014-12-17 17:19:53 -08004295
4296 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004297 // Maintain the illusion: since the legacy API only
4298 // understands one network at a time, we must pretend
4299 // that the current default network disconnected before
4300 // the new one connected.
4301 if (oldDefaultNetwork != null) {
4302 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004303 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004304 }
Paul Jensene0988542015-06-25 15:30:08 -04004305 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004306 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4307 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004308 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004309
4310 // Notify battery stats service about this network, both the normal
4311 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004312 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004313 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004314 final IBatteryStats bs = BatteryStatsService.getService();
4315 final int type = newNetwork.networkInfo.getType();
4316
4317 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4318 bs.noteNetworkInterfaceType(baseIface, type);
4319 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4320 final String stackedIface = stacked.getInterfaceName();
4321 bs.noteNetworkInterfaceType(stackedIface, type);
4322 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4323 }
4324 } catch (RemoteException ignored) {
4325 }
4326
Robert Greenwalt152ed372014-12-17 17:19:53 -08004327 // This has to happen after the notifyNetworkCallbacks as that tickles each
4328 // ConnectivityManager instance so that legacy requests correctly bind dns
4329 // requests to this network. The legacy users are listening for this bcast
4330 // and will generally do a dns request so they can ensureRouteToHost and if
4331 // they do that before the callbacks happen they'll use the default network.
4332 //
4333 // TODO: Is there still a race here? We send the broadcast
4334 // after sending the callback, but if the app can receive the
4335 // broadcast before the callback, it might still break.
4336 //
4337 // This *does* introduce a race where if the user uses the new api
4338 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4339 // they may get old info. Reverse this after the old startUsing api is removed.
4340 // This is on top of the multiple intent sequencing referenced in the todo above.
4341 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4342 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4343 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4344 // legacy type tracker filters out repeat adds
4345 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4346 }
4347 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004348
4349 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4350 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4351 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4352 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4353 if (newNetwork.isVPN()) {
4354 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4355 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004356 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004357 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4358 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004359 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004360 if (DBG) log("Reaping " + nai.name());
4361 teardownUnneededNetwork(nai);
4362 }
4363 }
4364 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004365 }
4366
Paul Jensen1c7ba022015-06-16 14:27:36 -04004367 /**
4368 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4369 * being disconnected.
4370 * @param changed If only one Network's score or capabilities have been modified since the last
4371 * time this function was called, pass this Network in this argument, otherwise pass
4372 * null.
4373 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4374 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4375 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4376 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4377 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004378 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004379 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004380 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4381 // to avoid the slowness. It is not simply enough to process just "changed", for
4382 // example in the case where "changed"'s score decreases and another network should begin
4383 // satifying a NetworkRequest that "changed" currently satisfies.
4384
4385 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4386 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4387 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004388 if (changed != null && oldScore < changed.getCurrentScore()) {
4389 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004390 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004391 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4392 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4393 // Rematch higher scoring networks first to prevent requests first matching a lower
4394 // scoring network and then a higher scoring network, which could produce multiple
4395 // callbacks and inadvertently unlinger networks.
4396 Arrays.sort(nais);
4397 for (NetworkAgentInfo nai : nais) {
4398 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004399 // Only reap the last time through the loop. Reaping before all rematching
4400 // is complete could incorrectly teardown a network that hasn't yet been
4401 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004402 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004403 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004404 }
4405 }
4406 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004407
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004408 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004409 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004410 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004411 // For now only update icons for default connection.
4412 // TODO: Update WiFi and cellular icons separately. b/17237507
4413 if (!isDefaultNetwork(nai)) return;
4414
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004415 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004416 // Don't repeat publish.
4417 if (newInetCondition == mDefaultInetConditionPublished) return;
4418
4419 mDefaultInetConditionPublished = newInetCondition;
4420 sendInetConditionBroadcast(nai.networkInfo);
4421 }
4422
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004423 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4424 if (mLockdownTracker != null) {
4425 if (nai != null && nai.isVPN()) {
4426 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4427 } else {
4428 mLockdownTracker.onNetworkInfoChanged();
4429 }
4430 }
4431 }
4432
Robert Greenwalt7b816022014-04-18 15:25:25 -07004433 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4434 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004435 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004436 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004437 synchronized (networkAgent) {
4438 oldInfo = networkAgent.networkInfo;
4439 networkAgent.networkInfo = newInfo;
4440 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004441 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004442
4443 if (oldInfo != null && oldInfo.getState() == state) {
4444 if (VDBG) log("ignoring duplicate network state non-change");
4445 return;
4446 }
4447 if (DBG) {
4448 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4449 (oldInfo == null ? "null" : oldInfo.getState()) +
4450 " to " + state);
4451 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004452
Paul Jenseneec75412014-08-04 12:21:19 -04004453 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004454 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004455 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004456 if (networkAgent.isVPN()) {
4457 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004458 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4459 (networkAgent.networkMisc == null ||
4460 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004461 } else {
4462 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4463 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004464 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004465 loge("Error creating network " + networkAgent.network.netId + ": "
4466 + e.getMessage());
4467 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004468 }
Paul Jenseneec75412014-08-04 12:21:19 -04004469 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004470 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004471 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004472
Paul Jensenca8f16a2014-05-09 12:47:55 -04004473 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004474 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004475
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004476 if (networkAgent.isVPN()) {
4477 // Temporarily disable the default proxy (not global).
4478 synchronized (mProxyLock) {
4479 if (!mDefaultProxyDisabled) {
4480 mDefaultProxyDisabled = true;
4481 if (mGlobalProxy == null && mDefaultProxy != null) {
4482 sendProxyBroadcast(null);
4483 }
4484 }
4485 }
4486 // TODO: support proxy per network.
4487 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004488
Paul Jensen2161a8e2014-09-11 11:00:39 -04004489 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004490 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004491
4492 // This has to happen after matching the requests, because callbacks are just requests.
4493 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004494 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004495 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004496 if (networkAgent.isVPN()) {
4497 synchronized (mProxyLock) {
4498 if (mDefaultProxyDisabled) {
4499 mDefaultProxyDisabled = false;
4500 if (mGlobalProxy == null && mDefaultProxy != null) {
4501 sendProxyBroadcast(mDefaultProxy);
4502 }
4503 }
4504 }
4505 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004506 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4507 state == NetworkInfo.State.SUSPENDED) {
4508 // going into or coming out of SUSPEND: rescore and notify
4509 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004510 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004511 }
4512 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4513 ConnectivityManager.CALLBACK_SUSPENDED :
4514 ConnectivityManager.CALLBACK_RESUMED));
4515 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004516 }
4517 }
4518
Robert Greenwaltac96c522014-06-03 16:43:57 -07004519 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4520 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004521 if (score < 0) {
4522 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4523 "). Bumping score to min of 0");
4524 score = 0;
4525 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004526
Paul Jensen2161a8e2014-09-11 11:00:39 -04004527 final int oldScore = nai.getCurrentScore();
4528 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004529
Paul Jensen85cf78e2015-06-25 13:25:07 -04004530 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004531
Paul Jensenc8b9a742014-09-30 15:37:41 -04004532 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004533 }
4534
Robert Greenwalt9258c642014-03-26 16:47:06 -07004535 // notify only this one new request of the current state
4536 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4537 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4538 // TODO - read state from monitor to decide what to send.
4539// if (nai.networkMonitor.isLingering()) {
4540// notifyType = NetworkCallbacks.LOSING;
4541// } else if (nai.networkMonitor.isEvaluating()) {
4542// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4543// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004544 if (nri.mPendingIntent == null) {
4545 callCallbackForRequest(nri, nai, notifyType);
4546 } else {
4547 sendPendingIntentForRequest(nri, nai, notifyType);
4548 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004549 }
4550
Robert Greenwalt8d482522015-06-24 13:23:42 -07004551 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004552 // The NetworkInfo we actually send out has no bearing on the real
4553 // state of affairs. For example, if the default connection is mobile,
4554 // and a request for HIPRI has just gone away, we need to pretend that
4555 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4556 // the state to DISCONNECTED, even though the network is of type MOBILE
4557 // and is still connected.
4558 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4559 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004560 if (state != DetailedState.DISCONNECTED) {
4561 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004562 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004563 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004564 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004565 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4566 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4567 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4568 if (info.isFailover()) {
4569 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4570 nai.networkInfo.setFailover(false);
4571 }
4572 if (info.getReason() != null) {
4573 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4574 }
4575 if (info.getExtraInfo() != null) {
4576 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4577 }
4578 NetworkAgentInfo newDefaultAgent = null;
4579 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004580 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004581 if (newDefaultAgent != null) {
4582 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4583 newDefaultAgent.networkInfo);
4584 } else {
4585 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4586 }
4587 }
4588 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4589 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004590 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004591 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004592 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004593 }
4594 }
4595 }
4596
Robert Greenwalt7b816022014-04-18 15:25:25 -07004597 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004598 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004599 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004600 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4601 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4602 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004603 if (nri.mPendingIntent == null) {
4604 callCallbackForRequest(nri, networkAgent, notifyType);
4605 } else {
4606 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4607 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004608 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004609 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004610
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004611 private String notifyTypeToName(int notifyType) {
4612 switch (notifyType) {
4613 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4614 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4615 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4616 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4617 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4618 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4619 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4620 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4621 }
4622 return "UNKNOWN";
4623 }
4624
Jeff Sharkey69736342014-12-08 14:50:12 -08004625 /**
4626 * Notify other system services that set of active ifaces has changed.
4627 */
4628 private void notifyIfacesChanged() {
4629 try {
4630 mStatsService.forceUpdateIfaces();
4631 } catch (Exception ignored) {
4632 }
4633 }
4634
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004635 @Override
4636 public boolean addVpnAddress(String address, int prefixLength) {
4637 throwIfLockdownEnabled();
4638 int user = UserHandle.getUserId(Binder.getCallingUid());
4639 synchronized (mVpns) {
4640 return mVpns.get(user).addAddress(address, prefixLength);
4641 }
4642 }
4643
4644 @Override
4645 public boolean removeVpnAddress(String address, int prefixLength) {
4646 throwIfLockdownEnabled();
4647 int user = UserHandle.getUserId(Binder.getCallingUid());
4648 synchronized (mVpns) {
4649 return mVpns.get(user).removeAddress(address, prefixLength);
4650 }
4651 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004652
4653 @Override
4654 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4655 throwIfLockdownEnabled();
4656 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004657 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004658 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004659 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004660 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004661 if (success) {
4662 notifyIfacesChanged();
4663 }
4664 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004665 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004666
4667 @Override
4668 public void factoryReset() {
4669 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004670
4671 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4672 return;
4673 }
4674
Robin Lee3b3dd942015-05-12 18:14:58 +01004675 final int userId = UserHandle.getCallingUserId();
4676
Stuart Scottf1fb3972015-04-02 18:00:02 -07004677 // Turn airplane mode off
4678 setAirplaneMode(false);
4679
Stuart Scotte3e314d2015-04-20 14:07:45 -07004680 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4681 // Untether
4682 for (String tether : getTetheredIfaces()) {
4683 untether(tether);
4684 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004685 }
4686
Stuart Scotte3e314d2015-04-20 14:07:45 -07004687 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4688 // Turn VPN off
4689 VpnConfig vpnConfig = getVpnConfig(userId);
4690 if (vpnConfig != null) {
4691 if (vpnConfig.legacy) {
4692 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4693 } else {
4694 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4695 // in the future without user intervention.
4696 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004697
Stuart Scotte3e314d2015-04-20 14:07:45 -07004698 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4699 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004700 }
4701 }
4702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703}