blob: 9b1e26a26b86a8552425fa74b3dc1ed021f22df5 [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];
566 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
567 if (isFirst || isDefault) {
568 maybeLogBroadcast(nai, state, type, isDefault);
569 sendLegacyNetworkBroadcast(nai, state, type);
570 }
571 }
572 }
573
Lorenzo Colittia793a672014-07-31 23:20:17 +0900574 private String naiToString(NetworkAgentInfo nai) {
575 String name = (nai != null) ? nai.name() : "null";
576 String state = (nai.networkInfo != null) ?
577 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
578 "???/???";
579 return name + " " + state;
580 }
581
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700582 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900583 pw.println("mLegacyTypeTracker:");
584 pw.increaseIndent();
585 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700586 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900587 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700588 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900589 pw.println();
590 pw.println("Current state:");
591 pw.increaseIndent();
592 for (int type = 0; type < mTypeLists.length; type++) {
593 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
594 for (NetworkAgentInfo nai : mTypeLists[type]) {
595 pw.println(type + " " + naiToString(nai));
596 }
597 }
598 pw.decreaseIndent();
599 pw.decreaseIndent();
600 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700601 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900602
603 // This class needs its own log method because it has a different TAG.
604 private void log(String s) {
605 Slog.d(TAG, s);
606 }
607
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700608 }
609 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
610
Jeff Sharkey899223b2012-08-04 15:24:58 -0700611 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700612 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800613 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800614
Erik Klineda4bfa82015-04-30 12:58:40 +0900615 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900616 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
617 new Binder(), NetworkRequestInfo.REQUEST);
618 mNetworkRequests.put(mDefaultRequest, defaultNRI);
619 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900620
621 mDefaultMobileDataRequest = createInternetRequestForTransport(
622 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700623
Wink Savillebb08caf2010-09-02 19:23:52 -0700624 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
625 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700626 mHandler = new InternalHandler(handlerThread.getLooper());
627 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700628
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800629 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800630 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
631 String id = Settings.Secure.getString(context.getContentResolver(),
632 Settings.Secure.ANDROID_ID);
633 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700634 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800635 SystemProperties.set("net.hostname", name);
636 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800637 }
638
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700639 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700640 String dns = Settings.Global.getString(context.getContentResolver(),
641 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700642 if (dns == null || dns.length() == 0) {
643 dns = context.getResources().getString(
644 com.android.internal.R.string.config_default_dns_server);
645 }
646 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800647 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
648 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800649 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700650 }
651
Jeremy Joslin79294842014-12-03 17:15:28 -0800652 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
653 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
654
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700655 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700656 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800657 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700658 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700659 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700660 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700661
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700662 try {
663 mPolicyManager.registerListener(mPolicyListener);
664 } catch (RemoteException e) {
665 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700666 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700667 }
668
669 final PowerManager powerManager = (PowerManager) context.getSystemService(
670 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700671 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
672 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
673 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800674 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700675
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700676 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700677
Wink Saville51f456f2013-04-23 14:26:51 -0700678 // TODO: What is the "correct" way to do determine if this is a wifi only device?
679 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
680 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700681 String[] naStrings = context.getResources().getStringArray(
682 com.android.internal.R.array.networkAttributes);
683 for (String naString : naStrings) {
684 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700685 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700686 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700687 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800688 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700689 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700690 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700691 }
Wink Saville51f456f2013-04-23 14:26:51 -0700692 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
693 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
694 n.type);
695 continue;
696 }
Wink Saville975c8482011-04-07 14:23:45 -0700697 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800698 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700699 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700700 continue;
701 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700702 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700703
Wink Saville975c8482011-04-07 14:23:45 -0700704 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700705 mNetworksDefined++;
706 } catch(Exception e) {
707 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700708 }
709 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700710
711 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
712 if (mNetConfigs[TYPE_VPN] == null) {
713 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
714 // don't need to add TYPE_VPN to mNetConfigs.
715 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
716 mNetworksDefined++; // used only in the log() statement below.
717 }
718
Wink Saville5e56bc52013-07-29 15:00:57 -0700719 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700720
Robert Greenwalt50393202011-06-21 17:26:14 -0700721 mProtectedNetworks = new ArrayList<Integer>();
722 int[] protectedNetworks = context.getResources().getIntArray(
723 com.android.internal.R.array.config_protectedNetworks);
724 for (int p : protectedNetworks) {
725 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
726 mProtectedNetworks.add(p);
727 } else {
728 if (DBG) loge("Ignoring protectedNetwork " + p);
729 }
730 }
731
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700732 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
733 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700734
Robert Greenwaltfab501672014-07-23 11:44:01 -0700735 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800736
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700737 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
738
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700739 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700740 IntentFilter intentFilter = new IntentFilter();
741 intentFilter.addAction(Intent.ACTION_USER_STARTING);
742 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
743 mContext.registerReceiverAsUser(
744 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900745
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700746 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700747 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700748 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700749 } catch (RemoteException e) {
750 loge("Error registering observer :" + e);
751 }
752
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700753 if (DBG) {
754 mInetLog = new ArrayList();
755 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700756
Erik Klineda4bfa82015-04-30 12:58:40 +0900757 mSettingsObserver = new SettingsObserver(mContext, mHandler);
758 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800759
John Spurlockbf991a82013-06-24 14:20:23 -0400760 mDataConnectionStats = new DataConnectionStats(mContext);
761 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400762
Jason Monkdecd2952013-10-10 14:02:51 -0400763 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700764
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400765 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700767
Erik Klineda4bfa82015-04-30 12:58:40 +0900768 private NetworkRequest createInternetRequestForTransport(int transportType) {
769 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900770 netCap.addCapability(NET_CAPABILITY_INTERNET);
771 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900772 if (transportType > -1) {
773 netCap.addTransportType(transportType);
774 }
775 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
776 }
777
778 private void handleMobileDataAlwaysOn() {
779 final boolean enable = (Settings.Global.getInt(
780 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
781 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
782 if (enable == isEnabled) {
783 return; // Nothing to do.
784 }
785
786 if (enable) {
787 handleRegisterNetworkRequest(new NetworkRequestInfo(
788 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
789 } else {
790 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
791 }
792 }
793
794 private void registerSettingsCallbacks() {
795 // Watch for global HTTP proxy changes.
796 mSettingsObserver.observe(
797 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
798 EVENT_APPLY_GLOBAL_HTTP_PROXY);
799
800 // Watch for whether or not to keep mobile data always on.
801 mSettingsObserver.observe(
802 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
803 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
804 }
805
Robert Greenwalt34524f02014-05-18 16:22:10 -0700806 private synchronized int nextNetworkRequestId() {
807 return mNextNetworkRequestId++;
808 }
809
Paul Jensen67b0b072015-06-10 11:22:17 -0400810 @VisibleForTesting
811 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400812 synchronized (mNetworkForNetId) {
813 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
814 int netId = mNextNetId;
815 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
816 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500817 if (!mNetIdInUse.get(netId)) {
818 mNetIdInUse.put(netId, true);
819 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400820 }
821 }
822 }
823 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700824 }
825
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800826 private NetworkState getFilteredNetworkState(int networkType, int uid) {
827 NetworkInfo info = null;
828 LinkProperties lp = null;
829 NetworkCapabilities nc = null;
830 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800831 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800832
833 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
834 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
835 if (nai != null) {
836 synchronized (nai) {
837 info = new NetworkInfo(nai.networkInfo);
838 lp = new LinkProperties(nai.linkProperties);
839 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400840 // Network objects are outwardly immutable so there is no point to duplicating.
841 // Duplicating also precludes sharing socket factories and connection pools.
842 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800843 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800844 }
845 info.setType(networkType);
846 } else {
847 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
848 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
849 info.setIsAvailable(true);
850 lp = new LinkProperties();
851 nc = new NetworkCapabilities();
852 network = null;
853 }
854 info = getFilteredNetworkInfo(info, lp, uid);
855 }
856
Jeff Sharkey32566012014-12-02 18:30:14 -0800857 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400858 }
859
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800860 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
861 if (network == null) {
862 return null;
863 }
864 synchronized (mNetworkForNetId) {
865 return mNetworkForNetId.get(network.netId);
866 }
867 };
868
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900869 private Network[] getVpnUnderlyingNetworks(int uid) {
870 if (!mLockdownEnabled) {
871 int user = UserHandle.getUserId(uid);
872 synchronized (mVpns) {
873 Vpn vpn = mVpns.get(user);
874 if (vpn != null && vpn.appliesToUid(uid)) {
875 return vpn.getUnderlyingNetworks();
876 }
877 }
878 }
879 return null;
880 }
881
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800882 private NetworkState getUnfilteredActiveNetworkState(int uid) {
883 NetworkInfo info = null;
884 LinkProperties lp = null;
885 NetworkCapabilities nc = null;
886 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800887 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800888
Paul Jensen85cf78e2015-06-25 13:25:07 -0400889 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800890
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900891 final Network[] networks = getVpnUnderlyingNetworks(uid);
892 if (networks != null) {
893 // getUnderlyingNetworks() returns:
894 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
895 // empty array => the VPN explicitly said "no default network".
896 // non-empty array => the VPN specified one or more default networks; we use the
897 // first one.
898 if (networks.length > 0) {
899 nai = getNetworkAgentInfoForNetwork(networks[0]);
900 } else {
901 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800902 }
903 }
904
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800905 if (nai != null) {
906 synchronized (nai) {
907 info = new NetworkInfo(nai.networkInfo);
908 lp = new LinkProperties(nai.linkProperties);
909 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400910 // Network objects are outwardly immutable so there is no point to duplicating.
911 // Duplicating also precludes sharing socket factories and connection pools.
912 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800913 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800914 }
915 }
916
Jeff Sharkey32566012014-12-02 18:30:14 -0800917 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400918 }
919
920 /**
921 * Check if UID should be blocked from using the network with the given LinkProperties.
922 */
923 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700924 final boolean networkCostly;
925 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700926
Robert Greenwalt12e67352014-05-13 21:41:06 -0700927 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700928 synchronized (mRulesLock) {
929 networkCostly = mMeteredIfaces.contains(iface);
930 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700931 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700932
Amith Yamasani15e472352015-04-24 19:06:07 -0700933 if ((uidRules & RULE_REJECT_ALL) != 0
934 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700935 return true;
936 }
937
938 // no restrictive rules; network is visible
939 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700940 }
941
942 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700943 * Return a filtered {@link NetworkInfo}, potentially marked
944 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800945 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700946 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800947 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
948 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400949 // network is blocked; clone and override state
950 info = new NetworkInfo(info);
951 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900952 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900953 log("returning Blocked NetworkInfo for ifname=" +
954 lp.getInterfaceName() + ", uid=" + uid);
955 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700956 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800957 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700958 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900959 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700960 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700961 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700962 }
963
964 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 * Return NetworkInfo for the active (i.e., connected) network interface.
966 * It is assumed that at most one network is active at a time. If more
967 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700968 * @return the info for the active network, or {@code null} if none is
969 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700971 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700973 enforceAccessPermission();
974 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800975 NetworkState state = getUnfilteredActiveNetworkState(uid);
976 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 }
978
Paul Jensen31a94f42015-02-13 14:18:39 -0500979 @Override
980 public Network getActiveNetwork() {
981 enforceAccessPermission();
982 final int uid = Binder.getCallingUid();
983 final int user = UserHandle.getUserId(uid);
984 int vpnNetId = NETID_UNSET;
985 synchronized (mVpns) {
986 final Vpn vpn = mVpns.get(user);
987 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
988 }
989 NetworkAgentInfo nai;
990 if (vpnNetId != NETID_UNSET) {
991 synchronized (mNetworkForNetId) {
992 nai = mNetworkForNetId.get(vpnNetId);
993 }
994 if (nai != null) return nai.network;
995 }
996 nai = getDefaultNetwork();
997 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
998 return nai != null ? nai.network : null;
999 }
1000
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001001 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1002 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001003 final int uid = Binder.getCallingUid();
1004 NetworkState state = getUnfilteredActiveNetworkState(uid);
1005 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001006 }
1007
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001008 @Override
1009 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1010 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001011 NetworkState state = getUnfilteredActiveNetworkState(uid);
1012 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001013 }
1014
1015 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 public NetworkInfo getNetworkInfo(int networkType) {
1017 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001018 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001019 if (getVpnUnderlyingNetworks(uid) != null) {
1020 // A VPN is active, so we may need to return one of its underlying networks. This
1021 // information is not available in LegacyTypeTracker, so we have to get it from
1022 // getUnfilteredActiveNetworkState.
1023 NetworkState state = getUnfilteredActiveNetworkState(uid);
1024 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1025 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1026 }
1027 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001028 NetworkState state = getFilteredNetworkState(networkType, uid);
1029 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 }
1031
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001032 @Override
1033 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1034 enforceAccessPermission();
1035 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001036 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001037 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1038 if (nai != null) {
1039 synchronized (nai) {
1040 info = new NetworkInfo(nai.networkInfo);
1041 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001042 }
1043 }
1044 return info;
1045 }
1046
1047 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 public NetworkInfo[] getAllNetworkInfo() {
1049 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001050 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001051 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1052 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001053 NetworkInfo info = getNetworkInfo(networkType);
1054 if (info != null) {
1055 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001058 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
1060
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001061 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001062 public Network getNetworkForType(int networkType) {
1063 enforceAccessPermission();
1064 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001065 NetworkState state = getFilteredNetworkState(networkType, uid);
1066 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1067 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001068 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001069 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001070 }
1071
1072 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001073 public Network[] getAllNetworks() {
1074 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001075 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001076 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001077 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001078 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001079 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001080 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001081 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001082 }
1083
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001084 @Override
1085 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1086 // The basic principle is: if an app's traffic could possibly go over a
1087 // network, without the app doing anything multinetwork-specific,
1088 // (hence, by "default"), then include that network's capabilities in
1089 // the array.
1090 //
1091 // In the normal case, app traffic only goes over the system's default
1092 // network connection, so that's the only network returned.
1093 //
1094 // With a VPN in force, some app traffic may go into the VPN, and thus
1095 // over whatever underlying networks the VPN specifies, while other app
1096 // traffic may go over the system default network (e.g.: a split-tunnel
1097 // VPN, or an app disallowed by the VPN), so the set of networks
1098 // returned includes the VPN's underlying networks and the system
1099 // default.
1100 enforceAccessPermission();
1101
1102 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1103
1104 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001105 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001106 if (nc != null) {
1107 result.put(nai.network, nc);
1108 }
1109
1110 if (!mLockdownEnabled) {
1111 synchronized (mVpns) {
1112 Vpn vpn = mVpns.get(userId);
1113 if (vpn != null) {
1114 Network[] networks = vpn.getUnderlyingNetworks();
1115 if (networks != null) {
1116 for (Network network : networks) {
1117 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001118 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001119 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001120 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001121 }
1122 }
1123 }
1124 }
1125 }
1126 }
1127
1128 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1129 out = result.values().toArray(out);
1130 return out;
1131 }
1132
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001133 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001134 public boolean isNetworkSupported(int networkType) {
1135 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001136 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001137 }
1138
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001139 /**
1140 * Return LinkProperties for the active (i.e., connected) default
1141 * network interface. It is assumed that at most one default network
1142 * is active at a time. If more than one is active, it is indeterminate
1143 * which will be returned.
1144 * @return the ip properties for the active network, or {@code null} if
1145 * none is active
1146 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001147 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001148 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001149 enforceAccessPermission();
1150 final int uid = Binder.getCallingUid();
1151 NetworkState state = getUnfilteredActiveNetworkState(uid);
1152 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001153 }
1154
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001155 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001156 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001157 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001158 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1159 if (nai != null) {
1160 synchronized (nai) {
1161 return new LinkProperties(nai.linkProperties);
1162 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001163 }
1164 return null;
1165 }
1166
Robert Greenwalt12e67352014-05-13 21:41:06 -07001167 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001168 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001169 public LinkProperties getLinkProperties(Network network) {
1170 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001171 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001172 if (nai != null) {
1173 synchronized (nai) {
1174 return new LinkProperties(nai.linkProperties);
1175 }
1176 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001177 return null;
1178 }
1179
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001180 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001181 if (nai != null) {
1182 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001183 if (nai.networkCapabilities != null) {
1184 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001185 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001186 }
1187 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001188 return null;
1189 }
1190
1191 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001192 public NetworkCapabilities getNetworkCapabilities(Network network) {
1193 enforceAccessPermission();
1194 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1195 }
1196
1197 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001198 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001199 // Require internal since we're handing out IMSI details
1200 enforceConnectivityInternalPermission();
1201
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001202 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001203 for (Network network : getAllNetworks()) {
1204 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1205 if (nai != null) {
1206 synchronized (nai) {
1207 final String subscriberId = (nai.networkMisc != null)
1208 ? nai.networkMisc.subscriberId : null;
1209 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1210 nai.networkCapabilities, network, subscriberId, null));
1211 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001212 }
1213 }
1214 return result.toArray(new NetworkState[result.size()]);
1215 }
1216
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001217 @Override
1218 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1219 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001220 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001221 final long token = Binder.clearCallingIdentity();
1222 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001223 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1224 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001225 try {
1226 return mPolicyManager.getNetworkQuotaInfo(state);
1227 } catch (RemoteException e) {
1228 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001229 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001230 return null;
1231 } finally {
1232 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001233 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001234 }
1235
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001236 @Override
1237 public boolean isActiveNetworkMetered() {
1238 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001240 final long token = Binder.clearCallingIdentity();
1241 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001242 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001243 } finally {
1244 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001245 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001246 }
1247
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001248 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1249 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1250 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001251 try {
1252 return mPolicyManager.isNetworkMetered(state);
1253 } catch (RemoteException e) {
1254 }
1255 }
1256 return false;
1257 }
1258
Jeff Sharkey216c1812012-08-05 14:29:23 -07001259 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1260 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001261 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001262 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001263 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001264 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001265 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001266
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001267 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 * Ensure that a network route exists to deliver traffic to the specified
1269 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001270 * @param networkType the type of the network over which traffic to the
1271 * specified host is to be routed
1272 * @param hostAddress the IP address of the host to which the route is
1273 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 * @return {@code true} on success, {@code false} on failure
1275 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001276 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001278 if (mProtectedNetworks.contains(networkType)) {
1279 enforceConnectivityInternalPermission();
1280 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001281
Chad Brubakerc0234532014-02-14 13:24:29 -08001282 InetAddress addr;
1283 try {
1284 addr = InetAddress.getByAddress(hostAddress);
1285 } catch (UnknownHostException e) {
1286 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1287 return false;
1288 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001291 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 return false;
1293 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001294
1295 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1296 if (nai == null) {
1297 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1298 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1299 } else {
1300 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1301 }
1302 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001303 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001304
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001305 DetailedState netState;
1306 synchronized (nai) {
1307 netState = nai.networkInfo.getDetailedState();
1308 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001309
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001310 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001311 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001312 log("requestRouteToHostAddress on down network "
1313 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001314 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001315 }
1316 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001318
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001319 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001320 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001321 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001322 LinkProperties lp;
1323 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001324 synchronized (nai) {
1325 lp = nai.linkProperties;
1326 netId = nai.network.netId;
1327 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001328 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001329 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1330 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001331 } finally {
1332 Binder.restoreCallingIdentity(token);
1333 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001334 }
1335
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001336 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001337 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001338 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001339 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001340 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001341 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001342 if (bestRoute.getGateway().equals(addr)) {
1343 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001344 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001345 } else {
1346 // if we will connect to this through another route, add a direct route
1347 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001348 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001349 }
1350 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001351 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001352 try {
1353 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1354 } catch (Exception e) {
1355 // never crash - catch them all
1356 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001357 return false;
1358 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001359 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 }
1361
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001362 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1363 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001364 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001365 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001366 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001367 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001368 }
1369
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001370 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001371 // skip update when we've already applied rules
1372 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1373 if (oldRules == uidRules) return;
1374
1375 mUidRules.put(uid, uidRules);
1376 }
1377
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001378 // TODO: notify UID when it has requested targeted updates
1379 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001380
1381 @Override
1382 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001383 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001384 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001385 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001386 }
1387
1388 synchronized (mRulesLock) {
1389 mMeteredIfaces.clear();
1390 for (String iface : meteredIfaces) {
1391 mMeteredIfaces.add(iface);
1392 }
1393 }
1394 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001395
1396 @Override
1397 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1398 // caller is NPMS, since we only register with them
1399 if (LOGD_RULES) {
1400 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1401 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001402 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001403 };
1404
Robin Lee3b3dd942015-05-12 18:14:58 +01001405 /**
1406 * Require that the caller is either in the same user or has appropriate permission to interact
1407 * across users.
1408 *
1409 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1410 */
1411 private void enforceCrossUserPermission(int userId) {
1412 if (userId == UserHandle.getCallingUserId()) {
1413 // Not a cross-user call.
1414 return;
1415 }
1416 mContext.enforceCallingOrSelfPermission(
1417 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1418 "ConnectivityService");
1419 }
1420
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001421 private void enforceInternetPermission() {
1422 mContext.enforceCallingOrSelfPermission(
1423 android.Manifest.permission.INTERNET,
1424 "ConnectivityService");
1425 }
1426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001428 mContext.enforceCallingOrSelfPermission(
1429 android.Manifest.permission.ACCESS_NETWORK_STATE,
1430 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 }
1432
1433 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001434 mContext.enforceCallingOrSelfPermission(
1435 android.Manifest.permission.CHANGE_NETWORK_STATE,
1436 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 }
1438
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001439 private void enforceTetherAccessPermission() {
1440 mContext.enforceCallingOrSelfPermission(
1441 android.Manifest.permission.ACCESS_NETWORK_STATE,
1442 "ConnectivityService");
1443 }
1444
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001445 private void enforceConnectivityInternalPermission() {
1446 mContext.enforceCallingOrSelfPermission(
1447 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1448 "ConnectivityService");
1449 }
1450
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001451 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001452 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001453 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001454 }
1455
1456 private void sendInetConditionBroadcast(NetworkInfo info) {
1457 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1458 }
1459
Wink Saville628b0852011-08-04 15:01:58 -07001460 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001461 if (mLockdownTracker != null) {
1462 info = mLockdownTracker.augmentNetworkInfo(info);
1463 }
1464
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001465 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001466 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001467 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 if (info.isFailover()) {
1469 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1470 info.setFailover(false);
1471 }
1472 if (info.getReason() != null) {
1473 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1474 }
1475 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001476 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1477 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001479 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001480 return intent;
1481 }
1482
1483 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1484 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1485 }
1486
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001487 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001488 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1489 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1490 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001491 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001492 final long ident = Binder.clearCallingIdentity();
1493 try {
1494 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1495 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1496 } finally {
1497 Binder.restoreCallingIdentity(ident);
1498 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001499 }
1500
Mike Lockwood0f79b542009-08-14 14:18:49 -04001501 private void sendStickyBroadcast(Intent intent) {
1502 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001503 if (!mSystemReady) {
1504 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001505 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001506 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001507 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001508 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001509 }
1510
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001511 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001512 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1513 final IBatteryStats bs = BatteryStatsService.getService();
1514 try {
1515 NetworkInfo ni = intent.getParcelableExtra(
1516 ConnectivityManager.EXTRA_NETWORK_INFO);
1517 bs.noteConnectivityChanged(intent.getIntExtra(
1518 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1519 ni != null ? ni.getState().toString() : "?");
1520 } catch (RemoteException e) {
1521 }
1522 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001523 try {
1524 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1525 } finally {
1526 Binder.restoreCallingIdentity(ident);
1527 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001528 }
1529 }
1530
1531 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001532 loadGlobalProxy();
1533
Mike Lockwood0f79b542009-08-14 14:18:49 -04001534 synchronized(this) {
1535 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001536 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001537 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001538 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001539 }
1540 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001541 // load the global proxy at startup
1542 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001543
1544 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1545 // for user to unlock device.
1546 if (!updateLockdownVpn()) {
1547 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1548 mContext.registerReceiver(mUserPresentReceiver, filter);
1549 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001550
Erik Klineda4bfa82015-04-30 12:58:40 +09001551 // Configure whether mobile data is always on.
1552 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1553
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001554 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001555
1556 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 }
1558
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001559 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1560 @Override
1561 public void onReceive(Context context, Intent intent) {
1562 // Try creating lockdown tracker, since user present usually means
1563 // unlocked keystore.
1564 if (updateLockdownVpn()) {
1565 mContext.unregisterReceiver(this);
1566 }
1567 }
1568 };
1569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001571 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001572 *
1573 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001574 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001575 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001576 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1577 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001578
1579 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001580 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001581
Robert Greenwalt7b816022014-04-18 15:25:25 -07001582 if (networkAgent.networkCapabilities.hasTransport(
1583 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001584 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1585 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001586 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001587 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001588 } else if (networkAgent.networkCapabilities.hasTransport(
1589 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001590 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1591 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001592 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001593 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001594 } else {
1595 // do not track any other networks
1596 timeout = 0;
1597 }
1598
Robert Greenwalt7b816022014-04-18 15:25:25 -07001599 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001600 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001601 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001602 } catch (Exception e) {
1603 // You shall not crash!
1604 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001605 }
1606 }
1607 }
1608
1609 /**
1610 * Remove data activity tracking when network disconnects.
1611 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001612 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1613 final String iface = networkAgent.linkProperties.getInterfaceName();
1614 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001615
Robert Greenwalt7b816022014-04-18 15:25:25 -07001616 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1617 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001618 try {
1619 // the call fails silently if no idletimer setup for this interface
1620 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001621 } catch (Exception e) {
1622 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001623 }
1624 }
1625 }
1626
1627 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001628 * Reads the network specific MTU size from reources.
1629 * and set it on it's iface.
1630 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001631 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1632 final String iface = newLp.getInterfaceName();
1633 final int mtu = newLp.getMtu();
1634 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1635 if (VDBG) log("identical MTU - not setting");
1636 return;
1637 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001638
Robert Greenwalt43074032014-08-15 17:53:05 -07001639 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001640 loge("Unexpected mtu value: " + mtu + ", " + iface);
1641 return;
1642 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001643
w1997615afd812014-08-05 15:18:11 -07001644 // Cannot set MTU without interface name
1645 if (TextUtils.isEmpty(iface)) {
1646 loge("Setting MTU size with null iface.");
1647 return;
1648 }
1649
Robert Greenwalt7b816022014-04-18 15:25:25 -07001650 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001651 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001652 mNetd.setMtu(iface, mtu);
1653 } catch (Exception e) {
1654 Slog.e(TAG, "exception in setMtu()" + e);
1655 }
1656 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001657
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001658 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001659 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1660
1661 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001662 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001663 protected int getDefaultTcpRwnd() {
1664 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1665 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001666
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001667 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1668 if (isDefaultNetwork(nai) == false) {
1669 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001670 }
1671
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001672 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1673 String[] values = null;
1674 if (tcpBufferSizes != null) {
1675 values = tcpBufferSizes.split(",");
1676 }
1677
1678 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001679 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001680 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1681 values = tcpBufferSizes.split(",");
1682 }
1683
1684 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1685
1686 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001687 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001688
1689 final String prefix = "/sys/kernel/ipv4/tcp_";
1690 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1691 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1692 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1693 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1694 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1695 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1696 mCurrentTcpBufferSizes = tcpBufferSizes;
1697 } catch (IOException e) {
1698 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001699 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001700
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001701 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001702 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001703 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1704 if (rwndValue != 0) {
1705 SystemProperties.set(sysctlKey, rwndValue.toString());
1706 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001707 }
1708
Mattias Falk8b47b362011-08-23 14:15:13 +02001709 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001710 /*
1711 * Tell the VMs to toss their DNS caches
1712 */
1713 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1714 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001715 /*
1716 * Connectivity events can happen before boot has completed ...
1717 */
1718 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001719 final long ident = Binder.clearCallingIdentity();
1720 try {
1721 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1722 } finally {
1723 Binder.restoreCallingIdentity(ident);
1724 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001725 }
1726
Robert Greenwalt562cc542014-05-15 18:07:26 -07001727 @Override
1728 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001729 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1730 NETWORK_RESTORE_DELAY_PROP_NAME);
1731 if(restoreDefaultNetworkDelayStr != null &&
1732 restoreDefaultNetworkDelayStr.length() != 0) {
1733 try {
1734 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1735 } catch (NumberFormatException e) {
1736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001738 // if the system property isn't set, use the value for the apn type
1739 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1740
1741 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1742 (mNetConfigs[networkType] != null)) {
1743 ret = mNetConfigs[networkType].restoreTime;
1744 }
1745 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 }
1747
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001748 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001749 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001750 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001751 }
1752 return false;
1753 }
1754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001756 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1757 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001758 if (mContext.checkCallingOrSelfPermission(
1759 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001761 pw.println("Permission Denial: can't dump ConnectivityService " +
1762 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1763 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 return;
1765 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001766
Erik Kline379747a2015-06-05 17:47:34 +09001767 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001768 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001769 final long DIAG_TIME_MS = 5000;
1770 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1771 // Start gathering diagnostic information.
1772 netDiags.add(new NetworkDiagnostics(
1773 nai.network,
1774 new LinkProperties(nai.linkProperties),
1775 DIAG_TIME_MS));
1776 }
1777
1778 for (NetworkDiagnostics netDiag : netDiags) {
1779 pw.println();
1780 netDiag.waitForMeasurements();
1781 netDiag.dump(pw);
1782 }
1783
1784 return;
1785 }
1786
Lorenzo Colittie3805462015-06-03 11:18:24 +09001787 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001788 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001789 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001790 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001791 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001792 pw.println();
1793
Paul Jensen85cf78e2015-06-25 13:25:07 -04001794 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001795 pw.print("Active default network: ");
1796 if (defaultNai == null) {
1797 pw.println("none");
1798 } else {
1799 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001801 pw.println();
1802
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001803 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001804 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001805 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1806 pw.println(nai.toString());
1807 pw.increaseIndent();
1808 pw.println("Requests:");
1809 pw.increaseIndent();
1810 for (int i = 0; i < nai.networkRequests.size(); i++) {
1811 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001812 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001813 pw.decreaseIndent();
1814 pw.println("Lingered:");
1815 pw.increaseIndent();
1816 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1817 pw.decreaseIndent();
1818 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001819 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001820 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001821 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001822
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001823 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001824 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001825 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1826 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001827 }
1828 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001829 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001830
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001831 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001832
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001833 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001834 pw.print("mNetTransitionWakeLock: currently " +
1835 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1836 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1837 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1838 } else {
1839 pw.println(", last requested never");
1840 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001841 }
1842 pw.println();
1843
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001844 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001845
Lorenzo Colittie3805462015-06-03 11:18:24 +09001846 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001847 pw.println();
1848 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001849 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001850 for(int i = 0; i < mInetLog.size(); i++) {
1851 pw.println(mInetLog.get(i));
1852 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001853 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001854 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001855
1856 if (argsContain(args, "--short") == false) {
1857 pw.println();
1858 synchronized (mValidationLogs) {
1859 pw.println("mValidationLogs (most recent first):");
1860 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1861 pw.println(p.first);
1862 pw.increaseIndent();
1863 p.second.dump(fd, pw, args);
1864 pw.decreaseIndent();
1865 }
1866 }
Erik Kline7523eb32015-07-09 18:24:03 +09001867
1868 pw.println();
1869 pw.println("mNetworkRequestInfoLogs (most recent first):");
1870 pw.increaseIndent();
1871 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1872 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 }
1875
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001876 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001877 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001878 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001879 if (officialNai != null && officialNai.equals(nai)) return true;
1880 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001881 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001882 " - " + nai);
1883 }
1884 return false;
1885 }
1886
Paul Jensenc8b9a742014-09-30 15:37:41 -04001887 private boolean isRequest(NetworkRequest request) {
1888 return mNetworkRequests.get(request).isRequest;
1889 }
1890
Robert Greenwalt42acef32009-08-12 16:08:25 -07001891 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001892 private class NetworkStateTrackerHandler extends Handler {
1893 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001894 super(looper);
1895 }
1896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 @Override
1898 public void handleMessage(Message msg) {
1899 NetworkInfo info;
1900 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001901 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001902 handleAsyncChannelHalfConnect(msg);
1903 break;
1904 }
1905 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1906 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1907 if (nai != null) nai.asyncChannel.disconnect();
1908 break;
1909 }
1910 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1911 handleAsyncChannelDisconnected(msg);
1912 break;
1913 }
1914 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1915 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1916 if (nai == null) {
1917 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1918 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001919 final NetworkCapabilities networkCapabilities =
1920 (NetworkCapabilities)msg.obj;
1921 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1922 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1923 Slog.wtf(TAG, "BUG: " + nai + " has stateful capability.");
1924 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001925 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001926 }
1927 break;
1928 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001929 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1930 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1931 if (nai == null) {
1932 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1933 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001934 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001935 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001936 "; created=" + nai.created);
1937 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001938 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001939 synchronized (nai) {
1940 nai.linkProperties = (LinkProperties)msg.obj;
1941 }
Paul Jenseneec75412014-08-04 12:21:19 -04001942 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001943 }
1944 break;
1945 }
1946 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1947 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1948 if (nai == null) {
1949 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1950 break;
1951 }
1952 info = (NetworkInfo) msg.obj;
1953 updateNetworkInfo(nai, info);
1954 break;
1955 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001956 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1957 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1958 if (nai == null) {
1959 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1960 break;
1961 }
1962 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001963 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001964 break;
1965 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001966 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1967 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1968 if (nai == null) {
1969 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1970 break;
1971 }
1972 try {
1973 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001974 } catch (Exception e) {
1975 // Never crash!
1976 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001977 }
1978 break;
1979 }
1980 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1981 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1982 if (nai == null) {
1983 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1984 break;
1985 }
1986 try {
1987 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001988 } catch (Exception e) {
1989 // Never crash!
1990 loge("Exception in removeVpnUidRanges: " + e);
1991 }
1992 break;
1993 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001994 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1995 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1996 if (nai == null) {
1997 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1998 break;
1999 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002000 if (nai.created && !nai.networkMisc.explicitlySelected) {
2001 loge("ERROR: created network explicitly selected.");
2002 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002003 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002004 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002005 break;
2006 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002007 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002008 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002009 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2010 final boolean valid =
2011 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002012 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2013 if (valid != nai.lastValidated) {
2014 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002015 nai.lastValidated = valid;
2016 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002017 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002018 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2019 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002020 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002021 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002022 // Let the NetworkAgent know the state of its network
2023 nai.asyncChannel.sendMessage(
2024 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2025 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2026 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002027 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002028 break;
2029 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002030 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002031 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002032 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2033 handleLingerComplete(nai);
2034 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002035 break;
2036 }
Paul Jensen869868be2014-05-15 10:33:05 -04002037 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002038 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002039 final boolean visible = (msg.arg1 != 0);
2040 final NetworkAgentInfo nai;
2041 synchronized (mNetworkForNetId) {
2042 nai = mNetworkForNetId.get(netId);
2043 }
2044 // If captive portal status has changed, update capabilities.
2045 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2046 nai.lastCaptivePortalDetected = visible;
2047 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002048 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002049 }
2050 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002051 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002052 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002053 if (nai == null) {
2054 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2055 break;
2056 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002057 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002058 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2059 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002060 }
Paul Jensen869868be2014-05-15 10:33:05 -04002061 break;
2062 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002063 }
2064 }
2065 }
2066
Paul Jensen85cf78e2015-06-25 13:25:07 -04002067 private void linger(NetworkAgentInfo nai) {
2068 nai.lingering = true;
2069 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2070 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2071 }
2072
Paul Jensen0cc17322014-11-25 15:26:53 -05002073 // Cancel any lingering so the linger timeout doesn't teardown a network.
2074 // This should be called when a network begins satisfying a NetworkRequest.
2075 // Note: depending on what state the NetworkMonitor is in (e.g.,
2076 // if it's awaiting captive portal login, or if validation failed), this
2077 // may trigger a re-evaluation of the network.
2078 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002079 nai.networkLingered.clear();
2080 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002081 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002082 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002083 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2084 }
2085
Robert Greenwalt7b816022014-04-18 15:25:25 -07002086 private void handleAsyncChannelHalfConnect(Message msg) {
2087 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002088 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002089 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2090 if (VDBG) log("NetworkFactory connected");
2091 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002092 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002093 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002094 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002095 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002096 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002097 }
2098 } else {
2099 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002100 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002101 }
2102 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2103 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2104 if (VDBG) log("NetworkAgent connected");
2105 // A network agent has requested a connection. Establish the connection.
2106 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2107 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2108 } else {
2109 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002110 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002111 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002112 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002113 synchronized (mNetworkForNetId) {
2114 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002115 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002116 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002117 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002118 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002119 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002120 }
2121 }
2122 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002123
Robert Greenwalt7b816022014-04-18 15:25:25 -07002124 private void handleAsyncChannelDisconnected(Message msg) {
2125 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2126 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002127 if (DBG) {
2128 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2129 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002130 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002131 // TODO - if we move the logic to the network agent (have them disconnect
2132 // because they lost all their requests or because their score isn't good)
2133 // then they would disconnect organically, report their new state and then
2134 // disconnect the channel.
2135 if (nai.networkInfo.isConnected()) {
2136 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2137 null, null);
2138 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002139 final boolean wasDefault = isDefaultNetwork(nai);
2140 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002141 mDefaultInetConditionPublished = 0;
2142 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002143 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002144 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002145 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002146 mNetworkAgentInfos.remove(msg.replyTo);
2147 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002148 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002149 // Remove the NetworkAgent, but don't mark the netId as
2150 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002151 mNetworkForNetId.remove(nai.network.netId);
2152 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002153 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002154 for (int i = 0; i < nai.networkRequests.size(); i++) {
2155 NetworkRequest request = nai.networkRequests.valueAt(i);
2156 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2157 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2158 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002159 sendUpdatedScoreToFactories(request, 0);
2160 }
2161 }
2162 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2163 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002164 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002165 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002167 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002168 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002169 if (nai.created) {
2170 // Tell netd to clean up the configuration for this network
2171 // (routing rules, DNS, etc).
2172 // This may be slow as it requires a lot of netd shelling out to ip and
2173 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2174 // after we've rematched networks with requests which should make a potential
2175 // fallback network the default or requested a new network from the
2176 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2177 // long time.
2178 try {
2179 mNetd.removeNetwork(nai.network.netId);
2180 } catch (Exception e) {
2181 loge("Exception removing network: " + e);
2182 }
2183 }
2184 synchronized (mNetworkForNetId) {
2185 mNetIdInUse.delete(nai.network.netId);
2186 }
2187 } else {
2188 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2189 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002190 }
2191 }
2192
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002193 // If this method proves to be too slow then we can maintain a separate
2194 // pendingIntent => NetworkRequestInfo map.
2195 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2196 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2197 Intent intent = pendingIntent.getIntent();
2198 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2199 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2200 if (existingPendingIntent != null &&
2201 existingPendingIntent.getIntent().filterEquals(intent)) {
2202 return entry.getValue();
2203 }
2204 }
2205 return null;
2206 }
2207
2208 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2209 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2210
2211 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2212 if (existingRequest != null) { // remove the existing request.
2213 if (DBG) log("Replacing " + existingRequest.request + " with "
2214 + nri.request + " because their intents matched.");
2215 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2216 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002217 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002218 }
2219
Erik Klineda4bfa82015-04-30 12:58:40 +09002220 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002221 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002222 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002223 rematchAllNetworksAndRequests(null, 0);
2224 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2225 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002226 }
2227 }
2228
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002229 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2230 int callingUid) {
2231 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2232 if (nri != null) {
2233 handleReleaseNetworkRequest(nri.request, callingUid);
2234 }
2235 }
2236
Paul Jensen99364842014-12-09 11:43:45 -05002237 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002238 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2239 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002240 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002241 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002242 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2243 // If this Network is already the highest scoring Network for a request, or if
2244 // there is hope for it to become one if it validated, then it is needed.
2245 if (nri.isRequest && nai.satisfies(nri.request) &&
2246 (nai.networkRequests.get(nri.request.requestId) != null ||
2247 // Note that this catches two important cases:
2248 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2249 // is currently satisfying the request. This is desirable when
2250 // cellular ends up validating but WiFi does not.
2251 // 2. Unvalidated WiFi will not be reaped when validated cellular
2252 // is currently satsifying the request. This is desirable when
2253 // WiFi ends up validating and out scoring cellular.
2254 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2255 nai.getCurrentScoreAsValidated())) {
2256 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002257 }
2258 }
Paul Jensene0988542015-06-25 15:30:08 -04002259 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002260 }
2261
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002262 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2263 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002264 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002265 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002266 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2267 return;
2268 }
2269 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002270 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002271 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002272 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002273 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002274 // Find all networks that are satisfying this request and remove the request
2275 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002276 // TODO - it's my understanding that for a request there is only a single
2277 // network satisfying it, so this loop is wasteful
2278 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002279 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2280 if (nai.networkRequests.get(nri.request.requestId) != null) {
2281 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002282 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002283 log(" Removing from current network " + nai.name() +
2284 ", leaving " + nai.networkRequests.size() +
2285 " requests.");
2286 }
Paul Jensen99364842014-12-09 11:43:45 -05002287 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002288 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002289 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002290 } else {
2291 // suspect there should only be one pass through here
2292 // but if any were kept do the check below
2293 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002294 }
2295 }
2296 }
2297
Robert Greenwalt51481852015-01-08 14:43:31 -08002298 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2299 if (nai != null) {
2300 mNetworkForRequestId.remove(nri.request.requestId);
2301 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002302 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002303 // that a network connected to serve it, even though the network was already
2304 // connected. Now that this request has gone away, we might have to pretend
2305 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002306 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002307 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2308 boolean doRemove = true;
2309 if (wasKept) {
2310 // check if any of the remaining requests for this network are for the
2311 // same legacy type - if so, don't remove the nai
2312 for (int i = 0; i < nai.networkRequests.size(); i++) {
2313 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2314 if (otherRequest.legacyType == nri.request.legacyType &&
2315 isRequest(otherRequest)) {
2316 if (DBG) log(" still have other legacy request - leaving");
2317 doRemove = false;
2318 }
2319 }
2320 }
2321
2322 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002323 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002324 }
2325 }
2326
Robert Greenwalta67be032014-05-16 15:49:14 -07002327 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002328 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2329 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002330 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002331 } else {
2332 // listens don't have a singular affectedNetwork. Check all networks to see
2333 // if this listen request applies and remove it.
2334 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2335 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002336 }
2337 }
2338 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2339 }
2340 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002341
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002342 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2343 enforceConnectivityInternalPermission();
2344 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2345 accept ? 1 : 0, always ? 1: 0, network));
2346 }
2347
2348 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2349 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2350 " accept=" + accept + " always=" + always);
2351
2352 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2353 if (nai == null) {
2354 // Nothing to do.
2355 return;
2356 }
2357
2358 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002359 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002360 return;
2361 }
2362
2363 if (!nai.networkMisc.explicitlySelected) {
2364 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2365 }
2366
2367 if (accept != nai.networkMisc.acceptUnvalidated) {
2368 int oldScore = nai.getCurrentScore();
2369 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002370 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002371 sendUpdatedScoreToFactories(nai);
2372 }
2373
2374 if (always) {
2375 nai.asyncChannel.sendMessage(
2376 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2377 }
2378
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002379 if (!accept) {
2380 // Tell the NetworkAgent that the network does not have Internet access (because that's
2381 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2382 // the future. We do this now because NetworkMonitor might not yet have finished
2383 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2384 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2385 NetworkAgent.INVALID_NETWORK, 0, null);
2386 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2387 // to reconnect to it immediately. http://b/20739299
2388 }
2389
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002390 }
2391
2392 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002393 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002394 mHandler.sendMessageDelayed(
2395 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2396 PROMPT_UNVALIDATED_DELAY_MS);
2397 }
2398
2399 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002400 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002401 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2402
2403 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2404 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002405 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002406 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002407 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2408 return;
2409 }
2410
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002411 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002412 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002413 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2414 intent.setClassName("com.android.settings",
2415 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002416
2417 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2418 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2419 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002420 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002421 }
2422
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002423 private class InternalHandler extends Handler {
2424 public InternalHandler(Looper looper) {
2425 super(looper);
2426 }
2427
2428 @Override
2429 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002430 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002431 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002432 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002433 String causedBy = null;
2434 synchronized (ConnectivityService.this) {
2435 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2436 mNetTransitionWakeLock.isHeld()) {
2437 mNetTransitionWakeLock.release();
2438 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002439 } else {
2440 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002441 }
2442 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002443 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2444 log("Failed to find a new network - expiring NetTransition Wakelock");
2445 } else {
2446 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2447 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002448 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002449 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002450 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002451 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002452 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002453 break;
2454 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002455 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002456 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002457 sendStickyBroadcast(intent);
2458 break;
2459 }
Jason Monkdecd2952013-10-10 14:02:51 -04002460 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002461 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002462 break;
2463 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002464 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002465 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2466 break;
2467 }
2468 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2469 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002470 break;
2471 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002472 case EVENT_REGISTER_NETWORK_AGENT: {
2473 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2474 break;
2475 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002476 case EVENT_REGISTER_NETWORK_REQUEST:
2477 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002478 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002479 break;
2480 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002481 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2482 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002483 handleRegisterNetworkRequestWithIntent(msg);
2484 break;
2485 }
2486 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2487 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2488 break;
2489 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002490 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002491 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002492 break;
2493 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002494 case EVENT_SET_ACCEPT_UNVALIDATED: {
2495 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2496 break;
2497 }
2498 case EVENT_PROMPT_UNVALIDATED: {
2499 handlePromptUnvalidated((Network) msg.obj);
2500 break;
2501 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002502 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2503 handleMobileDataAlwaysOn();
2504 break;
2505 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002506 case EVENT_SYSTEM_READY: {
2507 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2508 nai.networkMonitor.systemReady = true;
2509 }
2510 break;
2511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 }
2513 }
2514 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002515
2516 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002517 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002518 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002519 if (isTetheringSupported()) {
2520 return mTethering.tether(iface);
2521 } else {
2522 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2523 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002524 }
2525
2526 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002527 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002528 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002529
2530 if (isTetheringSupported()) {
2531 return mTethering.untether(iface);
2532 } else {
2533 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2534 }
2535 }
2536
2537 // javadoc from interface
2538 public int getLastTetherError(String iface) {
2539 enforceTetherAccessPermission();
2540
2541 if (isTetheringSupported()) {
2542 return mTethering.getLastTetherError(iface);
2543 } else {
2544 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2545 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002546 }
2547
2548 // TODO - proper iface API for selection by property, inspection, etc
2549 public String[] getTetherableUsbRegexs() {
2550 enforceTetherAccessPermission();
2551 if (isTetheringSupported()) {
2552 return mTethering.getTetherableUsbRegexs();
2553 } else {
2554 return new String[0];
2555 }
2556 }
2557
2558 public String[] getTetherableWifiRegexs() {
2559 enforceTetherAccessPermission();
2560 if (isTetheringSupported()) {
2561 return mTethering.getTetherableWifiRegexs();
2562 } else {
2563 return new String[0];
2564 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002565 }
2566
Danica Chang6fdd0c62010-08-11 14:54:43 -07002567 public String[] getTetherableBluetoothRegexs() {
2568 enforceTetherAccessPermission();
2569 if (isTetheringSupported()) {
2570 return mTethering.getTetherableBluetoothRegexs();
2571 } else {
2572 return new String[0];
2573 }
2574 }
2575
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002576 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002577 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002578 if (isTetheringSupported()) {
2579 return mTethering.setUsbTethering(enable);
2580 } else {
2581 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2582 }
2583 }
2584
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002585 // TODO - move iface listing, queries, etc to new module
2586 // javadoc from interface
2587 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002588 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002589 return mTethering.getTetherableIfaces();
2590 }
2591
2592 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002593 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002594 return mTethering.getTetheredIfaces();
2595 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002596
Robert Greenwalt5a735062010-03-02 17:25:02 -08002597 public String[] getTetheringErroredIfaces() {
2598 enforceTetherAccessPermission();
2599 return mTethering.getErroredIfaces();
2600 }
2601
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002602 public String[] getTetheredDhcpRanges() {
2603 enforceConnectivityInternalPermission();
2604 return mTethering.getTetheredDhcpRanges();
2605 }
2606
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002607 // if ro.tether.denied = true we default to no tethering
2608 // gservices could set the secure setting to 1 though to enable it on a build where it
2609 // had previously been turned off.
2610 public boolean isTetheringSupported() {
2611 enforceTetherAccessPermission();
2612 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002613 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002614 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2615 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002616 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2617 mTethering.getTetherableWifiRegexs().length != 0 ||
2618 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2619 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002620 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002621
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002622 // Called when we lose the default network and have no replacement yet.
2623 // This will automatically be cleared after X seconds or a new default network
2624 // becomes CONNECTED, whichever happens first. The timer is started by the
2625 // first caller and not restarted by subsequent callers.
2626 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002627 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002628 synchronized (this) {
2629 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002630 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002631 mNetTransitionWakeLock.acquire();
2632 mNetTransitionWakeLockCausedBy = forWhom;
2633 }
2634 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002635 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002636 mNetTransitionWakeLockTimeout);
2637 return;
2638 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002639
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002640 // 100 percent is full good, 0 is full bad.
2641 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002642 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002643 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002644 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002645 }
2646
Paul Jensenbfd17b72015-04-07 12:43:13 -04002647 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002648 enforceAccessPermission();
2649 enforceInternetPermission();
2650
Paul Jensenbfd17b72015-04-07 12:43:13 -04002651 NetworkAgentInfo nai;
2652 if (network == null) {
2653 nai = getDefaultNetwork();
2654 } else {
2655 nai = getNetworkAgentInfoForNetwork(network);
2656 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002657 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2658 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2659 return;
2660 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002661 // Revalidate if the app report does not match our current validated state.
2662 if (hasConnectivity == nai.lastValidated) return;
2663 final int uid = Binder.getCallingUid();
2664 if (DBG) {
2665 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2666 ") by " + uid);
2667 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002668 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002669 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2670 // which isn't meant to work on uncreated networks.
2671 if (!nai.created) return;
2672
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002673 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002674
2675 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2676 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002677 }
2678
Paul Jensencee9b512015-05-06 07:32:40 -04002679 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002680 // this information is already available as a world read/writable jvm property
2681 // so this API change wouldn't have a benifit. It also breaks the passing
2682 // of proxy info to all the JVMs.
2683 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002684 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002685 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002686 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2687 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002688 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002689 }
2690
Paul Jensencee9b512015-05-06 07:32:40 -04002691 public ProxyInfo getProxyForNetwork(Network network) {
2692 if (network == null) return getDefaultProxy();
2693 final ProxyInfo globalProxy = getGlobalProxy();
2694 if (globalProxy != null) return globalProxy;
2695 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2696 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2697 // caller may not have.
2698 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2699 if (nai == null) return null;
2700 synchronized (nai) {
2701 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2702 if (proxyInfo == null) return null;
2703 return new ProxyInfo(proxyInfo);
2704 }
2705 }
2706
Paul Jensene0bef712014-12-10 15:12:18 -05002707 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2708 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2709 // proxy is null then there is no proxy in place).
2710 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2711 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2712 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2713 proxy = null;
2714 }
2715 return proxy;
2716 }
2717
2718 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2719 // better for determining if a new proxy broadcast is necessary:
2720 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2721 // avoid unnecessary broadcasts.
2722 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2723 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2724 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2725 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2726 // all set.
2727 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2728 a = canonicalizeProxyInfo(a);
2729 b = canonicalizeProxyInfo(b);
2730 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2731 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2732 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2733 }
2734
Jason Monk207900c2014-04-25 15:00:09 -04002735 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002736 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002737
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002738 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002739 if (proxyProperties == mGlobalProxy) return;
2740 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2741 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2742
2743 String host = "";
2744 int port = 0;
2745 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002746 String pacFileUrl = "";
2747 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002748 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002749 if (!proxyProperties.isValid()) {
2750 if (DBG)
2751 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2752 return;
2753 }
Jason Monk207900c2014-04-25 15:00:09 -04002754 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002755 host = mGlobalProxy.getHost();
2756 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002757 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002758 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002759 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002760 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002761 } else {
2762 mGlobalProxy = null;
2763 }
2764 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002765 final long token = Binder.clearCallingIdentity();
2766 try {
2767 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2768 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2769 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2770 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002771 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002772 } finally {
2773 Binder.restoreCallingIdentity(token);
2774 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002775
Jason Monkcf0f97a2014-10-02 15:39:38 -04002776 if (mGlobalProxy == null) {
2777 proxyProperties = mDefaultProxy;
2778 }
2779 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002780 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002781 }
2782
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002783 private void loadGlobalProxy() {
2784 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002785 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2786 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2787 String exclList = Settings.Global.getString(res,
2788 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002789 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2790 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002791 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002792 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002793 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002794 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002795 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002796 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002797 if (!proxyProperties.isValid()) {
2798 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2799 return;
2800 }
2801
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002802 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002803 mGlobalProxy = proxyProperties;
2804 }
2805 }
2806 }
2807
Jason Monk207900c2014-04-25 15:00:09 -04002808 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002809 // this information is already available as a world read/writable jvm property
2810 // so this API change wouldn't have a benifit. It also breaks the passing
2811 // of proxy info to all the JVMs.
2812 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002813 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002814 return mGlobalProxy;
2815 }
2816 }
2817
Jason Monk207900c2014-04-25 15:00:09 -04002818 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002819 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002820 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002821 proxy = null;
2822 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002823 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002824 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002825 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002826 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002827 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2828 return;
2829 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002830
2831 // This call could be coming from the PacManager, containing the port of the local
2832 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2833 // global (to get the correct local port), and send a broadcast.
2834 // TODO: Switch PacManager to have its own message to send back rather than
2835 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002836 if ((mGlobalProxy != null) && (proxy != null)
2837 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002838 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2839 mGlobalProxy = proxy;
2840 sendProxyBroadcast(mGlobalProxy);
2841 return;
2842 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002843 mDefaultProxy = proxy;
2844
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002845 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002846 if (!mDefaultProxyDisabled) {
2847 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002848 }
2849 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002850 }
2851
Paul Jensene0bef712014-12-10 15:12:18 -05002852 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2853 // This method gets called when any network changes proxy, but the broadcast only ever contains
2854 // the default proxy (even if it hasn't changed).
2855 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2856 // world where an app might be bound to a non-default network.
2857 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2858 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2859 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2860
2861 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2862 sendProxyBroadcast(getDefaultProxy());
2863 }
2864 }
2865
Robert Greenwalt434203a2010-10-11 16:00:27 -07002866 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002867 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2868 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002869 if (!TextUtils.isEmpty(proxy)) {
2870 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002871 if (data.length == 0) {
2872 return;
2873 }
2874
Robert Greenwalt434203a2010-10-11 16:00:27 -07002875 String proxyHost = data[0];
2876 int proxyPort = 8080;
2877 if (data.length > 1) {
2878 try {
2879 proxyPort = Integer.parseInt(data[1]);
2880 } catch (NumberFormatException e) {
2881 return;
2882 }
2883 }
Jason Monk207900c2014-04-25 15:00:09 -04002884 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002885 setGlobalProxy(p);
2886 }
2887 }
2888
Jason Monk207900c2014-04-25 15:00:09 -04002889 private void sendProxyBroadcast(ProxyInfo proxy) {
2890 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002891 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002892 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002893 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002894 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2895 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002896 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002897 final long ident = Binder.clearCallingIdentity();
2898 try {
2899 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2900 } finally {
2901 Binder.restoreCallingIdentity(ident);
2902 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002903 }
2904
2905 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002906 final private HashMap<Uri, Integer> mUriEventMap;
2907 final private Context mContext;
2908 final private Handler mHandler;
2909
2910 SettingsObserver(Context context, Handler handler) {
2911 super(null);
2912 mUriEventMap = new HashMap<Uri, Integer>();
2913 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002914 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002915 }
2916
Erik Klineda4bfa82015-04-30 12:58:40 +09002917 void observe(Uri uri, int what) {
2918 mUriEventMap.put(uri, what);
2919 final ContentResolver resolver = mContext.getContentResolver();
2920 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002921 }
2922
2923 @Override
2924 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002925 Slog.wtf(TAG, "Should never be reached.");
2926 }
2927
2928 @Override
2929 public void onChange(boolean selfChange, Uri uri) {
2930 final Integer what = mUriEventMap.get(uri);
2931 if (what != null) {
2932 mHandler.obtainMessage(what.intValue()).sendToTarget();
2933 } else {
2934 loge("No matching event to send for URI=" + uri);
2935 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002936 }
2937 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002938
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002939 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002940 Slog.d(TAG, s);
2941 }
2942
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002943 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002944 Slog.e(TAG, s);
2945 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002946
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002947 private static <T> T checkNotNull(T value, String message) {
2948 if (value == null) {
2949 throw new NullPointerException(message);
2950 }
2951 return value;
2952 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002953
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002954 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002955 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002956 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2957 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2958 *
2959 * @param oldPackage Package name of the application which currently controls VPN, which will
2960 * be replaced. If there is no such application, this should should either be
2961 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2962 * @param newPackage Package name of the application which should gain control of VPN, or
2963 * {@code null} to disable.
2964 * @param userId User for whom to prepare the new VPN.
2965 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002966 * @hide
2967 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002968 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002969 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2970 int userId) {
2971 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002972 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01002973
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002974 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07002975 Vpn vpn = mVpns.get(userId);
2976 if (vpn != null) {
2977 return vpn.prepare(oldPackage, newPackage);
2978 } else {
2979 return false;
2980 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002981 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002982 }
2983
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002984 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01002985 * Set whether the VPN package has the ability to launch VPNs without user intervention.
2986 * This method is used by system-privileged apps.
2987 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2988 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2989 *
2990 * @param packageName The package for which authorization state should change.
2991 * @param userId User for whom {@code packageName} is installed.
2992 * @param authorized {@code true} if this app should be able to start a VPN connection without
2993 * explicit user approval, {@code false} if not.
2994 *
Jeff Davidson05542602014-08-11 14:07:27 -07002995 * @hide
2996 */
2997 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002998 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
2999 enforceCrossUserPermission(userId);
3000
Jeff Davidson05542602014-08-11 14:07:27 -07003001 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003002 Vpn vpn = mVpns.get(userId);
3003 if (vpn != null) {
3004 vpn.setPackageAuthorization(packageName, authorized);
3005 }
Jeff Davidson05542602014-08-11 14:07:27 -07003006 }
3007 }
3008
3009 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003010 * Configure a TUN interface and return its file descriptor. Parameters
3011 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003012 * and not available in ConnectivityManager. Permissions are checked in
3013 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003014 * @hide
3015 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003016 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003017 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003018 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003019 int user = UserHandle.getUserId(Binder.getCallingUid());
3020 synchronized(mVpns) {
3021 return mVpns.get(user).establish(config);
3022 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003023 }
3024
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003025 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003026 * Start legacy VPN, controlling native daemons as needed. Creates a
3027 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003028 */
3029 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003030 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003031 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003032 final LinkProperties egress = getActiveLinkProperties();
3033 if (egress == null) {
3034 throw new IllegalStateException("Missing active network connection");
3035 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003036 int user = UserHandle.getUserId(Binder.getCallingUid());
3037 synchronized(mVpns) {
3038 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3039 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003040 }
3041
3042 /**
3043 * Return the information of the ongoing legacy VPN. This method is used
3044 * by VpnSettings and not available in ConnectivityManager. Permissions
3045 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003046 */
3047 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003048 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3049 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003050 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003051 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003052 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003053 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003054 }
3055
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003056 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003057 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3058 * and not available in ConnectivityManager.
3059 */
3060 @Override
3061 public VpnInfo[] getAllVpnInfo() {
3062 enforceConnectivityInternalPermission();
3063 if (mLockdownEnabled) {
3064 return new VpnInfo[0];
3065 }
3066
3067 synchronized(mVpns) {
3068 List<VpnInfo> infoList = new ArrayList<>();
3069 for (int i = 0; i < mVpns.size(); i++) {
3070 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3071 if (info != null) {
3072 infoList.add(info);
3073 }
3074 }
3075 return infoList.toArray(new VpnInfo[infoList.size()]);
3076 }
3077 }
3078
3079 /**
3080 * @return VPN information for accounting, or null if we can't retrieve all required
3081 * information, e.g primary underlying iface.
3082 */
3083 @Nullable
3084 private VpnInfo createVpnInfo(Vpn vpn) {
3085 VpnInfo info = vpn.getVpnInfo();
3086 if (info == null) {
3087 return null;
3088 }
3089 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3090 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3091 // the underlyingNetworks list.
3092 if (underlyingNetworks == null) {
3093 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3094 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3095 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3096 }
3097 } else if (underlyingNetworks.length > 0) {
3098 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3099 if (linkProperties != null) {
3100 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3101 }
3102 }
3103 return info.primaryUnderlyingIface == null ? null : info;
3104 }
3105
3106 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003107 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3108 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003109 * Permissions are checked in Vpn class.
3110 * @hide
3111 */
3112 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003113 public VpnConfig getVpnConfig(int userId) {
3114 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003115 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003116 Vpn vpn = mVpns.get(userId);
3117 if (vpn != null) {
3118 return vpn.getVpnConfig();
3119 } else {
3120 return null;
3121 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003122 }
3123 }
3124
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003125 @Override
3126 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003127 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3128 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3129 return false;
3130 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003131
3132 // Tear down existing lockdown if profile was removed
3133 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3134 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003135 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003136 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3137 return false;
3138 }
3139
3140 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3141 final VpnProfile profile = VpnProfile.decode(
3142 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003143 int user = UserHandle.getUserId(Binder.getCallingUid());
3144 synchronized(mVpns) {
3145 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3146 profile));
3147 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003148 } else {
3149 setLockdownTracker(null);
3150 }
3151
3152 return true;
3153 }
3154
3155 /**
3156 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3157 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3158 */
3159 private void setLockdownTracker(LockdownVpnTracker tracker) {
3160 // Shutdown any existing tracker
3161 final LockdownVpnTracker existing = mLockdownTracker;
3162 mLockdownTracker = null;
3163 if (existing != null) {
3164 existing.shutdown();
3165 }
3166
3167 try {
3168 if (tracker != null) {
3169 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003170 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003171 mLockdownTracker = tracker;
3172 mLockdownTracker.init();
3173 } else {
3174 mNetd.setFirewallEnabled(false);
3175 }
3176 } catch (RemoteException e) {
3177 // ignored; NMS lives inside system_server
3178 }
3179 }
3180
3181 private void throwIfLockdownEnabled() {
3182 if (mLockdownEnabled) {
3183 throw new IllegalStateException("Unavailable in lockdown mode");
3184 }
3185 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003186
Wink Savilleab9321d2013-06-29 21:10:57 -07003187 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003188 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003189 // TODO: Remove? Any reason to trigger a provisioning check?
3190 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003191 }
3192
3193 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003194 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003195
Paul Jensen89e0f092014-09-15 15:59:36 -04003196 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003197 if (DBG) {
3198 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003199 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003200 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003201 Intent intent = new Intent(action);
3202 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003203 // Concatenate the range of types onto the range of NetIDs.
3204 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003205 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003206 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003207 }
3208
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003209 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003210 * Show or hide network provisioning notifications.
3211 *
3212 * We use notifications for two purposes: to notify that a network requires sign in
3213 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3214 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3215 * particular network we can display the notification type that was most recently requested.
3216 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3217 * might first display NO_INTERNET, and then when the captive portal check completes, display
3218 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003219 *
3220 * @param id an identifier that uniquely identifies this notification. This must match
3221 * between show and hide calls. We use the NetID value but for legacy callers
3222 * we concatenate the range of types with the range of NetIDs.
3223 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003224 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003225 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3226 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003227 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003228 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3229 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003230 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003231 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003232
3233 Resources r = Resources.getSystem();
3234 NotificationManager notificationManager = (NotificationManager) mContext
3235 .getSystemService(Context.NOTIFICATION_SERVICE);
3236
3237 if (visible) {
3238 CharSequence title;
3239 CharSequence details;
3240 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003241 if (notifyType == NotificationType.NO_INTERNET &&
3242 networkType == ConnectivityManager.TYPE_WIFI) {
3243 title = r.getString(R.string.wifi_no_internet, 0);
3244 details = r.getString(R.string.wifi_no_internet_detailed);
3245 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3246 } else if (notifyType == NotificationType.SIGN_IN) {
3247 switch (networkType) {
3248 case ConnectivityManager.TYPE_WIFI:
3249 title = r.getString(R.string.wifi_available_sign_in, 0);
3250 details = r.getString(R.string.network_available_sign_in_detailed,
3251 extraInfo);
3252 icon = R.drawable.stat_notify_wifi_in_range;
3253 break;
3254 case ConnectivityManager.TYPE_MOBILE:
3255 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3256 title = r.getString(R.string.network_available_sign_in, 0);
3257 // TODO: Change this to pull from NetworkInfo once a printable
3258 // name has been added to it
3259 details = mTelephonyManager.getNetworkOperatorName();
3260 icon = R.drawable.stat_notify_rssi_in_range;
3261 break;
3262 default:
3263 title = r.getString(R.string.network_available_sign_in, 0);
3264 details = r.getString(R.string.network_available_sign_in_detailed,
3265 extraInfo);
3266 icon = R.drawable.stat_notify_rssi_in_range;
3267 break;
3268 }
3269 } else {
3270 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3271 + getNetworkTypeName(networkType));
3272 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003273 }
3274
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003275 Notification notification = new Notification.Builder(mContext)
3276 .setWhen(0)
3277 .setSmallIcon(icon)
3278 .setAutoCancel(true)
3279 .setTicker(title)
3280 .setColor(mContext.getColor(
3281 com.android.internal.R.color.system_notification_accent_color))
3282 .setContentTitle(title)
3283 .setContentText(details)
3284 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003285 .setLocalOnly(true)
3286 .setPriority(highPriority ?
3287 Notification.PRIORITY_HIGH :
3288 Notification.PRIORITY_DEFAULT)
3289 .setDefaults(Notification.DEFAULT_ALL)
3290 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003291 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003292
Wink Saville948282b2013-08-29 08:55:16 -07003293 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003294 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003295 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003296 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003297 npe.printStackTrace();
3298 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003299 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003300 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003301 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003302 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003303 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003304 npe.printStackTrace();
3305 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003306 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003307 }
3308
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003309 /** Location to an updatable file listing carrier provisioning urls.
3310 * An example:
3311 *
3312 * <?xml version="1.0" encoding="utf-8"?>
3313 * <provisioningUrls>
3314 * <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 -07003315 * </provisioningUrls>
3316 */
3317 private static final String PROVISIONING_URL_PATH =
3318 "/data/misc/radio/provisioning_urls.xml";
3319 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003320
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003321 /** XML tag for root element. */
3322 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3323 /** XML tag for individual url */
3324 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003325 /** XML attribute for mcc */
3326 private static final String ATTR_MCC = "mcc";
3327 /** XML attribute for mnc */
3328 private static final String ATTR_MNC = "mnc";
3329
Paul Jensen434dde82015-06-11 09:43:30 -04003330 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003331 FileReader fileReader = null;
3332 XmlPullParser parser = null;
3333 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003334
3335 try {
3336 fileReader = new FileReader(mProvisioningUrlFile);
3337 parser = Xml.newPullParser();
3338 parser.setInput(fileReader);
3339 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3340
3341 while (true) {
3342 XmlUtils.nextElement(parser);
3343
3344 String element = parser.getName();
3345 if (element == null) break;
3346
Paul Jensen434dde82015-06-11 09:43:30 -04003347 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003348 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3349 try {
3350 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3351 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3352 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3353 parser.next();
3354 if (parser.getEventType() == XmlPullParser.TEXT) {
3355 return parser.getText();
3356 }
3357 }
3358 }
3359 } catch (NumberFormatException e) {
3360 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3361 }
3362 }
3363 }
3364 return null;
3365 } catch (FileNotFoundException e) {
3366 loge("Carrier Provisioning Urls file not found");
3367 } catch (XmlPullParserException e) {
3368 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3369 } catch (IOException e) {
3370 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3371 } finally {
3372 if (fileReader != null) {
3373 try {
3374 fileReader.close();
3375 } catch (IOException e) {}
3376 }
3377 }
3378 return null;
3379 }
3380
Wink Saville42d4f082013-07-20 20:31:59 -07003381 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003382 public String getMobileProvisioningUrl() {
3383 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003384 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003385 if (TextUtils.isEmpty(url)) {
3386 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003387 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003388 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003389 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003390 }
Wink Saville8cf35602013-07-10 23:00:07 -07003391 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003392 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003393 String phoneNumber = mTelephonyManager.getLine1Number();
3394 if (TextUtils.isEmpty(phoneNumber)) {
3395 phoneNumber = "0000000000";
3396 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003397 url = String.format(url,
3398 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3399 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003400 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003401 }
3402
Wink Savilleab9321d2013-06-29 21:10:57 -07003403 return url;
3404 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003405
Wink Saville948282b2013-08-29 08:55:16 -07003406 @Override
3407 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003408 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003409 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003410 final long ident = Binder.clearCallingIdentity();
3411 try {
3412 setProvNotificationVisible(visible, networkType, action);
3413 } finally {
3414 Binder.restoreCallingIdentity(ident);
3415 }
Wink Saville948282b2013-08-29 08:55:16 -07003416 }
Wink Saville7788c612013-08-29 14:57:08 -07003417
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003418 @Override
3419 public void setAirplaneMode(boolean enable) {
3420 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003421 final long ident = Binder.clearCallingIdentity();
3422 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003423 final ContentResolver cr = mContext.getContentResolver();
3424 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3425 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3426 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003427 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003428 } finally {
3429 Binder.restoreCallingIdentity(ident);
3430 }
3431 }
3432
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003433 private void onUserStart(int userId) {
3434 synchronized(mVpns) {
3435 Vpn userVpn = mVpns.get(userId);
3436 if (userVpn != null) {
3437 loge("Starting user already has a VPN");
3438 return;
3439 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003440 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003441 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003442 }
3443 }
3444
3445 private void onUserStop(int userId) {
3446 synchronized(mVpns) {
3447 Vpn userVpn = mVpns.get(userId);
3448 if (userVpn == null) {
3449 loge("Stopping user has no VPN");
3450 return;
3451 }
3452 mVpns.delete(userId);
3453 }
3454 }
3455
3456 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3457 @Override
3458 public void onReceive(Context context, Intent intent) {
3459 final String action = intent.getAction();
3460 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3461 if (userId == UserHandle.USER_NULL) return;
3462
3463 if (Intent.ACTION_USER_STARTING.equals(action)) {
3464 onUserStart(userId);
3465 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3466 onUserStop(userId);
3467 }
3468 }
3469 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003470
Robert Greenwalta67be032014-05-16 15:49:14 -07003471 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3472 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003473 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3474 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003475
Robert Greenwalta67be032014-05-16 15:49:14 -07003476 private static class NetworkFactoryInfo {
3477 public final String name;
3478 public final Messenger messenger;
3479 public final AsyncChannel asyncChannel;
3480
3481 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3482 this.name = name;
3483 this.messenger = messenger;
3484 this.asyncChannel = asyncChannel;
3485 }
3486 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003487
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003488 /**
3489 * Tracks info about the requester.
3490 * Also used to notice when the calling process dies so we can self-expire
3491 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003492 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3493 static final boolean REQUEST = true;
3494 static final boolean LISTEN = false;
3495
3496 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003497 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003498 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003499 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003500 final int mPid;
3501 final int mUid;
3502 final Messenger messenger;
3503 final boolean isRequest;
3504
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003505 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3506 request = r;
3507 mPendingIntent = pi;
3508 messenger = null;
3509 mBinder = null;
3510 mPid = getCallingPid();
3511 mUid = getCallingUid();
3512 this.isRequest = isRequest;
3513 }
3514
Robert Greenwalt9258c642014-03-26 16:47:06 -07003515 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3516 super();
3517 messenger = m;
3518 request = r;
3519 mBinder = binder;
3520 mPid = getCallingPid();
3521 mUid = getCallingUid();
3522 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003523 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003524
3525 try {
3526 mBinder.linkToDeath(this, 0);
3527 } catch (RemoteException e) {
3528 binderDied();
3529 }
3530 }
3531
3532 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003533 if (mBinder != null) {
3534 mBinder.unlinkToDeath(this, 0);
3535 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003536 }
3537
3538 public void binderDied() {
3539 log("ConnectivityService NetworkRequestInfo binderDied(" +
3540 request + ", " + mBinder + ")");
3541 releaseNetworkRequest(request);
3542 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003543
3544 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003545 return (isRequest ? "Request" : "Listen") +
3546 " from uid/pid:" + mUid + "/" + mPid +
3547 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003548 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003549 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003550 }
3551
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003552 private void ensureImmutableCapabilities(NetworkCapabilities networkCapabilities) {
3553 if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
3554 throw new IllegalArgumentException(
3555 "Cannot request network with NET_CAPABILITY_VALIDATED");
3556 }
3557 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
3558 throw new IllegalArgumentException(
3559 "Cannot request network with NET_CAPABILITY_CAPTIVE_PORTAL");
3560 }
3561 }
3562
Robert Greenwalt9258c642014-03-26 16:47:06 -07003563 @Override
3564 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003565 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003566 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003567 enforceNetworkRequestPermissions(networkCapabilities);
3568 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003569 ensureImmutableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003570
Robert Greenwalt6078b502014-06-11 16:05:07 -07003571 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003572 throw new IllegalArgumentException("Bad timeout specified");
3573 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003574
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003575 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3576 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003577 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3578 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003579 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003580
3581 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003582 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003583 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003584 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003585 }
3586 return networkRequest;
3587 }
3588
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003589 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003590 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003591 enforceConnectivityInternalPermission();
3592 } else {
3593 enforceChangePermission();
3594 }
3595 }
3596
fenglub15e72b2015-03-20 11:29:56 -07003597 @Override
fengludb571472015-04-21 17:12:05 -07003598 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003599 enforceAccessPermission();
3600 NetworkAgentInfo nai = null;
3601 if (network == null) {
3602 return false;
3603 }
3604 synchronized (mNetworkForNetId) {
3605 nai = mNetworkForNetId.get(network.netId);
3606 }
3607 if (nai != null) {
3608 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3609 return true;
3610 }
3611 return false;
3612 }
3613
3614
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003615 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3616 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003617 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003618 final int uidRules;
3619 final int uid = Binder.getCallingUid();
3620 synchronized(mRulesLock) {
3621 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3622 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003623 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003624 // we could silently fail or we can filter the available nets to only give
3625 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003626 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003627 }
3628 }
3629 }
3630
Robert Greenwalt9258c642014-03-26 16:47:06 -07003631 @Override
3632 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3633 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003634 checkNotNull(operation, "PendingIntent cannot be null.");
3635 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3636 enforceNetworkRequestPermissions(networkCapabilities);
3637 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003638 ensureImmutableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003639
3640 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3641 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003642 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3643 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003644 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003645 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3646 nri));
3647 return networkRequest;
3648 }
3649
Jeremy Joslin79294842014-12-03 17:15:28 -08003650 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3651 mHandler.sendMessageDelayed(
3652 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3653 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3654 }
3655
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003656 @Override
3657 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003658 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003659 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3660 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003661 }
3662
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003663 // In order to implement the compatibility measure for pre-M apps that call
3664 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3665 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3666 // This ensures it has permission to do so.
3667 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3668 if (nc == null) {
3669 return false;
3670 }
3671 int[] transportTypes = nc.getTransportTypes();
3672 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3673 return false;
3674 }
3675 try {
3676 mContext.enforceCallingOrSelfPermission(
3677 android.Manifest.permission.ACCESS_WIFI_STATE,
3678 "ConnectivityService");
3679 } catch (SecurityException e) {
3680 return false;
3681 }
3682 return true;
3683 }
3684
Robert Greenwalt9258c642014-03-26 16:47:06 -07003685 @Override
3686 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3687 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003688 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3689 enforceAccessPermission();
3690 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003691
Erik Kline7523eb32015-07-09 18:24:03 +09003692 NetworkRequest networkRequest = new NetworkRequest(
3693 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003694 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3695 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003696 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003697
3698 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3699 return networkRequest;
3700 }
3701
3702 @Override
3703 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3704 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003705 checkNotNull(operation, "PendingIntent cannot be null.");
3706 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3707 enforceAccessPermission();
3708 }
3709
Erik Kline7523eb32015-07-09 18:24:03 +09003710 NetworkRequest networkRequest = new NetworkRequest(
3711 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003712 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3713 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003714 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003715
3716 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003717 }
3718
3719 @Override
3720 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003721 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3722 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003723 }
3724
3725 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003726 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003727 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003728 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3729 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003730 }
3731
Robert Greenwalta67be032014-05-16 15:49:14 -07003732 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003733 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003734 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3735 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3736 }
3737
3738 @Override
3739 public void unregisterNetworkFactory(Messenger messenger) {
3740 enforceConnectivityInternalPermission();
3741 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3742 }
3743
3744 private void handleUnregisterNetworkFactory(Messenger messenger) {
3745 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3746 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003747 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003748 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003749 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003750 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003751 }
3752
Robert Greenwalt7b816022014-04-18 15:25:25 -07003753 /**
3754 * NetworkAgentInfo supporting a request by requestId.
3755 * These have already been vetted (their Capabilities satisfy the request)
3756 * and the are the highest scored network available.
3757 * the are keyed off the Requests requestId.
3758 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003759 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003760 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3761 new SparseArray<NetworkAgentInfo>();
3762
Paul Jensen31a94f42015-02-13 14:18:39 -05003763 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3764 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003765 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3766 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003767 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3768 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3769 // there may not be a strict 1:1 correlation between the two.
3770 @GuardedBy("mNetworkForNetId")
3771 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003772
Robert Greenwalt7b816022014-04-18 15:25:25 -07003773 // NetworkAgentInfo keyed off its connecting messenger
3774 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003775 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003776 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3777 new HashMap<Messenger, NetworkAgentInfo>();
3778
Paul Jensen2c311d62014-11-17 12:34:51 -05003779 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003780 private final NetworkRequest mDefaultRequest;
3781
Erik Klineda4bfa82015-04-30 12:58:40 +09003782 // Request used to optionally keep mobile data active even when higher
3783 // priority networks like Wi-Fi are active.
3784 private final NetworkRequest mDefaultMobileDataRequest;
3785
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003786 private NetworkAgentInfo getDefaultNetwork() {
3787 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3788 }
3789
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003790 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003791 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003792 }
3793
Paul Jensen31a94f42015-02-13 14:18:39 -05003794 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003795 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003796 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003797 enforceConnectivityInternalPermission();
3798
Paul Jensen2c311d62014-11-17 12:34:51 -05003799 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3800 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003801 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003802 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3803 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3804 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003805 synchronized (this) {
3806 nai.networkMonitor.systemReady = mSystemReady;
3807 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003808 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003809 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003810 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003811 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003812 }
3813
3814 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3815 if (VDBG) log("Got NetworkAgent Messenger");
3816 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003817 synchronized (mNetworkForNetId) {
3818 mNetworkForNetId.put(na.network.netId, na);
3819 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003820 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3821 NetworkInfo networkInfo = na.networkInfo;
3822 na.networkInfo = null;
3823 updateNetworkInfo(na, networkInfo);
3824 }
3825
3826 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3827 LinkProperties newLp = networkAgent.linkProperties;
3828 int netId = networkAgent.network.netId;
3829
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003830 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3831 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003832 if (networkAgent.clatd != null) {
3833 networkAgent.clatd.fixupLinkProperties(oldLp);
3834 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003835
Paul Jensen992f2522014-04-28 10:33:11 -04003836 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003837 updateMtu(newLp, oldLp);
3838 // TODO - figure out what to do for clat
3839// for (LinkProperties lp : newLp.getStackedLinks()) {
3840// updateMtu(lp, null);
3841// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003842 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003843
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003844 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3845 // In L, we used it only when the network had Internet access but provided no DNS servers.
3846 // For now, just disable it, and if disabling it doesn't break things, remove it.
3847 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3848 // NET_CAPABILITY_INTERNET);
3849 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003850 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003851 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3852
Paul Jensen3b759822014-05-13 11:44:01 -04003853 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003854 if (isDefaultNetwork(networkAgent)) {
3855 handleApplyDefaultProxy(newLp.getHttpProxy());
3856 } else {
3857 updateProxy(newLp, oldLp, networkAgent);
3858 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003859 // TODO - move this check to cover the whole function
3860 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003861 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003862 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3863 }
Paul Jensen3b759822014-05-13 11:44:01 -04003864 }
3865
Lorenzo Colitti95439462014-10-09 13:44:48 +09003866 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3867 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3868 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003869
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003870 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003871 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3872 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003873 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003874 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003875 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003876 }
Paul Jensen992f2522014-04-28 10:33:11 -04003877
3878 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3879 CompareResult<String> interfaceDiff = new CompareResult<String>();
3880 if (oldLp != null) {
3881 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3882 } else if (newLp != null) {
3883 interfaceDiff.added = newLp.getAllInterfaceNames();
3884 }
3885 for (String iface : interfaceDiff.added) {
3886 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003887 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003888 mNetd.addInterfaceToNetwork(iface, netId);
3889 } catch (Exception e) {
3890 loge("Exception adding interface: " + e);
3891 }
3892 }
3893 for (String iface : interfaceDiff.removed) {
3894 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003895 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003896 mNetd.removeInterfaceFromNetwork(iface, netId);
3897 } catch (Exception e) {
3898 loge("Exception removing interface: " + e);
3899 }
3900 }
3901 }
3902
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003903 /**
3904 * Have netd update routes from oldLp to newLp.
3905 * @return true if routes changed between oldLp and newLp
3906 */
3907 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003908 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3909 if (oldLp != null) {
3910 routeDiff = oldLp.compareAllRoutes(newLp);
3911 } else if (newLp != null) {
3912 routeDiff.added = newLp.getAllRoutes();
3913 }
3914
3915 // add routes before removing old in case it helps with continuous connectivity
3916
3917 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3918 for (RouteInfo route : routeDiff.added) {
3919 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003920 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003921 try {
3922 mNetd.addRoute(netId, route);
3923 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003924 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3925 loge("Exception in addRoute for non-gateway: " + e);
3926 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003927 }
3928 }
3929 for (RouteInfo route : routeDiff.added) {
3930 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003931 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003932 try {
3933 mNetd.addRoute(netId, route);
3934 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003935 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3936 loge("Exception in addRoute for gateway: " + e);
3937 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003938 }
3939 }
3940
3941 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003942 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003943 try {
3944 mNetd.removeRoute(netId, route);
3945 } catch (Exception e) {
3946 loge("Exception in removeRoute: " + e);
3947 }
3948 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003949 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003950 }
Erik Kline41368502015-06-17 13:19:54 +09003951
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003952 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3953 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003954 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09003955 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003956 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003957 dnses = new ArrayList();
3958 dnses.add(mDefaultDns);
3959 if (DBG) {
3960 loge("no dns provided for netId " + netId + ", so using defaults");
3961 }
3962 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003963 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003964 try {
3965 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3966 newLp.getDomains());
3967 } catch (Exception e) {
3968 loge("Exception in setDnsServersForNetwork: " + e);
3969 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003970 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003971 if (defaultNai != null && defaultNai.network.netId == netId) {
3972 setDefaultDnsSystemProperties(dnses);
3973 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003974 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003975 } else if (flush) {
3976 try {
3977 mNetd.flushNetworkDnsCache(netId);
3978 } catch (Exception e) {
3979 loge("Exception in flushNetworkDnsCache: " + e);
3980 }
3981 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003982 }
3983 }
3984
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003985 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3986 int last = 0;
3987 for (InetAddress dns : dnses) {
3988 ++last;
3989 String key = "net.dns" + last;
3990 String value = dns.getHostAddress();
3991 SystemProperties.set(key, value);
3992 }
3993 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3994 String key = "net.dns" + i;
3995 SystemProperties.set(key, "");
3996 }
3997 mNumDnsEntries = last;
3998 }
3999
Paul Jensen3d194ea2015-06-16 14:27:36 -04004000 /**
4001 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4002 * augmented with any stateful capabilities implied from {@code networkAgent}
4003 * (e.g., validated status and captive portal status).
4004 *
Paul Jensene0988542015-06-25 15:30:08 -04004005 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004006 * @param networkCapabilities the new network capabilities.
4007 */
Paul Jensene0988542015-06-25 15:30:08 -04004008 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004009 // Don't modify caller's NetworkCapabilities.
4010 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004011 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004012 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4013 } else {
4014 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4015 }
Paul Jensene0988542015-06-25 15:30:08 -04004016 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004017 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4018 } else {
4019 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4020 }
Paul Jensene0988542015-06-25 15:30:08 -04004021 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4022 final int oldScore = nai.getCurrentScore();
4023 synchronized (nai) {
4024 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004025 }
Paul Jensene0988542015-06-25 15:30:08 -04004026 rematchAllNetworksAndRequests(nai, oldScore);
4027 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004028 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004029 }
4030
Paul Jensenc8b9a742014-09-30 15:37:41 -04004031 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4032 for (int i = 0; i < nai.networkRequests.size(); i++) {
4033 NetworkRequest nr = nai.networkRequests.valueAt(i);
4034 // Don't send listening requests to factories. b/17393458
4035 if (!isRequest(nr)) continue;
4036 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4037 }
4038 }
4039
Robert Greenwalt7b816022014-04-18 15:25:25 -07004040 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4041 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004042 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004043 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4044 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004045 }
4046 }
4047
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004048 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4049 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004050 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004051 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004052 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4053 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004054 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004055 sendIntent(nri.mPendingIntent, intent);
4056 }
4057 // else not handled
4058 }
4059
4060 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4061 mPendingIntentWakeLock.acquire();
4062 try {
4063 if (DBG) log("Sending " + pendingIntent);
4064 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4065 } catch (PendingIntent.CanceledException e) {
4066 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4067 mPendingIntentWakeLock.release();
4068 releasePendingNetworkRequest(pendingIntent);
4069 }
4070 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4071 }
4072
4073 @Override
4074 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4075 String resultData, Bundle resultExtras) {
4076 if (DBG) log("Finished sending " + pendingIntent);
4077 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004078 // Release with a delay so the receiving client has an opportunity to put in its
4079 // own request.
4080 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004081 }
4082
Robert Greenwalt9258c642014-03-26 16:47:06 -07004083 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004084 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004085 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004086 Bundle bundle = new Bundle();
4087 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4088 new NetworkRequest(nri.request));
4089 Message msg = Message.obtain();
4090 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4091 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4092 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4093 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004094 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004095 case ConnectivityManager.CALLBACK_LOSING: {
4096 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4097 break;
4098 }
4099 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4100 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4101 new NetworkCapabilities(networkAgent.networkCapabilities));
4102 break;
4103 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004104 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004105 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4106 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004107 break;
4108 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004109 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004110 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004111 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004112 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004113 if (VDBG) {
4114 log("sending notification " + notifyTypeToName(notificationType) +
4115 " for " + nri.request);
4116 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004117 nri.messenger.send(msg);
4118 } catch (RemoteException e) {
4119 // may occur naturally in the race of binder death.
4120 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4121 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004122 }
4123
Paul Jensenc8b9a742014-09-30 15:37:41 -04004124 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4125 for (int i = 0; i < nai.networkRequests.size(); i++) {
4126 NetworkRequest nr = nai.networkRequests.valueAt(i);
4127 // Ignore listening requests.
4128 if (!isRequest(nr)) continue;
4129 loge("Dead network still had at least " + nr);
4130 break;
4131 }
4132 nai.asyncChannel.disconnect();
4133 }
4134
Robert Greenwalt7b816022014-04-18 15:25:25 -07004135 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4136 if (oldNetwork == null) {
4137 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4138 return;
4139 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004140 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4141 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004142 }
4143
Paul Jensen27b02b72014-07-14 12:03:33 -04004144 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004145 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004146 setupDataActivityTracking(newNetwork);
4147 try {
4148 mNetd.setDefaultNetId(newNetwork.network.netId);
4149 } catch (Exception e) {
4150 loge("Exception setting default network :" + e);
4151 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004152 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004153 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004154 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004155 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004156 }
4157
Paul Jensen2161a8e2014-09-11 11:00:39 -04004158 // Handles a network appearing or improving its score.
4159 //
4160 // - Evaluates all current NetworkRequests that can be
4161 // satisfied by newNetwork, and reassigns to newNetwork
4162 // any such requests for which newNetwork is the best.
4163 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004164 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004165 // needed. A network is needed if it is the best network for
4166 // one or more NetworkRequests, or if it is a VPN.
4167 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004168 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004169 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004170 //
4171 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4172 // networks that have no chance (i.e. even if validated)
4173 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004174 //
4175 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4176 // it does not remove NetworkRequests that other Networks could better satisfy.
4177 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4178 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4179 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004180 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004181 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004182 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4183 // performed to tear down unvalidated networks that have no chance (i.e. even if
4184 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004185 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004186 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004187 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004188 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004189 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004190 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004191 if (DBG) log("rematching " + newNetwork.name());
4192 // Find and migrate to this Network any NetworkRequests for
4193 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004195 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004196 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004197 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004198 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4199 if (newNetwork == currentNetwork) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004200 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004201 log("Network " + newNetwork.name() + " was already satisfying" +
4202 " request " + nri.request.requestId + ". No change.");
4203 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004204 keep = true;
4205 continue;
4206 }
4207
4208 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004209 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004210 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004211 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004212 // This is not a request, it's a callback listener.
4213 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004214 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004215 continue;
4216 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004217
Robert Greenwalt7b816022014-04-18 15:25:25 -07004218 // next check if it's better than any current network we're using for
4219 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004220 if (VDBG) {
4221 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004222 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4223 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004224 }
4225 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004226 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004227 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004228 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004229 currentNetwork.networkRequests.remove(nri.request.requestId);
4230 currentNetwork.networkLingered.add(nri.request);
4231 affectedNetworks.add(currentNetwork);
4232 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004233 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004234 }
Paul Jensen573a0352015-01-08 10:49:34 -05004235 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004236 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004237 if (!newNetwork.addRequest(nri.request)) {
4238 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4239 }
4240 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004241 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004242 // Tell NetworkFactories about the new score, so they can stop
4243 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004244 // TODO - this could get expensive if we have alot of requests for this
4245 // network. Think about if there is a way to reduce this. Push
4246 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004247 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004248 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004249 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004250 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004251 }
4252 }
4253 }
4254 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004255 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004256 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004257 if (nai.lingering) {
4258 // Already lingered. Nothing to do. This can only happen if "nai" is in
4259 // "affectedNetworks" twice. The reasoning being that to get added to
4260 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4261 // (i.e. not lingered) so it could have only been lingered by this loop.
4262 // unneeded(nai) will be false and we'll call unlinger() below which would
4263 // be bad, so handle it here.
4264 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004265 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004266 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004267 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004268 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004269 }
4270 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004271 if (keep) {
4272 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004273 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004274 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004275 synchronized (ConnectivityService.this) {
4276 // have a new default network, release the transition wakelock in
4277 // a second if it's held. The second pause is to allow apps
4278 // to reconnect over the new network
4279 if (mNetTransitionWakeLock.isHeld()) {
4280 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4281 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4282 mNetTransitionWakeLockSerialNumber, 0),
4283 1000);
4284 }
4285 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004286 }
4287
4288 // do this after the default net is switched, but
4289 // before LegacyTypeTracker sends legacy broadcasts
Paul Jensen3d911462015-06-12 06:40:24 -04004290 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
Robert Greenwalt152ed372014-12-17 17:19:53 -08004291
4292 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004293 // Maintain the illusion: since the legacy API only
4294 // understands one network at a time, we must pretend
4295 // that the current default network disconnected before
4296 // the new one connected.
4297 if (oldDefaultNetwork != null) {
4298 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004299 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004300 }
Paul Jensene0988542015-06-25 15:30:08 -04004301 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004302 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4303 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004304 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004305
4306 // Notify battery stats service about this network, both the normal
4307 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004308 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004309 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004310 final IBatteryStats bs = BatteryStatsService.getService();
4311 final int type = newNetwork.networkInfo.getType();
4312
4313 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4314 bs.noteNetworkInterfaceType(baseIface, type);
4315 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4316 final String stackedIface = stacked.getInterfaceName();
4317 bs.noteNetworkInterfaceType(stackedIface, type);
4318 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4319 }
4320 } catch (RemoteException ignored) {
4321 }
4322
Robert Greenwalt152ed372014-12-17 17:19:53 -08004323 // This has to happen after the notifyNetworkCallbacks as that tickles each
4324 // ConnectivityManager instance so that legacy requests correctly bind dns
4325 // requests to this network. The legacy users are listening for this bcast
4326 // and will generally do a dns request so they can ensureRouteToHost and if
4327 // they do that before the callbacks happen they'll use the default network.
4328 //
4329 // TODO: Is there still a race here? We send the broadcast
4330 // after sending the callback, but if the app can receive the
4331 // broadcast before the callback, it might still break.
4332 //
4333 // This *does* introduce a race where if the user uses the new api
4334 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4335 // they may get old info. Reverse this after the old startUsing api is removed.
4336 // This is on top of the multiple intent sequencing referenced in the todo above.
4337 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4338 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4339 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4340 // legacy type tracker filters out repeat adds
4341 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4342 }
4343 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004344
4345 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4346 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4347 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4348 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4349 if (newNetwork.isVPN()) {
4350 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4351 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004352 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004353 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4354 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004355 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004356 if (DBG) log("Reaping " + nai.name());
4357 teardownUnneededNetwork(nai);
4358 }
4359 }
4360 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004361 }
4362
Paul Jensen1c7ba022015-06-16 14:27:36 -04004363 /**
4364 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4365 * being disconnected.
4366 * @param changed If only one Network's score or capabilities have been modified since the last
4367 * time this function was called, pass this Network in this argument, otherwise pass
4368 * null.
4369 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4370 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4371 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4372 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4373 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004374 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004375 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004376 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4377 // to avoid the slowness. It is not simply enough to process just "changed", for
4378 // example in the case where "changed"'s score decreases and another network should begin
4379 // satifying a NetworkRequest that "changed" currently satisfies.
4380
4381 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4382 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4383 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004384 if (changed != null && oldScore < changed.getCurrentScore()) {
4385 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004386 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004387 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4388 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4389 // Rematch higher scoring networks first to prevent requests first matching a lower
4390 // scoring network and then a higher scoring network, which could produce multiple
4391 // callbacks and inadvertently unlinger networks.
4392 Arrays.sort(nais);
4393 for (NetworkAgentInfo nai : nais) {
4394 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004395 // Only reap the last time through the loop. Reaping before all rematching
4396 // is complete could incorrectly teardown a network that hasn't yet been
4397 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004398 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004399 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004400 }
4401 }
4402 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004403
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004404 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004405 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004406 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004407 // For now only update icons for default connection.
4408 // TODO: Update WiFi and cellular icons separately. b/17237507
4409 if (!isDefaultNetwork(nai)) return;
4410
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004411 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004412 // Don't repeat publish.
4413 if (newInetCondition == mDefaultInetConditionPublished) return;
4414
4415 mDefaultInetConditionPublished = newInetCondition;
4416 sendInetConditionBroadcast(nai.networkInfo);
4417 }
4418
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004419 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4420 if (mLockdownTracker != null) {
4421 if (nai != null && nai.isVPN()) {
4422 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4423 } else {
4424 mLockdownTracker.onNetworkInfoChanged();
4425 }
4426 }
4427 }
4428
Robert Greenwalt7b816022014-04-18 15:25:25 -07004429 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4430 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004431 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004432 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004433 synchronized (networkAgent) {
4434 oldInfo = networkAgent.networkInfo;
4435 networkAgent.networkInfo = newInfo;
4436 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004437 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004438
4439 if (oldInfo != null && oldInfo.getState() == state) {
4440 if (VDBG) log("ignoring duplicate network state non-change");
4441 return;
4442 }
4443 if (DBG) {
4444 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4445 (oldInfo == null ? "null" : oldInfo.getState()) +
4446 " to " + state);
4447 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004448
Paul Jenseneec75412014-08-04 12:21:19 -04004449 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004450 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004451 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004452 if (networkAgent.isVPN()) {
4453 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004454 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4455 (networkAgent.networkMisc == null ||
4456 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004457 } else {
4458 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4459 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004460 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004461 loge("Error creating network " + networkAgent.network.netId + ": "
4462 + e.getMessage());
4463 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004464 }
Paul Jenseneec75412014-08-04 12:21:19 -04004465 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004466 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004467 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004468
Paul Jensenca8f16a2014-05-09 12:47:55 -04004469 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004470 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004471
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004472 if (networkAgent.isVPN()) {
4473 // Temporarily disable the default proxy (not global).
4474 synchronized (mProxyLock) {
4475 if (!mDefaultProxyDisabled) {
4476 mDefaultProxyDisabled = true;
4477 if (mGlobalProxy == null && mDefaultProxy != null) {
4478 sendProxyBroadcast(null);
4479 }
4480 }
4481 }
4482 // TODO: support proxy per network.
4483 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004484
Paul Jensen2161a8e2014-09-11 11:00:39 -04004485 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004486 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004487
4488 // This has to happen after matching the requests, because callbacks are just requests.
4489 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004490 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004491 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004492 if (networkAgent.isVPN()) {
4493 synchronized (mProxyLock) {
4494 if (mDefaultProxyDisabled) {
4495 mDefaultProxyDisabled = false;
4496 if (mGlobalProxy == null && mDefaultProxy != null) {
4497 sendProxyBroadcast(mDefaultProxy);
4498 }
4499 }
4500 }
4501 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004502 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4503 state == NetworkInfo.State.SUSPENDED) {
4504 // going into or coming out of SUSPEND: rescore and notify
4505 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004506 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004507 }
4508 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4509 ConnectivityManager.CALLBACK_SUSPENDED :
4510 ConnectivityManager.CALLBACK_RESUMED));
4511 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004512 }
4513 }
4514
Robert Greenwaltac96c522014-06-03 16:43:57 -07004515 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4516 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004517 if (score < 0) {
4518 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4519 "). Bumping score to min of 0");
4520 score = 0;
4521 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004522
Paul Jensen2161a8e2014-09-11 11:00:39 -04004523 final int oldScore = nai.getCurrentScore();
4524 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004525
Paul Jensen85cf78e2015-06-25 13:25:07 -04004526 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004527
Paul Jensenc8b9a742014-09-30 15:37:41 -04004528 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004529 }
4530
Robert Greenwalt9258c642014-03-26 16:47:06 -07004531 // notify only this one new request of the current state
4532 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4533 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4534 // TODO - read state from monitor to decide what to send.
4535// if (nai.networkMonitor.isLingering()) {
4536// notifyType = NetworkCallbacks.LOSING;
4537// } else if (nai.networkMonitor.isEvaluating()) {
4538// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4539// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004540 if (nri.mPendingIntent == null) {
4541 callCallbackForRequest(nri, nai, notifyType);
4542 } else {
4543 sendPendingIntentForRequest(nri, nai, notifyType);
4544 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004545 }
4546
Robert Greenwalt8d482522015-06-24 13:23:42 -07004547 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004548 // The NetworkInfo we actually send out has no bearing on the real
4549 // state of affairs. For example, if the default connection is mobile,
4550 // and a request for HIPRI has just gone away, we need to pretend that
4551 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4552 // the state to DISCONNECTED, even though the network is of type MOBILE
4553 // and is still connected.
4554 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4555 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004556 if (state != DetailedState.DISCONNECTED) {
4557 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004558 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004559 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004560 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004561 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4562 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4563 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4564 if (info.isFailover()) {
4565 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4566 nai.networkInfo.setFailover(false);
4567 }
4568 if (info.getReason() != null) {
4569 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4570 }
4571 if (info.getExtraInfo() != null) {
4572 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4573 }
4574 NetworkAgentInfo newDefaultAgent = null;
4575 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004576 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004577 if (newDefaultAgent != null) {
4578 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4579 newDefaultAgent.networkInfo);
4580 } else {
4581 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4582 }
4583 }
4584 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4585 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004586 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004587 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004588 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004589 }
4590 }
4591 }
4592
Robert Greenwalt7b816022014-04-18 15:25:25 -07004593 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004594 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004595 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004596 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4597 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4598 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004599 if (nri.mPendingIntent == null) {
4600 callCallbackForRequest(nri, networkAgent, notifyType);
4601 } else {
4602 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4603 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004604 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004605 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004606
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004607 private String notifyTypeToName(int notifyType) {
4608 switch (notifyType) {
4609 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4610 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4611 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4612 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4613 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4614 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4615 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4616 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4617 }
4618 return "UNKNOWN";
4619 }
4620
Jeff Sharkey69736342014-12-08 14:50:12 -08004621 /**
4622 * Notify other system services that set of active ifaces has changed.
4623 */
4624 private void notifyIfacesChanged() {
4625 try {
4626 mStatsService.forceUpdateIfaces();
4627 } catch (Exception ignored) {
4628 }
4629 }
4630
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004631 @Override
4632 public boolean addVpnAddress(String address, int prefixLength) {
4633 throwIfLockdownEnabled();
4634 int user = UserHandle.getUserId(Binder.getCallingUid());
4635 synchronized (mVpns) {
4636 return mVpns.get(user).addAddress(address, prefixLength);
4637 }
4638 }
4639
4640 @Override
4641 public boolean removeVpnAddress(String address, int prefixLength) {
4642 throwIfLockdownEnabled();
4643 int user = UserHandle.getUserId(Binder.getCallingUid());
4644 synchronized (mVpns) {
4645 return mVpns.get(user).removeAddress(address, prefixLength);
4646 }
4647 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004648
4649 @Override
4650 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4651 throwIfLockdownEnabled();
4652 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004653 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004654 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004655 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004656 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004657 if (success) {
4658 notifyIfacesChanged();
4659 }
4660 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004661 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004662
4663 @Override
4664 public void factoryReset() {
4665 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004666
4667 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4668 return;
4669 }
4670
Robin Lee3b3dd942015-05-12 18:14:58 +01004671 final int userId = UserHandle.getCallingUserId();
4672
Stuart Scottf1fb3972015-04-02 18:00:02 -07004673 // Turn airplane mode off
4674 setAirplaneMode(false);
4675
Stuart Scotte3e314d2015-04-20 14:07:45 -07004676 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4677 // Untether
4678 for (String tether : getTetheredIfaces()) {
4679 untether(tether);
4680 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004681 }
4682
Stuart Scotte3e314d2015-04-20 14:07:45 -07004683 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4684 // Turn VPN off
4685 VpnConfig vpnConfig = getVpnConfig(userId);
4686 if (vpnConfig != null) {
4687 if (vpnConfig.legacy) {
4688 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4689 } else {
4690 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4691 // in the future without user intervention.
4692 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004693
Stuart Scotte3e314d2015-04-20 14:07:45 -07004694 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4695 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004696 }
4697 }
4698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004699}