blob: 76d2258e0b85888546e27720ce46ecf9ad6e3da9 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070036import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
43import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070046import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090047import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
50import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070051import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070052import android.net.INetworkPolicyListener;
53import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070054import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080055import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070056import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070057import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070058import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070059import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070060import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070062import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070063import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070064import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070065import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070066import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070067import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070068import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040069import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070070import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040071import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040072import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070074import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040075import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070077import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070078import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070079import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Looper;
81import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070082import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070083import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070084import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070085import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070086import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070087import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070089import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040090import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070092import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070093import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070094import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070095import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070096import android.util.LocalLog;
97import android.util.LocalLog.ReadOnlyLocalLog;
98import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080099import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700100import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500101import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700102import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700103import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400106import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400107import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700108import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700109import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700110import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700111import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800112import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700113import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700114import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700115import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700116import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700117import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700118import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400119import com.android.server.connectivity.DataConnectionStats;
Erik Kline379747a2015-06-05 17:47:34 +0900120import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900121import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700122import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400123import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400124import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700125import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800126import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700127import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700128import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700129import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700130import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700131import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700132
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700133import org.xmlpull.v1.XmlPullParser;
134import org.xmlpull.v1.XmlPullParserException;
135
136import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700138import java.io.FileNotFoundException;
139import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700140import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700142import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700143import java.net.InetAddress;
144import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700145import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700146import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700147import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700148import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700149import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700150import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500151import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700152import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700153import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700154import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700155import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
157/**
158 * @hide
159 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800160public class ConnectivityService extends IConnectivityManager.Stub
161 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700162 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700164 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700165 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Jake Hamby786e71a2014-02-06 14:43:50 -0800167 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700168
Jeff Sharkey899223b2012-08-04 15:24:58 -0700169 // TODO: create better separation between radio types and network types
170
Robert Greenwalt42acef32009-08-12 16:08:25 -0700171 // how long to wait before switching back to a radio's default network
172 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
173 // system property that can override the above value
174 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
175 "android.telephony.apn-restore";
176
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900177 // How long to wait before putting up a "This network doesn't have an Internet connection,
178 // connect anyway?" dialog after the user selects a network that doesn't validate.
179 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
180
Jeremy Joslin79294842014-12-03 17:15:28 -0800181 // How long to delay to removal of a pending intent based request.
182 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
183 private final int mReleasePendingIntentDelayMs;
184
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800185 private Tethering mTethering;
186
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700187 private final PermissionMonitor mPermissionMonitor;
188
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700189 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700190
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700191 @GuardedBy("mVpns")
192 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700193
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700194 private boolean mLockdownEnabled;
195 private LockdownVpnTracker mLockdownTracker;
196
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700197 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
198 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700199 /** Currently active network rules by UID. */
200 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700201 /** Set of ifaces that are costly. */
202 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700203
Erik Klineda4bfa82015-04-30 12:58:40 +0900204 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700206 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700207 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800209 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
211 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700212 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700214 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800215 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700216 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700217
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700218 private String mCurrentTcpBufferSizes;
219
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700220 private static final int ENABLED = 1;
221 private static final int DISABLED = 0;
222
Paul Jensenb10e37f2014-11-25 12:33:08 -0500223 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400224 // Tear down networks that have no chance (e.g. even if validated) of becoming
225 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500226 // all networks have been rematched against all NetworkRequests.
227 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400228 // Don't reap networks. This should be passed when some networks have not yet been
229 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500230 DONT_REAP
231 };
232
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700233 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700234 * used internally to change our mobile data enabled flag
235 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700236 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237
238 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700239 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700240 * from one net to another. Clear happens when we get a new
241 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
242 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700243 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700244 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700245
Robert Greenwalt434203a2010-10-11 16:00:27 -0700246 /**
247 * used internally to reload global proxy settings
248 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700249 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700250
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700251 /**
Wink Saville628b0852011-08-04 15:01:58 -0700252 * used internally to send a sticky broadcast delayed.
253 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700254 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700255
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700256 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400257 * PAC manager has received new port.
258 */
259 private static final int EVENT_PROXY_HAS_CHANGED = 16;
260
Robert Greenwalte049c232014-04-11 15:53:27 -0700261 /**
262 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700263 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700264 */
265 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
266
Robert Greenwalt7b816022014-04-18 15:25:25 -0700267 /**
268 * used internally when registering NetworkAgents
269 * obj = Messenger
270 */
271 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
272
Robert Greenwalt9258c642014-03-26 16:47:06 -0700273 /**
274 * used to add a network request
275 * includes a NetworkRequestInfo
276 */
277 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
278
279 /**
280 * indicates a timeout period is over - check if we had a network yet or not
281 * and if not, call the timeout calback (but leave the request live until they
282 * cancel it.
283 * includes a NetworkRequestInfo
284 */
285 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
286
287 /**
288 * used to add a network listener - no request
289 * includes a NetworkRequestInfo
290 */
291 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
292
293 /**
294 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400295 * arg1 = UID of caller
296 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700297 */
298 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
299
Robert Greenwalta67be032014-05-16 15:49:14 -0700300 /**
301 * used internally when registering NetworkFactories
302 * obj = Messenger
303 */
304 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
305
Robert Greenwalt27711812014-06-25 16:45:57 -0700306 /**
307 * used internally to expire a wakelock when transitioning
308 * from one net to another. Expire happens when we fail to find
309 * a new network (typically after 1 minute) -
310 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
311 * a replacement network.
312 */
313 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
314
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700315 /**
316 * Used internally to indicate the system is ready.
317 */
318 private static final int EVENT_SYSTEM_READY = 25;
319
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800320 /**
321 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400322 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800323 */
324 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
325
326 /**
327 * used to remove a pending intent and its associated network request.
328 * arg1 = UID of caller
329 * obj = PendingIntent
330 */
331 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
332
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900333 /**
334 * used to specify whether a network should be used even if unvalidated.
335 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
336 * arg2 = whether to remember this choice in the future (1 or 0)
337 * obj = network
338 */
339 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
340
341 /**
342 * used to ask the user to confirm a connection to an unvalidated network.
343 * obj = network
344 */
345 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700346
Erik Klineda4bfa82015-04-30 12:58:40 +0900347 /**
348 * used internally to (re)configure mobile data always-on settings.
349 */
350 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
351
Paul Jensen694f2b82015-06-17 14:15:39 -0400352 /**
353 * used to add a network listener with a pending intent
354 * obj = NetworkRequestInfo
355 */
356 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
357
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700358 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700359 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700360 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700361 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700362
Mike Lockwood0f79b542009-08-14 14:18:49 -0400363 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800364 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400365
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700366 private PowerManager.WakeLock mNetTransitionWakeLock;
367 private String mNetTransitionWakeLockCausedBy = "";
368 private int mNetTransitionWakeLockSerialNumber;
369 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800370 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700371
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700372 private InetAddress mDefaultDns;
373
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700374 // used in DBG mode to track inet condition reports
375 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
376 private ArrayList mInetLog;
377
Robert Greenwalt434203a2010-10-11 16:00:27 -0700378 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400379 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700380 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700381 private boolean mDefaultProxyDisabled = false;
382
Robert Greenwalt434203a2010-10-11 16:00:27 -0700383 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400384 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700385
Jason Monk602b2322013-07-03 17:04:33 -0400386 private PacManager mPacManager = null;
387
Erik Klineda4bfa82015-04-30 12:58:40 +0900388 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700389
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400390 private UserManager mUserManager;
391
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700392 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700393 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700394
Robert Greenwalt50393202011-06-21 17:26:14 -0700395 // the set of network types that can only be enabled by system/sig apps
396 List mProtectedNetworks;
397
John Spurlockbf991a82013-06-24 14:20:23 -0400398 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700399
Wink Savilleab9321d2013-06-29 21:10:57 -0700400 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400401
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700402 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
403 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700404 private final static int MAX_NET_ID = 65535;
405 private int mNextNetId = MIN_NET_ID;
406
Robert Greenwalt34524f02014-05-18 16:22:10 -0700407 // sequence number of NetworkRequests
408 private int mNextNetworkRequestId = 1;
409
Erik Kline7523eb32015-07-09 18:24:03 +0900410 // NetworkRequest activity String log entries.
411 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
412 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
413
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700414 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
415 private static final int MAX_VALIDATION_LOGS = 10;
416 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
417 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
418
419 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
420 synchronized(mValidationLogs) {
421 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
422 mValidationLogs.removeLast();
423 }
424 mValidationLogs.addFirst(new Pair(network, log));
425 }
426 }
427
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700428 /**
429 * Implements support for the legacy "one network per network type" model.
430 *
431 * We used to have a static array of NetworkStateTrackers, one for each
432 * network type, but that doesn't work any more now that we can have,
433 * for example, more that one wifi network. This class stores all the
434 * NetworkAgentInfo objects that support a given type, but the legacy
435 * API will only see the first one.
436 *
437 * It serves two main purposes:
438 *
439 * 1. Provide information about "the network for a given type" (since this
440 * API only supports one).
441 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
442 * the first network for a given type changes, or if the default network
443 * changes.
444 */
445 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900446
447 private static final boolean DBG = true;
448 private static final boolean VDBG = false;
449 private static final String TAG = "CSLegacyTypeTracker";
450
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700451 /**
452 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
453 * Each list holds references to all NetworkAgentInfos that are used to
454 * satisfy requests for that network type.
455 *
456 * This array is built out at startup such that an unsupported network
457 * doesn't get an ArrayList instance, making this a tristate:
458 * unsupported, supported but not active and active.
459 *
460 * The actual lists are populated when we scan the network types that
461 * are supported on this device.
462 */
463 private ArrayList<NetworkAgentInfo> mTypeLists[];
464
465 public LegacyTypeTracker() {
466 mTypeLists = (ArrayList<NetworkAgentInfo>[])
467 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
468 }
469
470 public void addSupportedType(int type) {
471 if (mTypeLists[type] != null) {
472 throw new IllegalStateException(
473 "legacy list for type " + type + "already initialized");
474 }
475 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
476 }
477
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700478 public boolean isTypeSupported(int type) {
479 return isNetworkTypeValid(type) && mTypeLists[type] != null;
480 }
481
482 public NetworkAgentInfo getNetworkForType(int type) {
483 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
484 return mTypeLists[type].get(0);
485 } else {
486 return null;
487 }
488 }
489
Robert Greenwalt8d482522015-06-24 13:23:42 -0700490 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900491 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900492 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700493 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900494 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900495 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900496 }
497 }
498
499 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700500 public void add(int type, NetworkAgentInfo nai) {
501 if (!isTypeSupported(type)) {
502 return; // Invalid network type.
503 }
504 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
505
506 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
507 if (list.contains(nai)) {
508 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
509 return;
510 }
511
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900512 list.add(nai);
513
514 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900515 final boolean isDefaultNetwork = isDefaultNetwork(nai);
516 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700517 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
518 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700519 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700520 }
521
Lorenzo Colittia793a672014-07-31 23:20:17 +0900522 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900523 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900524 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
525 if (list == null || list.isEmpty()) {
526 return;
527 }
528
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900529 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900530
531 if (!list.remove(nai)) {
532 return;
533 }
534
Robert Greenwalt8d482522015-06-24 13:23:42 -0700535 final DetailedState state = DetailedState.DISCONNECTED;
536
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900537 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700538 maybeLogBroadcast(nai, state, type, wasDefault);
539 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900540 }
541
542 if (!list.isEmpty() && wasFirstNetwork) {
543 if (DBG) log("Other network available for type " + type +
544 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900545 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700546 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
547 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900548 }
549 }
550
551 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900552 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
553 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700554 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900555 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700556 }
557 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700558
Robert Greenwalt8d482522015-06-24 13:23:42 -0700559 // send out another legacy broadcast - currently only used for suspend/unsuspend
560 // toggle
561 public void update(NetworkAgentInfo nai) {
562 final boolean isDefault = isDefaultNetwork(nai);
563 final DetailedState state = nai.networkInfo.getDetailedState();
564 for (int type = 0; type < mTypeLists.length; type++) {
565 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700566 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700567 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700568 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700569 maybeLogBroadcast(nai, state, type, isDefault);
570 sendLegacyNetworkBroadcast(nai, state, type);
571 }
572 }
573 }
574
Lorenzo Colittia793a672014-07-31 23:20:17 +0900575 private String naiToString(NetworkAgentInfo nai) {
576 String name = (nai != null) ? nai.name() : "null";
577 String state = (nai.networkInfo != null) ?
578 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
579 "???/???";
580 return name + " " + state;
581 }
582
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700583 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900584 pw.println("mLegacyTypeTracker:");
585 pw.increaseIndent();
586 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700587 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900588 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700589 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900590 pw.println();
591 pw.println("Current state:");
592 pw.increaseIndent();
593 for (int type = 0; type < mTypeLists.length; type++) {
594 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
595 for (NetworkAgentInfo nai : mTypeLists[type]) {
596 pw.println(type + " " + naiToString(nai));
597 }
598 }
599 pw.decreaseIndent();
600 pw.decreaseIndent();
601 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700602 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900603
604 // This class needs its own log method because it has a different TAG.
605 private void log(String s) {
606 Slog.d(TAG, s);
607 }
608
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700609 }
610 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
611
Jeff Sharkey899223b2012-08-04 15:24:58 -0700612 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700613 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800614 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800615
Erik Klineda4bfa82015-04-30 12:58:40 +0900616 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900617 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
618 new Binder(), NetworkRequestInfo.REQUEST);
619 mNetworkRequests.put(mDefaultRequest, defaultNRI);
620 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900621
622 mDefaultMobileDataRequest = createInternetRequestForTransport(
623 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700624
Wink Savillebb08caf2010-09-02 19:23:52 -0700625 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
626 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700627 mHandler = new InternalHandler(handlerThread.getLooper());
628 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700629
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800630 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800631 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
632 String id = Settings.Secure.getString(context.getContentResolver(),
633 Settings.Secure.ANDROID_ID);
634 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700635 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800636 SystemProperties.set("net.hostname", name);
637 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800638 }
639
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700640 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700641 String dns = Settings.Global.getString(context.getContentResolver(),
642 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700643 if (dns == null || dns.length() == 0) {
644 dns = context.getResources().getString(
645 com.android.internal.R.string.config_default_dns_server);
646 }
647 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800648 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
649 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800650 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700651 }
652
Jeremy Joslin79294842014-12-03 17:15:28 -0800653 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
654 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
655
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700656 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700657 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800658 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700659 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700660 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700661 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700662
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700663 try {
664 mPolicyManager.registerListener(mPolicyListener);
665 } catch (RemoteException e) {
666 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700667 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700668 }
669
670 final PowerManager powerManager = (PowerManager) context.getSystemService(
671 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700672 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
673 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
674 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800675 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700676
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700677 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700678
Wink Saville51f456f2013-04-23 14:26:51 -0700679 // TODO: What is the "correct" way to do determine if this is a wifi only device?
680 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
681 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700682 String[] naStrings = context.getResources().getStringArray(
683 com.android.internal.R.array.networkAttributes);
684 for (String naString : naStrings) {
685 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700686 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700687 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700688 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800689 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700690 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700691 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700692 }
Wink Saville51f456f2013-04-23 14:26:51 -0700693 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
694 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
695 n.type);
696 continue;
697 }
Wink Saville975c8482011-04-07 14:23:45 -0700698 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800699 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700700 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700701 continue;
702 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700703 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700704
Wink Saville975c8482011-04-07 14:23:45 -0700705 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700706 mNetworksDefined++;
707 } catch(Exception e) {
708 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700709 }
710 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700711
712 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
713 if (mNetConfigs[TYPE_VPN] == null) {
714 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
715 // don't need to add TYPE_VPN to mNetConfigs.
716 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
717 mNetworksDefined++; // used only in the log() statement below.
718 }
719
Wink Saville5e56bc52013-07-29 15:00:57 -0700720 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700721
Robert Greenwalt50393202011-06-21 17:26:14 -0700722 mProtectedNetworks = new ArrayList<Integer>();
723 int[] protectedNetworks = context.getResources().getIntArray(
724 com.android.internal.R.array.config_protectedNetworks);
725 for (int p : protectedNetworks) {
726 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
727 mProtectedNetworks.add(p);
728 } else {
729 if (DBG) loge("Ignoring protectedNetwork " + p);
730 }
731 }
732
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700733 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
734 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700735
Robert Greenwaltfab501672014-07-23 11:44:01 -0700736 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800737
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700738 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
739
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700740 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700741 IntentFilter intentFilter = new IntentFilter();
742 intentFilter.addAction(Intent.ACTION_USER_STARTING);
743 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
744 mContext.registerReceiverAsUser(
745 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900746
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700747 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700748 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700749 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700750 } catch (RemoteException e) {
751 loge("Error registering observer :" + e);
752 }
753
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700754 if (DBG) {
755 mInetLog = new ArrayList();
756 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700757
Erik Klineda4bfa82015-04-30 12:58:40 +0900758 mSettingsObserver = new SettingsObserver(mContext, mHandler);
759 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800760
John Spurlockbf991a82013-06-24 14:20:23 -0400761 mDataConnectionStats = new DataConnectionStats(mContext);
762 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400763
Jason Monkdecd2952013-10-10 14:02:51 -0400764 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700765
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400766 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700768
Erik Klineda4bfa82015-04-30 12:58:40 +0900769 private NetworkRequest createInternetRequestForTransport(int transportType) {
770 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900771 netCap.addCapability(NET_CAPABILITY_INTERNET);
772 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900773 if (transportType > -1) {
774 netCap.addTransportType(transportType);
775 }
776 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
777 }
778
779 private void handleMobileDataAlwaysOn() {
780 final boolean enable = (Settings.Global.getInt(
781 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
782 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
783 if (enable == isEnabled) {
784 return; // Nothing to do.
785 }
786
787 if (enable) {
788 handleRegisterNetworkRequest(new NetworkRequestInfo(
789 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
790 } else {
791 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
792 }
793 }
794
795 private void registerSettingsCallbacks() {
796 // Watch for global HTTP proxy changes.
797 mSettingsObserver.observe(
798 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
799 EVENT_APPLY_GLOBAL_HTTP_PROXY);
800
801 // Watch for whether or not to keep mobile data always on.
802 mSettingsObserver.observe(
803 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
804 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
805 }
806
Robert Greenwalt34524f02014-05-18 16:22:10 -0700807 private synchronized int nextNetworkRequestId() {
808 return mNextNetworkRequestId++;
809 }
810
Paul Jensen67b0b072015-06-10 11:22:17 -0400811 @VisibleForTesting
812 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400813 synchronized (mNetworkForNetId) {
814 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
815 int netId = mNextNetId;
816 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
817 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500818 if (!mNetIdInUse.get(netId)) {
819 mNetIdInUse.put(netId, true);
820 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400821 }
822 }
823 }
824 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700825 }
826
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800827 private NetworkState getFilteredNetworkState(int networkType, int uid) {
828 NetworkInfo info = null;
829 LinkProperties lp = null;
830 NetworkCapabilities nc = null;
831 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800832 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800833
834 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
835 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
836 if (nai != null) {
837 synchronized (nai) {
838 info = new NetworkInfo(nai.networkInfo);
839 lp = new LinkProperties(nai.linkProperties);
840 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400841 // Network objects are outwardly immutable so there is no point to duplicating.
842 // Duplicating also precludes sharing socket factories and connection pools.
843 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800844 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800845 }
846 info.setType(networkType);
847 } else {
848 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
849 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
850 info.setIsAvailable(true);
851 lp = new LinkProperties();
852 nc = new NetworkCapabilities();
853 network = null;
854 }
855 info = getFilteredNetworkInfo(info, lp, uid);
856 }
857
Jeff Sharkey32566012014-12-02 18:30:14 -0800858 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400859 }
860
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800861 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
862 if (network == null) {
863 return null;
864 }
865 synchronized (mNetworkForNetId) {
866 return mNetworkForNetId.get(network.netId);
867 }
868 };
869
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900870 private Network[] getVpnUnderlyingNetworks(int uid) {
871 if (!mLockdownEnabled) {
872 int user = UserHandle.getUserId(uid);
873 synchronized (mVpns) {
874 Vpn vpn = mVpns.get(user);
875 if (vpn != null && vpn.appliesToUid(uid)) {
876 return vpn.getUnderlyingNetworks();
877 }
878 }
879 }
880 return null;
881 }
882
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800883 private NetworkState getUnfilteredActiveNetworkState(int uid) {
884 NetworkInfo info = null;
885 LinkProperties lp = null;
886 NetworkCapabilities nc = null;
887 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800888 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800889
Paul Jensen85cf78e2015-06-25 13:25:07 -0400890 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800891
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900892 final Network[] networks = getVpnUnderlyingNetworks(uid);
893 if (networks != null) {
894 // getUnderlyingNetworks() returns:
895 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
896 // empty array => the VPN explicitly said "no default network".
897 // non-empty array => the VPN specified one or more default networks; we use the
898 // first one.
899 if (networks.length > 0) {
900 nai = getNetworkAgentInfoForNetwork(networks[0]);
901 } else {
902 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800903 }
904 }
905
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800906 if (nai != null) {
907 synchronized (nai) {
908 info = new NetworkInfo(nai.networkInfo);
909 lp = new LinkProperties(nai.linkProperties);
910 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400911 // Network objects are outwardly immutable so there is no point to duplicating.
912 // Duplicating also precludes sharing socket factories and connection pools.
913 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800914 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800915 }
916 }
917
Jeff Sharkey32566012014-12-02 18:30:14 -0800918 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400919 }
920
921 /**
922 * Check if UID should be blocked from using the network with the given LinkProperties.
923 */
924 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700925 final boolean networkCostly;
926 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700927
Robert Greenwalt12e67352014-05-13 21:41:06 -0700928 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700929 synchronized (mRulesLock) {
930 networkCostly = mMeteredIfaces.contains(iface);
931 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700932 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700933
Amith Yamasani15e472352015-04-24 19:06:07 -0700934 if ((uidRules & RULE_REJECT_ALL) != 0
935 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700936 return true;
937 }
938
939 // no restrictive rules; network is visible
940 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700941 }
942
943 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700944 * Return a filtered {@link NetworkInfo}, potentially marked
945 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800946 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700947 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800948 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
949 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400950 // network is blocked; clone and override state
951 info = new NetworkInfo(info);
952 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900953 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900954 log("returning Blocked NetworkInfo for ifname=" +
955 lp.getInterfaceName() + ", uid=" + uid);
956 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700957 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800958 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700959 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900960 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700961 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700962 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700963 }
964
965 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 * Return NetworkInfo for the active (i.e., connected) network interface.
967 * It is assumed that at most one network is active at a time. If more
968 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700969 * @return the info for the active network, or {@code null} if none is
970 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700972 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700974 enforceAccessPermission();
975 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800976 NetworkState state = getUnfilteredActiveNetworkState(uid);
977 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 }
979
Paul Jensen31a94f42015-02-13 14:18:39 -0500980 @Override
981 public Network getActiveNetwork() {
982 enforceAccessPermission();
983 final int uid = Binder.getCallingUid();
984 final int user = UserHandle.getUserId(uid);
985 int vpnNetId = NETID_UNSET;
986 synchronized (mVpns) {
987 final Vpn vpn = mVpns.get(user);
988 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
989 }
990 NetworkAgentInfo nai;
991 if (vpnNetId != NETID_UNSET) {
992 synchronized (mNetworkForNetId) {
993 nai = mNetworkForNetId.get(vpnNetId);
994 }
995 if (nai != null) return nai.network;
996 }
997 nai = getDefaultNetwork();
998 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
999 return nai != null ? nai.network : null;
1000 }
1001
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001002 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1003 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001004 final int uid = Binder.getCallingUid();
1005 NetworkState state = getUnfilteredActiveNetworkState(uid);
1006 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001007 }
1008
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001009 @Override
1010 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1011 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001012 NetworkState state = getUnfilteredActiveNetworkState(uid);
1013 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001014 }
1015
1016 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 public NetworkInfo getNetworkInfo(int networkType) {
1018 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001020 if (getVpnUnderlyingNetworks(uid) != null) {
1021 // A VPN is active, so we may need to return one of its underlying networks. This
1022 // information is not available in LegacyTypeTracker, so we have to get it from
1023 // getUnfilteredActiveNetworkState.
1024 NetworkState state = getUnfilteredActiveNetworkState(uid);
1025 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1026 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1027 }
1028 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001029 NetworkState state = getFilteredNetworkState(networkType, uid);
1030 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
1032
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001033 @Override
1034 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1035 enforceAccessPermission();
1036 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001037 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001038 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1039 if (nai != null) {
1040 synchronized (nai) {
1041 info = new NetworkInfo(nai.networkInfo);
1042 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001043 }
1044 }
1045 return info;
1046 }
1047
1048 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 public NetworkInfo[] getAllNetworkInfo() {
1050 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001051 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001052 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1053 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001054 NetworkInfo info = getNetworkInfo(networkType);
1055 if (info != null) {
1056 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001059 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 }
1061
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001062 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001063 public Network getNetworkForType(int networkType) {
1064 enforceAccessPermission();
1065 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001066 NetworkState state = getFilteredNetworkState(networkType, uid);
1067 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1068 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001069 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001070 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001071 }
1072
1073 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001074 public Network[] getAllNetworks() {
1075 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001076 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001077 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001078 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001079 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001080 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001081 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001082 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001083 }
1084
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001085 @Override
1086 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1087 // The basic principle is: if an app's traffic could possibly go over a
1088 // network, without the app doing anything multinetwork-specific,
1089 // (hence, by "default"), then include that network's capabilities in
1090 // the array.
1091 //
1092 // In the normal case, app traffic only goes over the system's default
1093 // network connection, so that's the only network returned.
1094 //
1095 // With a VPN in force, some app traffic may go into the VPN, and thus
1096 // over whatever underlying networks the VPN specifies, while other app
1097 // traffic may go over the system default network (e.g.: a split-tunnel
1098 // VPN, or an app disallowed by the VPN), so the set of networks
1099 // returned includes the VPN's underlying networks and the system
1100 // default.
1101 enforceAccessPermission();
1102
1103 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1104
1105 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001106 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001107 if (nc != null) {
1108 result.put(nai.network, nc);
1109 }
1110
1111 if (!mLockdownEnabled) {
1112 synchronized (mVpns) {
1113 Vpn vpn = mVpns.get(userId);
1114 if (vpn != null) {
1115 Network[] networks = vpn.getUnderlyingNetworks();
1116 if (networks != null) {
1117 for (Network network : networks) {
1118 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001119 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001120 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001121 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001122 }
1123 }
1124 }
1125 }
1126 }
1127 }
1128
1129 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1130 out = result.values().toArray(out);
1131 return out;
1132 }
1133
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001134 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001135 public boolean isNetworkSupported(int networkType) {
1136 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001137 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001138 }
1139
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001140 /**
1141 * Return LinkProperties for the active (i.e., connected) default
1142 * network interface. It is assumed that at most one default network
1143 * is active at a time. If more than one is active, it is indeterminate
1144 * which will be returned.
1145 * @return the ip properties for the active network, or {@code null} if
1146 * none is active
1147 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001148 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001149 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001150 enforceAccessPermission();
1151 final int uid = Binder.getCallingUid();
1152 NetworkState state = getUnfilteredActiveNetworkState(uid);
1153 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001154 }
1155
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001156 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001157 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001158 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001159 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1160 if (nai != null) {
1161 synchronized (nai) {
1162 return new LinkProperties(nai.linkProperties);
1163 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001164 }
1165 return null;
1166 }
1167
Robert Greenwalt12e67352014-05-13 21:41:06 -07001168 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001169 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001170 public LinkProperties getLinkProperties(Network network) {
1171 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001173 if (nai != null) {
1174 synchronized (nai) {
1175 return new LinkProperties(nai.linkProperties);
1176 }
1177 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001178 return null;
1179 }
1180
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001181 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001182 if (nai != null) {
1183 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001184 if (nai.networkCapabilities != null) {
1185 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001186 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001187 }
1188 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001189 return null;
1190 }
1191
1192 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001193 public NetworkCapabilities getNetworkCapabilities(Network network) {
1194 enforceAccessPermission();
1195 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1196 }
1197
1198 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001199 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001200 // Require internal since we're handing out IMSI details
1201 enforceConnectivityInternalPermission();
1202
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001203 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001204 for (Network network : getAllNetworks()) {
1205 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1206 if (nai != null) {
1207 synchronized (nai) {
1208 final String subscriberId = (nai.networkMisc != null)
1209 ? nai.networkMisc.subscriberId : null;
1210 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1211 nai.networkCapabilities, network, subscriberId, null));
1212 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001213 }
1214 }
1215 return result.toArray(new NetworkState[result.size()]);
1216 }
1217
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001218 @Override
1219 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1220 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001221 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001222 final long token = Binder.clearCallingIdentity();
1223 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001224 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1225 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001226 try {
1227 return mPolicyManager.getNetworkQuotaInfo(state);
1228 } catch (RemoteException e) {
1229 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001230 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001231 return null;
1232 } finally {
1233 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001234 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001235 }
1236
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001237 @Override
1238 public boolean isActiveNetworkMetered() {
1239 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001240 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001241 final long token = Binder.clearCallingIdentity();
1242 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001244 } finally {
1245 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001246 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001247 }
1248
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001249 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1250 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1251 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001252 try {
1253 return mPolicyManager.isNetworkMetered(state);
1254 } catch (RemoteException e) {
1255 }
1256 }
1257 return false;
1258 }
1259
Jeff Sharkey216c1812012-08-05 14:29:23 -07001260 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1261 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001262 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001263 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001264 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001265 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001266 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001267
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001268 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 * Ensure that a network route exists to deliver traffic to the specified
1270 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001271 * @param networkType the type of the network over which traffic to the
1272 * specified host is to be routed
1273 * @param hostAddress the IP address of the host to which the route is
1274 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 * @return {@code true} on success, {@code false} on failure
1276 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001277 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001279 if (mProtectedNetworks.contains(networkType)) {
1280 enforceConnectivityInternalPermission();
1281 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001282
Chad Brubakerc0234532014-02-14 13:24:29 -08001283 InetAddress addr;
1284 try {
1285 addr = InetAddress.getByAddress(hostAddress);
1286 } catch (UnknownHostException e) {
1287 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1288 return false;
1289 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001292 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 return false;
1294 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001295
1296 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1297 if (nai == null) {
1298 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1299 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1300 } else {
1301 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1302 }
1303 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001304 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001305
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001306 DetailedState netState;
1307 synchronized (nai) {
1308 netState = nai.networkInfo.getDetailedState();
1309 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001310
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001311 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001312 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001313 log("requestRouteToHostAddress on down network "
1314 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001315 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001316 }
1317 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001319
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001320 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001321 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001322 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001323 LinkProperties lp;
1324 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001325 synchronized (nai) {
1326 lp = nai.linkProperties;
1327 netId = nai.network.netId;
1328 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001329 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001330 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1331 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001332 } finally {
1333 Binder.restoreCallingIdentity(token);
1334 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001335 }
1336
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001337 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001338 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001339 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001340 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001341 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001342 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001343 if (bestRoute.getGateway().equals(addr)) {
1344 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001345 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001346 } else {
1347 // if we will connect to this through another route, add a direct route
1348 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001349 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001350 }
1351 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001352 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001353 try {
1354 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1355 } catch (Exception e) {
1356 // never crash - catch them all
1357 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001358 return false;
1359 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001360 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 }
1362
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001363 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1364 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001365 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001366 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001367 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001368 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001369 }
1370
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001371 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001372 // skip update when we've already applied rules
1373 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1374 if (oldRules == uidRules) return;
1375
1376 mUidRules.put(uid, uidRules);
1377 }
1378
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001379 // TODO: notify UID when it has requested targeted updates
1380 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001381
1382 @Override
1383 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001384 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001385 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001386 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001387 }
1388
1389 synchronized (mRulesLock) {
1390 mMeteredIfaces.clear();
1391 for (String iface : meteredIfaces) {
1392 mMeteredIfaces.add(iface);
1393 }
1394 }
1395 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001396
1397 @Override
1398 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1399 // caller is NPMS, since we only register with them
1400 if (LOGD_RULES) {
1401 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1402 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001403 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001404 };
1405
Robin Lee3b3dd942015-05-12 18:14:58 +01001406 /**
1407 * Require that the caller is either in the same user or has appropriate permission to interact
1408 * across users.
1409 *
1410 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1411 */
1412 private void enforceCrossUserPermission(int userId) {
1413 if (userId == UserHandle.getCallingUserId()) {
1414 // Not a cross-user call.
1415 return;
1416 }
1417 mContext.enforceCallingOrSelfPermission(
1418 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1419 "ConnectivityService");
1420 }
1421
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001422 private void enforceInternetPermission() {
1423 mContext.enforceCallingOrSelfPermission(
1424 android.Manifest.permission.INTERNET,
1425 "ConnectivityService");
1426 }
1427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001429 mContext.enforceCallingOrSelfPermission(
1430 android.Manifest.permission.ACCESS_NETWORK_STATE,
1431 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
1433
1434 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001435 mContext.enforceCallingOrSelfPermission(
1436 android.Manifest.permission.CHANGE_NETWORK_STATE,
1437 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001440 private void enforceTetherAccessPermission() {
1441 mContext.enforceCallingOrSelfPermission(
1442 android.Manifest.permission.ACCESS_NETWORK_STATE,
1443 "ConnectivityService");
1444 }
1445
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001446 private void enforceConnectivityInternalPermission() {
1447 mContext.enforceCallingOrSelfPermission(
1448 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1449 "ConnectivityService");
1450 }
1451
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001452 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001453 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001454 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001455 }
1456
1457 private void sendInetConditionBroadcast(NetworkInfo info) {
1458 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1459 }
1460
Wink Saville628b0852011-08-04 15:01:58 -07001461 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001462 if (mLockdownTracker != null) {
1463 info = mLockdownTracker.augmentNetworkInfo(info);
1464 }
1465
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001466 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001467 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001468 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 if (info.isFailover()) {
1470 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1471 info.setFailover(false);
1472 }
1473 if (info.getReason() != null) {
1474 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1475 }
1476 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001477 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1478 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001480 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001481 return intent;
1482 }
1483
1484 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1485 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1486 }
1487
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001488 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001489 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1490 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1491 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001492 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001493 final long ident = Binder.clearCallingIdentity();
1494 try {
1495 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1496 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1497 } finally {
1498 Binder.restoreCallingIdentity(ident);
1499 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001500 }
1501
Mike Lockwood0f79b542009-08-14 14:18:49 -04001502 private void sendStickyBroadcast(Intent intent) {
1503 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001504 if (!mSystemReady) {
1505 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001506 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001507 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001508 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001509 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001510 }
1511
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001512 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001513 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1514 final IBatteryStats bs = BatteryStatsService.getService();
1515 try {
1516 NetworkInfo ni = intent.getParcelableExtra(
1517 ConnectivityManager.EXTRA_NETWORK_INFO);
1518 bs.noteConnectivityChanged(intent.getIntExtra(
1519 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1520 ni != null ? ni.getState().toString() : "?");
1521 } catch (RemoteException e) {
1522 }
1523 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001524 try {
1525 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1526 } finally {
1527 Binder.restoreCallingIdentity(ident);
1528 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001529 }
1530 }
1531
1532 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001533 loadGlobalProxy();
1534
Mike Lockwood0f79b542009-08-14 14:18:49 -04001535 synchronized(this) {
1536 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001537 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001538 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001539 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001540 }
1541 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001542 // load the global proxy at startup
1543 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001544
1545 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1546 // for user to unlock device.
1547 if (!updateLockdownVpn()) {
1548 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1549 mContext.registerReceiver(mUserPresentReceiver, filter);
1550 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001551
Erik Klineda4bfa82015-04-30 12:58:40 +09001552 // Configure whether mobile data is always on.
1553 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1554
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001555 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001556
1557 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001560 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1561 @Override
1562 public void onReceive(Context context, Intent intent) {
1563 // Try creating lockdown tracker, since user present usually means
1564 // unlocked keystore.
1565 if (updateLockdownVpn()) {
1566 mContext.unregisterReceiver(this);
1567 }
1568 }
1569 };
1570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001572 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001573 *
1574 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001575 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001576 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001577 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1578 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001579
1580 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001581 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001582
Robert Greenwalt7b816022014-04-18 15:25:25 -07001583 if (networkAgent.networkCapabilities.hasTransport(
1584 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001585 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1586 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001587 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001588 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001589 } else if (networkAgent.networkCapabilities.hasTransport(
1590 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001591 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1592 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001593 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001594 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001595 } else {
1596 // do not track any other networks
1597 timeout = 0;
1598 }
1599
Robert Greenwalt7b816022014-04-18 15:25:25 -07001600 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001601 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001602 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001603 } catch (Exception e) {
1604 // You shall not crash!
1605 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001606 }
1607 }
1608 }
1609
1610 /**
1611 * Remove data activity tracking when network disconnects.
1612 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001613 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1614 final String iface = networkAgent.linkProperties.getInterfaceName();
1615 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001616
Robert Greenwalt7b816022014-04-18 15:25:25 -07001617 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1618 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001619 try {
1620 // the call fails silently if no idletimer setup for this interface
1621 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001622 } catch (Exception e) {
1623 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001624 }
1625 }
1626 }
1627
1628 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001629 * Reads the network specific MTU size from reources.
1630 * and set it on it's iface.
1631 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001632 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1633 final String iface = newLp.getInterfaceName();
1634 final int mtu = newLp.getMtu();
1635 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1636 if (VDBG) log("identical MTU - not setting");
1637 return;
1638 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001639
Robert Greenwalt43074032014-08-15 17:53:05 -07001640 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001641 loge("Unexpected mtu value: " + mtu + ", " + iface);
1642 return;
1643 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001644
w1997615afd812014-08-05 15:18:11 -07001645 // Cannot set MTU without interface name
1646 if (TextUtils.isEmpty(iface)) {
1647 loge("Setting MTU size with null iface.");
1648 return;
1649 }
1650
Robert Greenwalt7b816022014-04-18 15:25:25 -07001651 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001652 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001653 mNetd.setMtu(iface, mtu);
1654 } catch (Exception e) {
1655 Slog.e(TAG, "exception in setMtu()" + e);
1656 }
1657 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001658
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001659 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001660 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1661
1662 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001663 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001664 protected int getDefaultTcpRwnd() {
1665 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1666 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001667
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001668 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1669 if (isDefaultNetwork(nai) == false) {
1670 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001671 }
1672
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001673 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1674 String[] values = null;
1675 if (tcpBufferSizes != null) {
1676 values = tcpBufferSizes.split(",");
1677 }
1678
1679 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001680 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001681 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1682 values = tcpBufferSizes.split(",");
1683 }
1684
1685 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1686
1687 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001688 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001689
1690 final String prefix = "/sys/kernel/ipv4/tcp_";
1691 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1692 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1693 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1694 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1695 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1696 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1697 mCurrentTcpBufferSizes = tcpBufferSizes;
1698 } catch (IOException e) {
1699 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001700 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001701
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001702 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001703 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001704 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1705 if (rwndValue != 0) {
1706 SystemProperties.set(sysctlKey, rwndValue.toString());
1707 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001708 }
1709
Mattias Falk8b47b362011-08-23 14:15:13 +02001710 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001711 /*
1712 * Tell the VMs to toss their DNS caches
1713 */
1714 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1715 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001716 /*
1717 * Connectivity events can happen before boot has completed ...
1718 */
1719 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001720 final long ident = Binder.clearCallingIdentity();
1721 try {
1722 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1723 } finally {
1724 Binder.restoreCallingIdentity(ident);
1725 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001726 }
1727
Robert Greenwalt562cc542014-05-15 18:07:26 -07001728 @Override
1729 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001730 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1731 NETWORK_RESTORE_DELAY_PROP_NAME);
1732 if(restoreDefaultNetworkDelayStr != null &&
1733 restoreDefaultNetworkDelayStr.length() != 0) {
1734 try {
1735 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1736 } catch (NumberFormatException e) {
1737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001739 // if the system property isn't set, use the value for the apn type
1740 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1741
1742 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1743 (mNetConfigs[networkType] != null)) {
1744 ret = mNetConfigs[networkType].restoreTime;
1745 }
1746 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
1748
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001749 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001750 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001751 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001752 }
1753 return false;
1754 }
1755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001757 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1758 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001759 if (mContext.checkCallingOrSelfPermission(
1760 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001762 pw.println("Permission Denial: can't dump ConnectivityService " +
1763 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1764 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 return;
1766 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001767
Erik Kline379747a2015-06-05 17:47:34 +09001768 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001769 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001770 final long DIAG_TIME_MS = 5000;
1771 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1772 // Start gathering diagnostic information.
1773 netDiags.add(new NetworkDiagnostics(
1774 nai.network,
Lorenzo Colitti87cfc702015-07-27 16:35:33 +09001775 new LinkProperties(nai.linkProperties), // Must be a copy.
Erik Kline379747a2015-06-05 17:47:34 +09001776 DIAG_TIME_MS));
1777 }
1778
1779 for (NetworkDiagnostics netDiag : netDiags) {
1780 pw.println();
1781 netDiag.waitForMeasurements();
1782 netDiag.dump(pw);
1783 }
1784
1785 return;
1786 }
1787
Lorenzo Colittie3805462015-06-03 11:18:24 +09001788 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001789 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001790 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001791 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001792 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001793 pw.println();
1794
Paul Jensen85cf78e2015-06-25 13:25:07 -04001795 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001796 pw.print("Active default network: ");
1797 if (defaultNai == null) {
1798 pw.println("none");
1799 } else {
1800 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001802 pw.println();
1803
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001804 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001805 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001806 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1807 pw.println(nai.toString());
1808 pw.increaseIndent();
1809 pw.println("Requests:");
1810 pw.increaseIndent();
1811 for (int i = 0; i < nai.networkRequests.size(); i++) {
1812 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001813 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001814 pw.decreaseIndent();
1815 pw.println("Lingered:");
1816 pw.increaseIndent();
1817 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1818 pw.decreaseIndent();
1819 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001820 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001821 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001822 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001823
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001824 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001825 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001826 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1827 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001828 }
1829 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001830 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001831
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001832 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001833
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001834 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001835 pw.print("mNetTransitionWakeLock: currently " +
1836 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1837 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1838 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1839 } else {
1840 pw.println(", last requested never");
1841 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001842 }
1843 pw.println();
1844
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001845 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001846
Lorenzo Colittie3805462015-06-03 11:18:24 +09001847 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001848 pw.println();
1849 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001850 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001851 for(int i = 0; i < mInetLog.size(); i++) {
1852 pw.println(mInetLog.get(i));
1853 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001854 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001855 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001856
1857 if (argsContain(args, "--short") == false) {
1858 pw.println();
1859 synchronized (mValidationLogs) {
1860 pw.println("mValidationLogs (most recent first):");
1861 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1862 pw.println(p.first);
1863 pw.increaseIndent();
1864 p.second.dump(fd, pw, args);
1865 pw.decreaseIndent();
1866 }
1867 }
Erik Kline7523eb32015-07-09 18:24:03 +09001868
1869 pw.println();
1870 pw.println("mNetworkRequestInfoLogs (most recent first):");
1871 pw.increaseIndent();
1872 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1873 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 }
1876
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001877 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001878 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001879 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001880 if (officialNai != null && officialNai.equals(nai)) return true;
1881 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001882 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001883 " - " + nai);
1884 }
1885 return false;
1886 }
1887
Paul Jensenc8b9a742014-09-30 15:37:41 -04001888 private boolean isRequest(NetworkRequest request) {
1889 return mNetworkRequests.get(request).isRequest;
1890 }
1891
Robert Greenwalt42acef32009-08-12 16:08:25 -07001892 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001893 private class NetworkStateTrackerHandler extends Handler {
1894 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001895 super(looper);
1896 }
1897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 @Override
1899 public void handleMessage(Message msg) {
1900 NetworkInfo info;
1901 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001902 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001903 handleAsyncChannelHalfConnect(msg);
1904 break;
1905 }
1906 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1907 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1908 if (nai != null) nai.asyncChannel.disconnect();
1909 break;
1910 }
1911 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1912 handleAsyncChannelDisconnected(msg);
1913 break;
1914 }
1915 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1916 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1917 if (nai == null) {
1918 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1919 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001920 final NetworkCapabilities networkCapabilities =
1921 (NetworkCapabilities)msg.obj;
1922 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1923 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1924 Slog.wtf(TAG, "BUG: " + nai + " has stateful capability.");
1925 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001926 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001927 }
1928 break;
1929 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001930 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1931 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1932 if (nai == null) {
1933 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1934 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001935 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001936 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001937 "; created=" + nai.created);
1938 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001939 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001940 synchronized (nai) {
1941 nai.linkProperties = (LinkProperties)msg.obj;
1942 }
Paul Jenseneec75412014-08-04 12:21:19 -04001943 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001944 }
1945 break;
1946 }
1947 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1948 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1949 if (nai == null) {
1950 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1951 break;
1952 }
1953 info = (NetworkInfo) msg.obj;
1954 updateNetworkInfo(nai, info);
1955 break;
1956 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001957 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1958 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1959 if (nai == null) {
1960 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1961 break;
1962 }
1963 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001964 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001965 break;
1966 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001967 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1968 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1969 if (nai == null) {
1970 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1971 break;
1972 }
1973 try {
1974 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001975 } catch (Exception e) {
1976 // Never crash!
1977 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001978 }
1979 break;
1980 }
1981 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1982 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1983 if (nai == null) {
1984 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1985 break;
1986 }
1987 try {
1988 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001989 } catch (Exception e) {
1990 // Never crash!
1991 loge("Exception in removeVpnUidRanges: " + e);
1992 }
1993 break;
1994 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001995 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1996 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1997 if (nai == null) {
1998 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1999 break;
2000 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002001 if (nai.created && !nai.networkMisc.explicitlySelected) {
2002 loge("ERROR: created network explicitly selected.");
2003 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002004 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002005 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002006 break;
2007 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002008 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002009 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002010 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2011 final boolean valid =
2012 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002013 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2014 if (valid != nai.lastValidated) {
2015 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002016 nai.lastValidated = valid;
2017 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002018 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002019 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2020 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002021 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002022 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002023 // Let the NetworkAgent know the state of its network
2024 nai.asyncChannel.sendMessage(
2025 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2026 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2027 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002028 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002029 break;
2030 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002031 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002032 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002033 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2034 handleLingerComplete(nai);
2035 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002036 break;
2037 }
Paul Jensen869868be2014-05-15 10:33:05 -04002038 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002039 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002040 final boolean visible = (msg.arg1 != 0);
2041 final NetworkAgentInfo nai;
2042 synchronized (mNetworkForNetId) {
2043 nai = mNetworkForNetId.get(netId);
2044 }
2045 // If captive portal status has changed, update capabilities.
2046 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2047 nai.lastCaptivePortalDetected = visible;
2048 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002049 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002050 }
2051 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002052 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002053 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002054 if (nai == null) {
2055 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2056 break;
2057 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002058 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002059 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2060 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002061 }
Paul Jensen869868be2014-05-15 10:33:05 -04002062 break;
2063 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002064 }
2065 }
2066 }
2067
Paul Jensen85cf78e2015-06-25 13:25:07 -04002068 private void linger(NetworkAgentInfo nai) {
2069 nai.lingering = true;
2070 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2071 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2072 }
2073
Paul Jensen0cc17322014-11-25 15:26:53 -05002074 // Cancel any lingering so the linger timeout doesn't teardown a network.
2075 // This should be called when a network begins satisfying a NetworkRequest.
2076 // Note: depending on what state the NetworkMonitor is in (e.g.,
2077 // if it's awaiting captive portal login, or if validation failed), this
2078 // may trigger a re-evaluation of the network.
2079 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002080 nai.networkLingered.clear();
2081 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002082 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002083 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002084 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2085 }
2086
Robert Greenwalt7b816022014-04-18 15:25:25 -07002087 private void handleAsyncChannelHalfConnect(Message msg) {
2088 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002089 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002090 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2091 if (VDBG) log("NetworkFactory connected");
2092 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002093 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002094 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002095 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002096 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002097 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002098 }
2099 } else {
2100 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002101 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002102 }
2103 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2104 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2105 if (VDBG) log("NetworkAgent connected");
2106 // A network agent has requested a connection. Establish the connection.
2107 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2108 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2109 } else {
2110 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002111 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002112 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002113 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002114 synchronized (mNetworkForNetId) {
2115 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002116 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002117 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002118 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002119 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002120 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002121 }
2122 }
2123 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002124
Robert Greenwalt7b816022014-04-18 15:25:25 -07002125 private void handleAsyncChannelDisconnected(Message msg) {
2126 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2127 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002128 if (DBG) {
2129 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2130 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002131 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002132 // TODO - if we move the logic to the network agent (have them disconnect
2133 // because they lost all their requests or because their score isn't good)
2134 // then they would disconnect organically, report their new state and then
2135 // disconnect the channel.
2136 if (nai.networkInfo.isConnected()) {
2137 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2138 null, null);
2139 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002140 final boolean wasDefault = isDefaultNetwork(nai);
2141 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002142 mDefaultInetConditionPublished = 0;
2143 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002144 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002145 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002146 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002147 mNetworkAgentInfos.remove(msg.replyTo);
2148 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002149 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002150 // Remove the NetworkAgent, but don't mark the netId as
2151 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002152 mNetworkForNetId.remove(nai.network.netId);
2153 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002154 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002155 for (int i = 0; i < nai.networkRequests.size(); i++) {
2156 NetworkRequest request = nai.networkRequests.valueAt(i);
2157 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2158 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2159 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002160 sendUpdatedScoreToFactories(request, 0);
2161 }
2162 }
2163 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2164 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002165 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002166 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002167 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002168 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002169 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002170 if (nai.created) {
2171 // Tell netd to clean up the configuration for this network
2172 // (routing rules, DNS, etc).
2173 // This may be slow as it requires a lot of netd shelling out to ip and
2174 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2175 // after we've rematched networks with requests which should make a potential
2176 // fallback network the default or requested a new network from the
2177 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2178 // long time.
2179 try {
2180 mNetd.removeNetwork(nai.network.netId);
2181 } catch (Exception e) {
2182 loge("Exception removing network: " + e);
2183 }
2184 }
2185 synchronized (mNetworkForNetId) {
2186 mNetIdInUse.delete(nai.network.netId);
2187 }
2188 } else {
2189 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2190 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002191 }
2192 }
2193
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002194 // If this method proves to be too slow then we can maintain a separate
2195 // pendingIntent => NetworkRequestInfo map.
2196 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2197 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2198 Intent intent = pendingIntent.getIntent();
2199 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2200 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2201 if (existingPendingIntent != null &&
2202 existingPendingIntent.getIntent().filterEquals(intent)) {
2203 return entry.getValue();
2204 }
2205 }
2206 return null;
2207 }
2208
2209 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2210 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2211
2212 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2213 if (existingRequest != null) { // remove the existing request.
2214 if (DBG) log("Replacing " + existingRequest.request + " with "
2215 + nri.request + " because their intents matched.");
2216 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2217 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002218 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002219 }
2220
Erik Klineda4bfa82015-04-30 12:58:40 +09002221 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002222 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002223 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002224 rematchAllNetworksAndRequests(null, 0);
2225 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2226 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002227 }
2228 }
2229
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002230 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2231 int callingUid) {
2232 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2233 if (nri != null) {
2234 handleReleaseNetworkRequest(nri.request, callingUid);
2235 }
2236 }
2237
Paul Jensen99364842014-12-09 11:43:45 -05002238 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002239 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2240 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002241 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002242 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002243 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2244 // If this Network is already the highest scoring Network for a request, or if
2245 // there is hope for it to become one if it validated, then it is needed.
2246 if (nri.isRequest && nai.satisfies(nri.request) &&
2247 (nai.networkRequests.get(nri.request.requestId) != null ||
2248 // Note that this catches two important cases:
2249 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2250 // is currently satisfying the request. This is desirable when
2251 // cellular ends up validating but WiFi does not.
2252 // 2. Unvalidated WiFi will not be reaped when validated cellular
2253 // is currently satsifying the request. This is desirable when
2254 // WiFi ends up validating and out scoring cellular.
2255 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2256 nai.getCurrentScoreAsValidated())) {
2257 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002258 }
2259 }
Paul Jensene0988542015-06-25 15:30:08 -04002260 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002261 }
2262
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002263 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2264 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002265 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002266 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002267 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2268 return;
2269 }
2270 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002271 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002272 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002273 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002274 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002275 // Find all networks that are satisfying this request and remove the request
2276 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002277 // TODO - it's my understanding that for a request there is only a single
2278 // network satisfying it, so this loop is wasteful
2279 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002280 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2281 if (nai.networkRequests.get(nri.request.requestId) != null) {
2282 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002283 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002284 log(" Removing from current network " + nai.name() +
2285 ", leaving " + nai.networkRequests.size() +
2286 " requests.");
2287 }
Paul Jensen99364842014-12-09 11:43:45 -05002288 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002289 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002290 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002291 } else {
2292 // suspect there should only be one pass through here
2293 // but if any were kept do the check below
2294 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002295 }
2296 }
2297 }
2298
Robert Greenwalt51481852015-01-08 14:43:31 -08002299 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2300 if (nai != null) {
2301 mNetworkForRequestId.remove(nri.request.requestId);
2302 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002303 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002304 // that a network connected to serve it, even though the network was already
2305 // connected. Now that this request has gone away, we might have to pretend
2306 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002307 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002308 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2309 boolean doRemove = true;
2310 if (wasKept) {
2311 // check if any of the remaining requests for this network are for the
2312 // same legacy type - if so, don't remove the nai
2313 for (int i = 0; i < nai.networkRequests.size(); i++) {
2314 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2315 if (otherRequest.legacyType == nri.request.legacyType &&
2316 isRequest(otherRequest)) {
2317 if (DBG) log(" still have other legacy request - leaving");
2318 doRemove = false;
2319 }
2320 }
2321 }
2322
2323 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002324 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002325 }
2326 }
2327
Robert Greenwalta67be032014-05-16 15:49:14 -07002328 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002329 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2330 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002331 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002332 } else {
2333 // listens don't have a singular affectedNetwork. Check all networks to see
2334 // if this listen request applies and remove it.
2335 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2336 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002337 }
2338 }
2339 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2340 }
2341 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002342
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002343 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2344 enforceConnectivityInternalPermission();
2345 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2346 accept ? 1 : 0, always ? 1: 0, network));
2347 }
2348
2349 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2350 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2351 " accept=" + accept + " always=" + always);
2352
2353 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2354 if (nai == null) {
2355 // Nothing to do.
2356 return;
2357 }
2358
2359 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002360 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002361 return;
2362 }
2363
2364 if (!nai.networkMisc.explicitlySelected) {
2365 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2366 }
2367
2368 if (accept != nai.networkMisc.acceptUnvalidated) {
2369 int oldScore = nai.getCurrentScore();
2370 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002371 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002372 sendUpdatedScoreToFactories(nai);
2373 }
2374
2375 if (always) {
2376 nai.asyncChannel.sendMessage(
2377 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2378 }
2379
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002380 if (!accept) {
2381 // Tell the NetworkAgent that the network does not have Internet access (because that's
2382 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2383 // the future. We do this now because NetworkMonitor might not yet have finished
2384 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2385 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2386 NetworkAgent.INVALID_NETWORK, 0, null);
2387 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2388 // to reconnect to it immediately. http://b/20739299
2389 }
2390
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002391 }
2392
2393 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002394 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002395 mHandler.sendMessageDelayed(
2396 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2397 PROMPT_UNVALIDATED_DELAY_MS);
2398 }
2399
2400 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002401 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002402 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2403
2404 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2405 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002406 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002407 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002408 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2409 return;
2410 }
2411
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002412 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002413 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002414 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2415 intent.setClassName("com.android.settings",
2416 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002417
2418 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2419 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2420 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002421 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002422 }
2423
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002424 private class InternalHandler extends Handler {
2425 public InternalHandler(Looper looper) {
2426 super(looper);
2427 }
2428
2429 @Override
2430 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002431 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002432 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002433 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002434 String causedBy = null;
2435 synchronized (ConnectivityService.this) {
2436 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2437 mNetTransitionWakeLock.isHeld()) {
2438 mNetTransitionWakeLock.release();
2439 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002440 } else {
2441 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002442 }
2443 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002444 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2445 log("Failed to find a new network - expiring NetTransition Wakelock");
2446 } else {
2447 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2448 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002449 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002450 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002451 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002452 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002453 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002454 break;
2455 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002456 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002457 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002458 sendStickyBroadcast(intent);
2459 break;
2460 }
Jason Monkdecd2952013-10-10 14:02:51 -04002461 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002462 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002463 break;
2464 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002465 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002466 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2467 break;
2468 }
2469 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2470 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002471 break;
2472 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002473 case EVENT_REGISTER_NETWORK_AGENT: {
2474 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2475 break;
2476 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002477 case EVENT_REGISTER_NETWORK_REQUEST:
2478 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002479 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002480 break;
2481 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002482 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2483 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002484 handleRegisterNetworkRequestWithIntent(msg);
2485 break;
2486 }
2487 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2488 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2489 break;
2490 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002491 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002492 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002493 break;
2494 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002495 case EVENT_SET_ACCEPT_UNVALIDATED: {
2496 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2497 break;
2498 }
2499 case EVENT_PROMPT_UNVALIDATED: {
2500 handlePromptUnvalidated((Network) msg.obj);
2501 break;
2502 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002503 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2504 handleMobileDataAlwaysOn();
2505 break;
2506 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002507 case EVENT_SYSTEM_READY: {
2508 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2509 nai.networkMonitor.systemReady = true;
2510 }
2511 break;
2512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 }
2514 }
2515 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002516
2517 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002518 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002519 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002520 if (isTetheringSupported()) {
2521 return mTethering.tether(iface);
2522 } else {
2523 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2524 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002525 }
2526
2527 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002528 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002529 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002530
2531 if (isTetheringSupported()) {
2532 return mTethering.untether(iface);
2533 } else {
2534 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2535 }
2536 }
2537
2538 // javadoc from interface
2539 public int getLastTetherError(String iface) {
2540 enforceTetherAccessPermission();
2541
2542 if (isTetheringSupported()) {
2543 return mTethering.getLastTetherError(iface);
2544 } else {
2545 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2546 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002547 }
2548
2549 // TODO - proper iface API for selection by property, inspection, etc
2550 public String[] getTetherableUsbRegexs() {
2551 enforceTetherAccessPermission();
2552 if (isTetheringSupported()) {
2553 return mTethering.getTetherableUsbRegexs();
2554 } else {
2555 return new String[0];
2556 }
2557 }
2558
2559 public String[] getTetherableWifiRegexs() {
2560 enforceTetherAccessPermission();
2561 if (isTetheringSupported()) {
2562 return mTethering.getTetherableWifiRegexs();
2563 } else {
2564 return new String[0];
2565 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002566 }
2567
Danica Chang6fdd0c62010-08-11 14:54:43 -07002568 public String[] getTetherableBluetoothRegexs() {
2569 enforceTetherAccessPermission();
2570 if (isTetheringSupported()) {
2571 return mTethering.getTetherableBluetoothRegexs();
2572 } else {
2573 return new String[0];
2574 }
2575 }
2576
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002577 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002578 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002579 if (isTetheringSupported()) {
2580 return mTethering.setUsbTethering(enable);
2581 } else {
2582 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2583 }
2584 }
2585
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002586 // TODO - move iface listing, queries, etc to new module
2587 // javadoc from interface
2588 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002589 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002590 return mTethering.getTetherableIfaces();
2591 }
2592
2593 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002594 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002595 return mTethering.getTetheredIfaces();
2596 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002597
Robert Greenwalt5a735062010-03-02 17:25:02 -08002598 public String[] getTetheringErroredIfaces() {
2599 enforceTetherAccessPermission();
2600 return mTethering.getErroredIfaces();
2601 }
2602
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002603 public String[] getTetheredDhcpRanges() {
2604 enforceConnectivityInternalPermission();
2605 return mTethering.getTetheredDhcpRanges();
2606 }
2607
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002608 // if ro.tether.denied = true we default to no tethering
2609 // gservices could set the secure setting to 1 though to enable it on a build where it
2610 // had previously been turned off.
2611 public boolean isTetheringSupported() {
2612 enforceTetherAccessPermission();
2613 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002614 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002615 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2616 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002617 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2618 mTethering.getTetherableWifiRegexs().length != 0 ||
2619 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2620 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002621 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002622
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002623 // Called when we lose the default network and have no replacement yet.
2624 // This will automatically be cleared after X seconds or a new default network
2625 // becomes CONNECTED, whichever happens first. The timer is started by the
2626 // first caller and not restarted by subsequent callers.
2627 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002628 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002629 synchronized (this) {
2630 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002631 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002632 mNetTransitionWakeLock.acquire();
2633 mNetTransitionWakeLockCausedBy = forWhom;
2634 }
2635 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002636 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002637 mNetTransitionWakeLockTimeout);
2638 return;
2639 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002640
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002641 // 100 percent is full good, 0 is full bad.
2642 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002643 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002644 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002645 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002646 }
2647
Paul Jensenbfd17b72015-04-07 12:43:13 -04002648 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002649 enforceAccessPermission();
2650 enforceInternetPermission();
2651
Paul Jensenbfd17b72015-04-07 12:43:13 -04002652 NetworkAgentInfo nai;
2653 if (network == null) {
2654 nai = getDefaultNetwork();
2655 } else {
2656 nai = getNetworkAgentInfoForNetwork(network);
2657 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002658 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2659 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2660 return;
2661 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002662 // Revalidate if the app report does not match our current validated state.
2663 if (hasConnectivity == nai.lastValidated) return;
2664 final int uid = Binder.getCallingUid();
2665 if (DBG) {
2666 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2667 ") by " + uid);
2668 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002669 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002670 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2671 // which isn't meant to work on uncreated networks.
2672 if (!nai.created) return;
2673
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002674 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002675
2676 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2677 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002678 }
2679
Paul Jensencee9b512015-05-06 07:32:40 -04002680 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002681 // this information is already available as a world read/writable jvm property
2682 // so this API change wouldn't have a benifit. It also breaks the passing
2683 // of proxy info to all the JVMs.
2684 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002685 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002686 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002687 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2688 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002689 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002690 }
2691
Paul Jensencee9b512015-05-06 07:32:40 -04002692 public ProxyInfo getProxyForNetwork(Network network) {
2693 if (network == null) return getDefaultProxy();
2694 final ProxyInfo globalProxy = getGlobalProxy();
2695 if (globalProxy != null) return globalProxy;
2696 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2697 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2698 // caller may not have.
2699 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2700 if (nai == null) return null;
2701 synchronized (nai) {
2702 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2703 if (proxyInfo == null) return null;
2704 return new ProxyInfo(proxyInfo);
2705 }
2706 }
2707
Paul Jensene0bef712014-12-10 15:12:18 -05002708 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2709 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2710 // proxy is null then there is no proxy in place).
2711 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2712 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2713 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2714 proxy = null;
2715 }
2716 return proxy;
2717 }
2718
2719 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2720 // better for determining if a new proxy broadcast is necessary:
2721 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2722 // avoid unnecessary broadcasts.
2723 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2724 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2725 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2726 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2727 // all set.
2728 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2729 a = canonicalizeProxyInfo(a);
2730 b = canonicalizeProxyInfo(b);
2731 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2732 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2733 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2734 }
2735
Jason Monk207900c2014-04-25 15:00:09 -04002736 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002737 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002738
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002739 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002740 if (proxyProperties == mGlobalProxy) return;
2741 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2742 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2743
2744 String host = "";
2745 int port = 0;
2746 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002747 String pacFileUrl = "";
2748 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002749 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002750 if (!proxyProperties.isValid()) {
2751 if (DBG)
2752 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2753 return;
2754 }
Jason Monk207900c2014-04-25 15:00:09 -04002755 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002756 host = mGlobalProxy.getHost();
2757 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002758 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002759 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002760 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002761 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002762 } else {
2763 mGlobalProxy = null;
2764 }
2765 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002766 final long token = Binder.clearCallingIdentity();
2767 try {
2768 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2769 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2770 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2771 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002772 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002773 } finally {
2774 Binder.restoreCallingIdentity(token);
2775 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002776
Jason Monkcf0f97a2014-10-02 15:39:38 -04002777 if (mGlobalProxy == null) {
2778 proxyProperties = mDefaultProxy;
2779 }
2780 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002781 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002782 }
2783
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002784 private void loadGlobalProxy() {
2785 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002786 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2787 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2788 String exclList = Settings.Global.getString(res,
2789 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002790 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2791 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002792 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002793 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002794 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002795 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002796 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002797 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002798 if (!proxyProperties.isValid()) {
2799 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2800 return;
2801 }
2802
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002803 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002804 mGlobalProxy = proxyProperties;
2805 }
2806 }
2807 }
2808
Jason Monk207900c2014-04-25 15:00:09 -04002809 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002810 // this information is already available as a world read/writable jvm property
2811 // so this API change wouldn't have a benifit. It also breaks the passing
2812 // of proxy info to all the JVMs.
2813 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002814 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002815 return mGlobalProxy;
2816 }
2817 }
2818
Jason Monk207900c2014-04-25 15:00:09 -04002819 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002820 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002821 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002822 proxy = null;
2823 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002824 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002825 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002826 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002827 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002828 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2829 return;
2830 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002831
2832 // This call could be coming from the PacManager, containing the port of the local
2833 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2834 // global (to get the correct local port), and send a broadcast.
2835 // TODO: Switch PacManager to have its own message to send back rather than
2836 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002837 if ((mGlobalProxy != null) && (proxy != null)
2838 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002839 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2840 mGlobalProxy = proxy;
2841 sendProxyBroadcast(mGlobalProxy);
2842 return;
2843 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002844 mDefaultProxy = proxy;
2845
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002846 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002847 if (!mDefaultProxyDisabled) {
2848 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002849 }
2850 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002851 }
2852
Paul Jensene0bef712014-12-10 15:12:18 -05002853 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2854 // This method gets called when any network changes proxy, but the broadcast only ever contains
2855 // the default proxy (even if it hasn't changed).
2856 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2857 // world where an app might be bound to a non-default network.
2858 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2859 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2860 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2861
2862 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2863 sendProxyBroadcast(getDefaultProxy());
2864 }
2865 }
2866
Robert Greenwalt434203a2010-10-11 16:00:27 -07002867 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002868 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2869 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002870 if (!TextUtils.isEmpty(proxy)) {
2871 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002872 if (data.length == 0) {
2873 return;
2874 }
2875
Robert Greenwalt434203a2010-10-11 16:00:27 -07002876 String proxyHost = data[0];
2877 int proxyPort = 8080;
2878 if (data.length > 1) {
2879 try {
2880 proxyPort = Integer.parseInt(data[1]);
2881 } catch (NumberFormatException e) {
2882 return;
2883 }
2884 }
Jason Monk207900c2014-04-25 15:00:09 -04002885 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002886 setGlobalProxy(p);
2887 }
2888 }
2889
Jason Monk207900c2014-04-25 15:00:09 -04002890 private void sendProxyBroadcast(ProxyInfo proxy) {
2891 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002892 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002893 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002894 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002895 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2896 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002897 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002898 final long ident = Binder.clearCallingIdentity();
2899 try {
2900 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2901 } finally {
2902 Binder.restoreCallingIdentity(ident);
2903 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002904 }
2905
2906 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002907 final private HashMap<Uri, Integer> mUriEventMap;
2908 final private Context mContext;
2909 final private Handler mHandler;
2910
2911 SettingsObserver(Context context, Handler handler) {
2912 super(null);
2913 mUriEventMap = new HashMap<Uri, Integer>();
2914 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002915 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002916 }
2917
Erik Klineda4bfa82015-04-30 12:58:40 +09002918 void observe(Uri uri, int what) {
2919 mUriEventMap.put(uri, what);
2920 final ContentResolver resolver = mContext.getContentResolver();
2921 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002922 }
2923
2924 @Override
2925 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002926 Slog.wtf(TAG, "Should never be reached.");
2927 }
2928
2929 @Override
2930 public void onChange(boolean selfChange, Uri uri) {
2931 final Integer what = mUriEventMap.get(uri);
2932 if (what != null) {
2933 mHandler.obtainMessage(what.intValue()).sendToTarget();
2934 } else {
2935 loge("No matching event to send for URI=" + uri);
2936 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002937 }
2938 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002939
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002940 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002941 Slog.d(TAG, s);
2942 }
2943
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002944 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002945 Slog.e(TAG, s);
2946 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002947
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002948 private static <T> T checkNotNull(T value, String message) {
2949 if (value == null) {
2950 throw new NullPointerException(message);
2951 }
2952 return value;
2953 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002954
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002955 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002956 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002957 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2958 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2959 *
2960 * @param oldPackage Package name of the application which currently controls VPN, which will
2961 * be replaced. If there is no such application, this should should either be
2962 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2963 * @param newPackage Package name of the application which should gain control of VPN, or
2964 * {@code null} to disable.
2965 * @param userId User for whom to prepare the new VPN.
2966 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002967 * @hide
2968 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002969 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002970 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2971 int userId) {
2972 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002973 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01002974
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002975 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07002976 Vpn vpn = mVpns.get(userId);
2977 if (vpn != null) {
2978 return vpn.prepare(oldPackage, newPackage);
2979 } else {
2980 return false;
2981 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002982 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002983 }
2984
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002985 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01002986 * Set whether the VPN package has the ability to launch VPNs without user intervention.
2987 * This method is used by system-privileged apps.
2988 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2989 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2990 *
2991 * @param packageName The package for which authorization state should change.
2992 * @param userId User for whom {@code packageName} is installed.
2993 * @param authorized {@code true} if this app should be able to start a VPN connection without
2994 * explicit user approval, {@code false} if not.
2995 *
Jeff Davidson05542602014-08-11 14:07:27 -07002996 * @hide
2997 */
2998 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002999 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3000 enforceCrossUserPermission(userId);
3001
Jeff Davidson05542602014-08-11 14:07:27 -07003002 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003003 Vpn vpn = mVpns.get(userId);
3004 if (vpn != null) {
3005 vpn.setPackageAuthorization(packageName, authorized);
3006 }
Jeff Davidson05542602014-08-11 14:07:27 -07003007 }
3008 }
3009
3010 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003011 * Configure a TUN interface and return its file descriptor. Parameters
3012 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003013 * and not available in ConnectivityManager. Permissions are checked in
3014 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003015 * @hide
3016 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003017 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003018 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003019 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003020 int user = UserHandle.getUserId(Binder.getCallingUid());
3021 synchronized(mVpns) {
3022 return mVpns.get(user).establish(config);
3023 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003024 }
3025
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003026 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003027 * Start legacy VPN, controlling native daemons as needed. Creates a
3028 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003029 */
3030 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003031 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003032 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003033 final LinkProperties egress = getActiveLinkProperties();
3034 if (egress == null) {
3035 throw new IllegalStateException("Missing active network connection");
3036 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003037 int user = UserHandle.getUserId(Binder.getCallingUid());
3038 synchronized(mVpns) {
3039 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3040 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003041 }
3042
3043 /**
3044 * Return the information of the ongoing legacy VPN. This method is used
3045 * by VpnSettings and not available in ConnectivityManager. Permissions
3046 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003047 */
3048 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003049 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3050 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003051 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003052 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003053 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003054 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003055 }
3056
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003057 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003058 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3059 * and not available in ConnectivityManager.
3060 */
3061 @Override
3062 public VpnInfo[] getAllVpnInfo() {
3063 enforceConnectivityInternalPermission();
3064 if (mLockdownEnabled) {
3065 return new VpnInfo[0];
3066 }
3067
3068 synchronized(mVpns) {
3069 List<VpnInfo> infoList = new ArrayList<>();
3070 for (int i = 0; i < mVpns.size(); i++) {
3071 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3072 if (info != null) {
3073 infoList.add(info);
3074 }
3075 }
3076 return infoList.toArray(new VpnInfo[infoList.size()]);
3077 }
3078 }
3079
3080 /**
3081 * @return VPN information for accounting, or null if we can't retrieve all required
3082 * information, e.g primary underlying iface.
3083 */
3084 @Nullable
3085 private VpnInfo createVpnInfo(Vpn vpn) {
3086 VpnInfo info = vpn.getVpnInfo();
3087 if (info == null) {
3088 return null;
3089 }
3090 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3091 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3092 // the underlyingNetworks list.
3093 if (underlyingNetworks == null) {
3094 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3095 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3096 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3097 }
3098 } else if (underlyingNetworks.length > 0) {
3099 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3100 if (linkProperties != null) {
3101 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3102 }
3103 }
3104 return info.primaryUnderlyingIface == null ? null : info;
3105 }
3106
3107 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003108 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3109 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003110 * Permissions are checked in Vpn class.
3111 * @hide
3112 */
3113 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003114 public VpnConfig getVpnConfig(int userId) {
3115 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003116 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003117 Vpn vpn = mVpns.get(userId);
3118 if (vpn != null) {
3119 return vpn.getVpnConfig();
3120 } else {
3121 return null;
3122 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003123 }
3124 }
3125
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003126 @Override
3127 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003128 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3129 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3130 return false;
3131 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003132
3133 // Tear down existing lockdown if profile was removed
3134 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3135 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003136 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003137 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3138 return false;
3139 }
3140
3141 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3142 final VpnProfile profile = VpnProfile.decode(
3143 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003144 int user = UserHandle.getUserId(Binder.getCallingUid());
3145 synchronized(mVpns) {
3146 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3147 profile));
3148 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003149 } else {
3150 setLockdownTracker(null);
3151 }
3152
3153 return true;
3154 }
3155
3156 /**
3157 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3158 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3159 */
3160 private void setLockdownTracker(LockdownVpnTracker tracker) {
3161 // Shutdown any existing tracker
3162 final LockdownVpnTracker existing = mLockdownTracker;
3163 mLockdownTracker = null;
3164 if (existing != null) {
3165 existing.shutdown();
3166 }
3167
3168 try {
3169 if (tracker != null) {
3170 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003171 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003172 mLockdownTracker = tracker;
3173 mLockdownTracker.init();
3174 } else {
3175 mNetd.setFirewallEnabled(false);
3176 }
3177 } catch (RemoteException e) {
3178 // ignored; NMS lives inside system_server
3179 }
3180 }
3181
3182 private void throwIfLockdownEnabled() {
3183 if (mLockdownEnabled) {
3184 throw new IllegalStateException("Unavailable in lockdown mode");
3185 }
3186 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003187
Wink Savilleab9321d2013-06-29 21:10:57 -07003188 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003189 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003190 // TODO: Remove? Any reason to trigger a provisioning check?
3191 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003192 }
3193
3194 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003195 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003196
Paul Jensen89e0f092014-09-15 15:59:36 -04003197 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003198 if (DBG) {
3199 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003200 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003201 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003202 Intent intent = new Intent(action);
3203 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003204 // Concatenate the range of types onto the range of NetIDs.
3205 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003206 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003207 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003208 }
3209
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003210 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003211 * Show or hide network provisioning notifications.
3212 *
3213 * We use notifications for two purposes: to notify that a network requires sign in
3214 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3215 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3216 * particular network we can display the notification type that was most recently requested.
3217 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3218 * might first display NO_INTERNET, and then when the captive portal check completes, display
3219 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003220 *
3221 * @param id an identifier that uniquely identifies this notification. This must match
3222 * between show and hide calls. We use the NetID value but for legacy callers
3223 * we concatenate the range of types with the range of NetIDs.
3224 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003225 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003226 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3227 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003228 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003229 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3230 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003231 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003232 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003233
3234 Resources r = Resources.getSystem();
3235 NotificationManager notificationManager = (NotificationManager) mContext
3236 .getSystemService(Context.NOTIFICATION_SERVICE);
3237
3238 if (visible) {
3239 CharSequence title;
3240 CharSequence details;
3241 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003242 if (notifyType == NotificationType.NO_INTERNET &&
3243 networkType == ConnectivityManager.TYPE_WIFI) {
3244 title = r.getString(R.string.wifi_no_internet, 0);
3245 details = r.getString(R.string.wifi_no_internet_detailed);
3246 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3247 } else if (notifyType == NotificationType.SIGN_IN) {
3248 switch (networkType) {
3249 case ConnectivityManager.TYPE_WIFI:
3250 title = r.getString(R.string.wifi_available_sign_in, 0);
3251 details = r.getString(R.string.network_available_sign_in_detailed,
3252 extraInfo);
3253 icon = R.drawable.stat_notify_wifi_in_range;
3254 break;
3255 case ConnectivityManager.TYPE_MOBILE:
3256 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3257 title = r.getString(R.string.network_available_sign_in, 0);
3258 // TODO: Change this to pull from NetworkInfo once a printable
3259 // name has been added to it
3260 details = mTelephonyManager.getNetworkOperatorName();
3261 icon = R.drawable.stat_notify_rssi_in_range;
3262 break;
3263 default:
3264 title = r.getString(R.string.network_available_sign_in, 0);
3265 details = r.getString(R.string.network_available_sign_in_detailed,
3266 extraInfo);
3267 icon = R.drawable.stat_notify_rssi_in_range;
3268 break;
3269 }
3270 } else {
3271 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3272 + getNetworkTypeName(networkType));
3273 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003274 }
3275
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003276 Notification notification = new Notification.Builder(mContext)
3277 .setWhen(0)
3278 .setSmallIcon(icon)
3279 .setAutoCancel(true)
3280 .setTicker(title)
3281 .setColor(mContext.getColor(
3282 com.android.internal.R.color.system_notification_accent_color))
3283 .setContentTitle(title)
3284 .setContentText(details)
3285 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003286 .setLocalOnly(true)
3287 .setPriority(highPriority ?
3288 Notification.PRIORITY_HIGH :
3289 Notification.PRIORITY_DEFAULT)
3290 .setDefaults(Notification.DEFAULT_ALL)
3291 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003292 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003293
Wink Saville948282b2013-08-29 08:55:16 -07003294 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003295 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003296 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003297 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003298 npe.printStackTrace();
3299 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003300 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003301 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003302 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003303 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003304 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003305 npe.printStackTrace();
3306 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003307 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003308 }
3309
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003310 /** Location to an updatable file listing carrier provisioning urls.
3311 * An example:
3312 *
3313 * <?xml version="1.0" encoding="utf-8"?>
3314 * <provisioningUrls>
3315 * <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 -07003316 * </provisioningUrls>
3317 */
3318 private static final String PROVISIONING_URL_PATH =
3319 "/data/misc/radio/provisioning_urls.xml";
3320 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003321
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003322 /** XML tag for root element. */
3323 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3324 /** XML tag for individual url */
3325 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003326 /** XML attribute for mcc */
3327 private static final String ATTR_MCC = "mcc";
3328 /** XML attribute for mnc */
3329 private static final String ATTR_MNC = "mnc";
3330
Paul Jensen434dde82015-06-11 09:43:30 -04003331 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003332 FileReader fileReader = null;
3333 XmlPullParser parser = null;
3334 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003335
3336 try {
3337 fileReader = new FileReader(mProvisioningUrlFile);
3338 parser = Xml.newPullParser();
3339 parser.setInput(fileReader);
3340 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3341
3342 while (true) {
3343 XmlUtils.nextElement(parser);
3344
3345 String element = parser.getName();
3346 if (element == null) break;
3347
Paul Jensen434dde82015-06-11 09:43:30 -04003348 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003349 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3350 try {
3351 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3352 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3353 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3354 parser.next();
3355 if (parser.getEventType() == XmlPullParser.TEXT) {
3356 return parser.getText();
3357 }
3358 }
3359 }
3360 } catch (NumberFormatException e) {
3361 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3362 }
3363 }
3364 }
3365 return null;
3366 } catch (FileNotFoundException e) {
3367 loge("Carrier Provisioning Urls file not found");
3368 } catch (XmlPullParserException e) {
3369 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3370 } catch (IOException e) {
3371 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3372 } finally {
3373 if (fileReader != null) {
3374 try {
3375 fileReader.close();
3376 } catch (IOException e) {}
3377 }
3378 }
3379 return null;
3380 }
3381
Wink Saville42d4f082013-07-20 20:31:59 -07003382 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003383 public String getMobileProvisioningUrl() {
3384 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003385 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003386 if (TextUtils.isEmpty(url)) {
3387 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003388 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003389 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003390 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003391 }
Wink Saville8cf35602013-07-10 23:00:07 -07003392 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003393 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003394 String phoneNumber = mTelephonyManager.getLine1Number();
3395 if (TextUtils.isEmpty(phoneNumber)) {
3396 phoneNumber = "0000000000";
3397 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003398 url = String.format(url,
3399 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3400 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003401 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003402 }
3403
Wink Savilleab9321d2013-06-29 21:10:57 -07003404 return url;
3405 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003406
Wink Saville948282b2013-08-29 08:55:16 -07003407 @Override
3408 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003409 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003410 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003411 final long ident = Binder.clearCallingIdentity();
3412 try {
3413 setProvNotificationVisible(visible, networkType, action);
3414 } finally {
3415 Binder.restoreCallingIdentity(ident);
3416 }
Wink Saville948282b2013-08-29 08:55:16 -07003417 }
Wink Saville7788c612013-08-29 14:57:08 -07003418
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003419 @Override
3420 public void setAirplaneMode(boolean enable) {
3421 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003422 final long ident = Binder.clearCallingIdentity();
3423 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003424 final ContentResolver cr = mContext.getContentResolver();
3425 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3426 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3427 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003428 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003429 } finally {
3430 Binder.restoreCallingIdentity(ident);
3431 }
3432 }
3433
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003434 private void onUserStart(int userId) {
3435 synchronized(mVpns) {
3436 Vpn userVpn = mVpns.get(userId);
3437 if (userVpn != null) {
3438 loge("Starting user already has a VPN");
3439 return;
3440 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003441 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003442 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003443 }
3444 }
3445
3446 private void onUserStop(int userId) {
3447 synchronized(mVpns) {
3448 Vpn userVpn = mVpns.get(userId);
3449 if (userVpn == null) {
3450 loge("Stopping user has no VPN");
3451 return;
3452 }
3453 mVpns.delete(userId);
3454 }
3455 }
3456
3457 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3458 @Override
3459 public void onReceive(Context context, Intent intent) {
3460 final String action = intent.getAction();
3461 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3462 if (userId == UserHandle.USER_NULL) return;
3463
3464 if (Intent.ACTION_USER_STARTING.equals(action)) {
3465 onUserStart(userId);
3466 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3467 onUserStop(userId);
3468 }
3469 }
3470 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003471
Robert Greenwalta67be032014-05-16 15:49:14 -07003472 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3473 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003474 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3475 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003476
Robert Greenwalta67be032014-05-16 15:49:14 -07003477 private static class NetworkFactoryInfo {
3478 public final String name;
3479 public final Messenger messenger;
3480 public final AsyncChannel asyncChannel;
3481
3482 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3483 this.name = name;
3484 this.messenger = messenger;
3485 this.asyncChannel = asyncChannel;
3486 }
3487 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003488
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003489 /**
3490 * Tracks info about the requester.
3491 * Also used to notice when the calling process dies so we can self-expire
3492 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003493 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3494 static final boolean REQUEST = true;
3495 static final boolean LISTEN = false;
3496
3497 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003498 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003499 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003500 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003501 final int mPid;
3502 final int mUid;
3503 final Messenger messenger;
3504 final boolean isRequest;
3505
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003506 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3507 request = r;
3508 mPendingIntent = pi;
3509 messenger = null;
3510 mBinder = null;
3511 mPid = getCallingPid();
3512 mUid = getCallingUid();
3513 this.isRequest = isRequest;
3514 }
3515
Robert Greenwalt9258c642014-03-26 16:47:06 -07003516 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3517 super();
3518 messenger = m;
3519 request = r;
3520 mBinder = binder;
3521 mPid = getCallingPid();
3522 mUid = getCallingUid();
3523 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003524 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003525
3526 try {
3527 mBinder.linkToDeath(this, 0);
3528 } catch (RemoteException e) {
3529 binderDied();
3530 }
3531 }
3532
3533 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003534 if (mBinder != null) {
3535 mBinder.unlinkToDeath(this, 0);
3536 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003537 }
3538
3539 public void binderDied() {
3540 log("ConnectivityService NetworkRequestInfo binderDied(" +
3541 request + ", " + mBinder + ")");
3542 releaseNetworkRequest(request);
3543 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003544
3545 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003546 return (isRequest ? "Request" : "Listen") +
3547 " from uid/pid:" + mUid + "/" + mPid +
3548 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003549 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003550 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003551 }
3552
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003553 private void ensureImmutableCapabilities(NetworkCapabilities networkCapabilities) {
3554 if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
3555 throw new IllegalArgumentException(
3556 "Cannot request network with NET_CAPABILITY_VALIDATED");
3557 }
3558 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
3559 throw new IllegalArgumentException(
3560 "Cannot request network with NET_CAPABILITY_CAPTIVE_PORTAL");
3561 }
3562 }
3563
Robert Greenwalt9258c642014-03-26 16:47:06 -07003564 @Override
3565 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003566 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003567 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003568 enforceNetworkRequestPermissions(networkCapabilities);
3569 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003570 ensureImmutableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003571
Robert Greenwalt6078b502014-06-11 16:05:07 -07003572 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003573 throw new IllegalArgumentException("Bad timeout specified");
3574 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003575
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003576 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3577 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003578 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3579 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003580 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003581
3582 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003583 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003584 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003585 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003586 }
3587 return networkRequest;
3588 }
3589
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003590 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003591 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003592 enforceConnectivityInternalPermission();
3593 } else {
3594 enforceChangePermission();
3595 }
3596 }
3597
fenglub15e72b2015-03-20 11:29:56 -07003598 @Override
fengludb571472015-04-21 17:12:05 -07003599 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003600 enforceAccessPermission();
3601 NetworkAgentInfo nai = null;
3602 if (network == null) {
3603 return false;
3604 }
3605 synchronized (mNetworkForNetId) {
3606 nai = mNetworkForNetId.get(network.netId);
3607 }
3608 if (nai != null) {
3609 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3610 return true;
3611 }
3612 return false;
3613 }
3614
3615
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003616 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3617 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003618 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003619 final int uidRules;
3620 final int uid = Binder.getCallingUid();
3621 synchronized(mRulesLock) {
3622 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3623 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003624 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003625 // we could silently fail or we can filter the available nets to only give
3626 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003627 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003628 }
3629 }
3630 }
3631
Robert Greenwalt9258c642014-03-26 16:47:06 -07003632 @Override
3633 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3634 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003635 checkNotNull(operation, "PendingIntent cannot be null.");
3636 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3637 enforceNetworkRequestPermissions(networkCapabilities);
3638 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003639 ensureImmutableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003640
3641 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3642 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003643 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3644 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003645 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003646 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3647 nri));
3648 return networkRequest;
3649 }
3650
Jeremy Joslin79294842014-12-03 17:15:28 -08003651 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3652 mHandler.sendMessageDelayed(
3653 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3654 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3655 }
3656
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003657 @Override
3658 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003659 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003660 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3661 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003662 }
3663
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003664 // In order to implement the compatibility measure for pre-M apps that call
3665 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3666 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3667 // This ensures it has permission to do so.
3668 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3669 if (nc == null) {
3670 return false;
3671 }
3672 int[] transportTypes = nc.getTransportTypes();
3673 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3674 return false;
3675 }
3676 try {
3677 mContext.enforceCallingOrSelfPermission(
3678 android.Manifest.permission.ACCESS_WIFI_STATE,
3679 "ConnectivityService");
3680 } catch (SecurityException e) {
3681 return false;
3682 }
3683 return true;
3684 }
3685
Robert Greenwalt9258c642014-03-26 16:47:06 -07003686 @Override
3687 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3688 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003689 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3690 enforceAccessPermission();
3691 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003692
Erik Kline7523eb32015-07-09 18:24:03 +09003693 NetworkRequest networkRequest = new NetworkRequest(
3694 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003695 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3696 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003697 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003698
3699 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3700 return networkRequest;
3701 }
3702
3703 @Override
3704 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3705 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003706 checkNotNull(operation, "PendingIntent cannot be null.");
3707 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3708 enforceAccessPermission();
3709 }
3710
Erik Kline7523eb32015-07-09 18:24:03 +09003711 NetworkRequest networkRequest = new NetworkRequest(
3712 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003713 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3714 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003715 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003716
3717 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003718 }
3719
3720 @Override
3721 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003722 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3723 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003724 }
3725
3726 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003727 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003728 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003729 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3730 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003731 }
3732
Robert Greenwalta67be032014-05-16 15:49:14 -07003733 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003734 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003735 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3736 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3737 }
3738
3739 @Override
3740 public void unregisterNetworkFactory(Messenger messenger) {
3741 enforceConnectivityInternalPermission();
3742 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3743 }
3744
3745 private void handleUnregisterNetworkFactory(Messenger messenger) {
3746 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3747 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003748 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003749 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003750 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003751 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003752 }
3753
Robert Greenwalt7b816022014-04-18 15:25:25 -07003754 /**
3755 * NetworkAgentInfo supporting a request by requestId.
3756 * These have already been vetted (their Capabilities satisfy the request)
3757 * and the are the highest scored network available.
3758 * the are keyed off the Requests requestId.
3759 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003760 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003761 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3762 new SparseArray<NetworkAgentInfo>();
3763
Paul Jensen31a94f42015-02-13 14:18:39 -05003764 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3765 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003766 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3767 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003768 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3769 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3770 // there may not be a strict 1:1 correlation between the two.
3771 @GuardedBy("mNetworkForNetId")
3772 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003773
Robert Greenwalt7b816022014-04-18 15:25:25 -07003774 // NetworkAgentInfo keyed off its connecting messenger
3775 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003776 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003777 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3778 new HashMap<Messenger, NetworkAgentInfo>();
3779
Paul Jensen2c311d62014-11-17 12:34:51 -05003780 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003781 private final NetworkRequest mDefaultRequest;
3782
Erik Klineda4bfa82015-04-30 12:58:40 +09003783 // Request used to optionally keep mobile data active even when higher
3784 // priority networks like Wi-Fi are active.
3785 private final NetworkRequest mDefaultMobileDataRequest;
3786
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003787 private NetworkAgentInfo getDefaultNetwork() {
3788 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3789 }
3790
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003791 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003792 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003793 }
3794
Paul Jensen31a94f42015-02-13 14:18:39 -05003795 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003796 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003797 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003798 enforceConnectivityInternalPermission();
3799
Paul Jensen2c311d62014-11-17 12:34:51 -05003800 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3801 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003802 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003803 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3804 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3805 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003806 synchronized (this) {
3807 nai.networkMonitor.systemReady = mSystemReady;
3808 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003809 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003810 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003811 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003812 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003813 }
3814
3815 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3816 if (VDBG) log("Got NetworkAgent Messenger");
3817 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003818 synchronized (mNetworkForNetId) {
3819 mNetworkForNetId.put(na.network.netId, na);
3820 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003821 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3822 NetworkInfo networkInfo = na.networkInfo;
3823 na.networkInfo = null;
3824 updateNetworkInfo(na, networkInfo);
3825 }
3826
3827 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3828 LinkProperties newLp = networkAgent.linkProperties;
3829 int netId = networkAgent.network.netId;
3830
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003831 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3832 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003833 if (networkAgent.clatd != null) {
3834 networkAgent.clatd.fixupLinkProperties(oldLp);
3835 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003836
Paul Jensen992f2522014-04-28 10:33:11 -04003837 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003838 updateMtu(newLp, oldLp);
3839 // TODO - figure out what to do for clat
3840// for (LinkProperties lp : newLp.getStackedLinks()) {
3841// updateMtu(lp, null);
3842// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003843 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003844
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003845 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3846 // In L, we used it only when the network had Internet access but provided no DNS servers.
3847 // For now, just disable it, and if disabling it doesn't break things, remove it.
3848 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3849 // NET_CAPABILITY_INTERNET);
3850 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003851 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003852 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3853
Paul Jensen3b759822014-05-13 11:44:01 -04003854 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003855 if (isDefaultNetwork(networkAgent)) {
3856 handleApplyDefaultProxy(newLp.getHttpProxy());
3857 } else {
3858 updateProxy(newLp, oldLp, networkAgent);
3859 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003860 // TODO - move this check to cover the whole function
3861 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003862 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003863 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3864 }
Paul Jensen3b759822014-05-13 11:44:01 -04003865 }
3866
Lorenzo Colitti95439462014-10-09 13:44:48 +09003867 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3868 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3869 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003870
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003871 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003872 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3873 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003874 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003875 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003876 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003877 }
Paul Jensen992f2522014-04-28 10:33:11 -04003878
3879 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3880 CompareResult<String> interfaceDiff = new CompareResult<String>();
3881 if (oldLp != null) {
3882 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3883 } else if (newLp != null) {
3884 interfaceDiff.added = newLp.getAllInterfaceNames();
3885 }
3886 for (String iface : interfaceDiff.added) {
3887 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003888 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003889 mNetd.addInterfaceToNetwork(iface, netId);
3890 } catch (Exception e) {
3891 loge("Exception adding interface: " + e);
3892 }
3893 }
3894 for (String iface : interfaceDiff.removed) {
3895 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003896 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003897 mNetd.removeInterfaceFromNetwork(iface, netId);
3898 } catch (Exception e) {
3899 loge("Exception removing interface: " + e);
3900 }
3901 }
3902 }
3903
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003904 /**
3905 * Have netd update routes from oldLp to newLp.
3906 * @return true if routes changed between oldLp and newLp
3907 */
3908 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003909 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3910 if (oldLp != null) {
3911 routeDiff = oldLp.compareAllRoutes(newLp);
3912 } else if (newLp != null) {
3913 routeDiff.added = newLp.getAllRoutes();
3914 }
3915
3916 // add routes before removing old in case it helps with continuous connectivity
3917
3918 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3919 for (RouteInfo route : routeDiff.added) {
3920 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003921 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003922 try {
3923 mNetd.addRoute(netId, route);
3924 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003925 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3926 loge("Exception in addRoute for non-gateway: " + e);
3927 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003928 }
3929 }
3930 for (RouteInfo route : routeDiff.added) {
3931 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003932 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003933 try {
3934 mNetd.addRoute(netId, route);
3935 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003936 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3937 loge("Exception in addRoute for gateway: " + e);
3938 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003939 }
3940 }
3941
3942 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003943 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003944 try {
3945 mNetd.removeRoute(netId, route);
3946 } catch (Exception e) {
3947 loge("Exception in removeRoute: " + e);
3948 }
3949 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003950 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003951 }
Erik Kline41368502015-06-17 13:19:54 +09003952
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003953 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3954 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003955 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09003956 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003957 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003958 dnses = new ArrayList();
3959 dnses.add(mDefaultDns);
3960 if (DBG) {
3961 loge("no dns provided for netId " + netId + ", so using defaults");
3962 }
3963 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003964 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003965 try {
3966 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3967 newLp.getDomains());
3968 } catch (Exception e) {
3969 loge("Exception in setDnsServersForNetwork: " + e);
3970 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04003971 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003972 if (defaultNai != null && defaultNai.network.netId == netId) {
3973 setDefaultDnsSystemProperties(dnses);
3974 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003975 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003976 } else if (flush) {
3977 try {
3978 mNetd.flushNetworkDnsCache(netId);
3979 } catch (Exception e) {
3980 loge("Exception in flushNetworkDnsCache: " + e);
3981 }
3982 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003983 }
3984 }
3985
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003986 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3987 int last = 0;
3988 for (InetAddress dns : dnses) {
3989 ++last;
3990 String key = "net.dns" + last;
3991 String value = dns.getHostAddress();
3992 SystemProperties.set(key, value);
3993 }
3994 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3995 String key = "net.dns" + i;
3996 SystemProperties.set(key, "");
3997 }
3998 mNumDnsEntries = last;
3999 }
4000
Paul Jensen3d194ea2015-06-16 14:27:36 -04004001 /**
4002 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4003 * augmented with any stateful capabilities implied from {@code networkAgent}
4004 * (e.g., validated status and captive portal status).
4005 *
Paul Jensene0988542015-06-25 15:30:08 -04004006 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004007 * @param networkCapabilities the new network capabilities.
4008 */
Paul Jensene0988542015-06-25 15:30:08 -04004009 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004010 // Don't modify caller's NetworkCapabilities.
4011 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004012 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004013 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4014 } else {
4015 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4016 }
Paul Jensene0988542015-06-25 15:30:08 -04004017 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004018 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4019 } else {
4020 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4021 }
Paul Jensene0988542015-06-25 15:30:08 -04004022 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4023 final int oldScore = nai.getCurrentScore();
4024 synchronized (nai) {
4025 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004026 }
Paul Jensene0988542015-06-25 15:30:08 -04004027 rematchAllNetworksAndRequests(nai, oldScore);
4028 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004029 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004030 }
4031
Paul Jensenc8b9a742014-09-30 15:37:41 -04004032 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4033 for (int i = 0; i < nai.networkRequests.size(); i++) {
4034 NetworkRequest nr = nai.networkRequests.valueAt(i);
4035 // Don't send listening requests to factories. b/17393458
4036 if (!isRequest(nr)) continue;
4037 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4038 }
4039 }
4040
Robert Greenwalt7b816022014-04-18 15:25:25 -07004041 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4042 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004043 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004044 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4045 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004046 }
4047 }
4048
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004049 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4050 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004051 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004052 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004053 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4054 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004055 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004056 sendIntent(nri.mPendingIntent, intent);
4057 }
4058 // else not handled
4059 }
4060
4061 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4062 mPendingIntentWakeLock.acquire();
4063 try {
4064 if (DBG) log("Sending " + pendingIntent);
4065 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4066 } catch (PendingIntent.CanceledException e) {
4067 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4068 mPendingIntentWakeLock.release();
4069 releasePendingNetworkRequest(pendingIntent);
4070 }
4071 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4072 }
4073
4074 @Override
4075 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4076 String resultData, Bundle resultExtras) {
4077 if (DBG) log("Finished sending " + pendingIntent);
4078 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004079 // Release with a delay so the receiving client has an opportunity to put in its
4080 // own request.
4081 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004082 }
4083
Robert Greenwalt9258c642014-03-26 16:47:06 -07004084 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004085 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004086 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004087 Bundle bundle = new Bundle();
4088 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4089 new NetworkRequest(nri.request));
4090 Message msg = Message.obtain();
4091 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4092 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4093 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4094 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004095 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004096 case ConnectivityManager.CALLBACK_LOSING: {
4097 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4098 break;
4099 }
4100 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4101 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4102 new NetworkCapabilities(networkAgent.networkCapabilities));
4103 break;
4104 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004105 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004106 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4107 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004108 break;
4109 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004110 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004111 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004112 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004113 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004114 if (VDBG) {
4115 log("sending notification " + notifyTypeToName(notificationType) +
4116 " for " + nri.request);
4117 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004118 nri.messenger.send(msg);
4119 } catch (RemoteException e) {
4120 // may occur naturally in the race of binder death.
4121 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4122 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004123 }
4124
Paul Jensenc8b9a742014-09-30 15:37:41 -04004125 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4126 for (int i = 0; i < nai.networkRequests.size(); i++) {
4127 NetworkRequest nr = nai.networkRequests.valueAt(i);
4128 // Ignore listening requests.
4129 if (!isRequest(nr)) continue;
4130 loge("Dead network still had at least " + nr);
4131 break;
4132 }
4133 nai.asyncChannel.disconnect();
4134 }
4135
Robert Greenwalt7b816022014-04-18 15:25:25 -07004136 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4137 if (oldNetwork == null) {
4138 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4139 return;
4140 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004141 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4142 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004143 }
4144
Paul Jensen27b02b72014-07-14 12:03:33 -04004145 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004146 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004147 setupDataActivityTracking(newNetwork);
4148 try {
4149 mNetd.setDefaultNetId(newNetwork.network.netId);
4150 } catch (Exception e) {
4151 loge("Exception setting default network :" + e);
4152 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004153 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004154 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004155 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004156 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004157 }
4158
Paul Jensen2161a8e2014-09-11 11:00:39 -04004159 // Handles a network appearing or improving its score.
4160 //
4161 // - Evaluates all current NetworkRequests that can be
4162 // satisfied by newNetwork, and reassigns to newNetwork
4163 // any such requests for which newNetwork is the best.
4164 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004165 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004166 // needed. A network is needed if it is the best network for
4167 // one or more NetworkRequests, or if it is a VPN.
4168 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004169 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004170 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004171 //
4172 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4173 // networks that have no chance (i.e. even if validated)
4174 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004175 //
4176 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4177 // it does not remove NetworkRequests that other Networks could better satisfy.
4178 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4179 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4180 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004181 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004182 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004183 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4184 // performed to tear down unvalidated networks that have no chance (i.e. even if
4185 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004186 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004187 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004188 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004189 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004190 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004191 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004192 if (DBG) log("rematching " + newNetwork.name());
4193 // Find and migrate to this Network any NetworkRequests for
4194 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004195 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004196 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004197 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004198 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004199 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4200 if (newNetwork == currentNetwork) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004201 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004202 log("Network " + newNetwork.name() + " was already satisfying" +
4203 " request " + nri.request.requestId + ". No change.");
4204 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004205 keep = true;
4206 continue;
4207 }
4208
4209 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004210 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004211 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004212 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004213 // This is not a request, it's a callback listener.
4214 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004215 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004216 continue;
4217 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004218
Robert Greenwalt7b816022014-04-18 15:25:25 -07004219 // next check if it's better than any current network we're using for
4220 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004221 if (VDBG) {
4222 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004223 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4224 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004225 }
4226 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004227 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004228 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004229 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004230 currentNetwork.networkRequests.remove(nri.request.requestId);
4231 currentNetwork.networkLingered.add(nri.request);
4232 affectedNetworks.add(currentNetwork);
4233 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004234 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004235 }
Paul Jensen573a0352015-01-08 10:49:34 -05004236 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004237 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004238 if (!newNetwork.addRequest(nri.request)) {
4239 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4240 }
4241 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004242 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004243 // Tell NetworkFactories about the new score, so they can stop
4244 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004245 // TODO - this could get expensive if we have alot of requests for this
4246 // network. Think about if there is a way to reduce this. Push
4247 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004248 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004249 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004250 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004251 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004252 }
4253 }
4254 }
4255 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004256 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004257 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004258 if (nai.lingering) {
4259 // Already lingered. Nothing to do. This can only happen if "nai" is in
4260 // "affectedNetworks" twice. The reasoning being that to get added to
4261 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4262 // (i.e. not lingered) so it could have only been lingered by this loop.
4263 // unneeded(nai) will be false and we'll call unlinger() below which would
4264 // be bad, so handle it here.
4265 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004266 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004267 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004268 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004269 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004270 }
4271 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004272 if (keep) {
4273 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004274 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004275 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004276 synchronized (ConnectivityService.this) {
4277 // have a new default network, release the transition wakelock in
4278 // a second if it's held. The second pause is to allow apps
4279 // to reconnect over the new network
4280 if (mNetTransitionWakeLock.isHeld()) {
4281 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4282 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4283 mNetTransitionWakeLockSerialNumber, 0),
4284 1000);
4285 }
4286 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004287 }
4288
4289 // do this after the default net is switched, but
4290 // before LegacyTypeTracker sends legacy broadcasts
Paul Jensen3d911462015-06-12 06:40:24 -04004291 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
Robert Greenwalt152ed372014-12-17 17:19:53 -08004292
4293 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004294 // Maintain the illusion: since the legacy API only
4295 // understands one network at a time, we must pretend
4296 // that the current default network disconnected before
4297 // the new one connected.
4298 if (oldDefaultNetwork != null) {
4299 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004300 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004301 }
Paul Jensene0988542015-06-25 15:30:08 -04004302 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004303 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4304 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004305 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004306
4307 // Notify battery stats service about this network, both the normal
4308 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004309 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004310 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004311 final IBatteryStats bs = BatteryStatsService.getService();
4312 final int type = newNetwork.networkInfo.getType();
4313
4314 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4315 bs.noteNetworkInterfaceType(baseIface, type);
4316 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4317 final String stackedIface = stacked.getInterfaceName();
4318 bs.noteNetworkInterfaceType(stackedIface, type);
4319 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4320 }
4321 } catch (RemoteException ignored) {
4322 }
4323
Robert Greenwalt152ed372014-12-17 17:19:53 -08004324 // This has to happen after the notifyNetworkCallbacks as that tickles each
4325 // ConnectivityManager instance so that legacy requests correctly bind dns
4326 // requests to this network. The legacy users are listening for this bcast
4327 // and will generally do a dns request so they can ensureRouteToHost and if
4328 // they do that before the callbacks happen they'll use the default network.
4329 //
4330 // TODO: Is there still a race here? We send the broadcast
4331 // after sending the callback, but if the app can receive the
4332 // broadcast before the callback, it might still break.
4333 //
4334 // This *does* introduce a race where if the user uses the new api
4335 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4336 // they may get old info. Reverse this after the old startUsing api is removed.
4337 // This is on top of the multiple intent sequencing referenced in the todo above.
4338 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4339 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4340 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4341 // legacy type tracker filters out repeat adds
4342 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4343 }
4344 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004345
4346 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4347 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4348 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4349 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4350 if (newNetwork.isVPN()) {
4351 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4352 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004353 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004354 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4355 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004356 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004357 if (DBG) log("Reaping " + nai.name());
4358 teardownUnneededNetwork(nai);
4359 }
4360 }
4361 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004362 }
4363
Paul Jensen1c7ba022015-06-16 14:27:36 -04004364 /**
4365 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4366 * being disconnected.
4367 * @param changed If only one Network's score or capabilities have been modified since the last
4368 * time this function was called, pass this Network in this argument, otherwise pass
4369 * null.
4370 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4371 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4372 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4373 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4374 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004375 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004376 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004377 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4378 // to avoid the slowness. It is not simply enough to process just "changed", for
4379 // example in the case where "changed"'s score decreases and another network should begin
4380 // satifying a NetworkRequest that "changed" currently satisfies.
4381
4382 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4383 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4384 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004385 if (changed != null && oldScore < changed.getCurrentScore()) {
4386 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004387 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004388 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4389 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4390 // Rematch higher scoring networks first to prevent requests first matching a lower
4391 // scoring network and then a higher scoring network, which could produce multiple
4392 // callbacks and inadvertently unlinger networks.
4393 Arrays.sort(nais);
4394 for (NetworkAgentInfo nai : nais) {
4395 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004396 // Only reap the last time through the loop. Reaping before all rematching
4397 // is complete could incorrectly teardown a network that hasn't yet been
4398 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004399 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004400 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004401 }
4402 }
4403 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004404
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004405 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004406 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004407 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004408 // For now only update icons for default connection.
4409 // TODO: Update WiFi and cellular icons separately. b/17237507
4410 if (!isDefaultNetwork(nai)) return;
4411
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004412 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004413 // Don't repeat publish.
4414 if (newInetCondition == mDefaultInetConditionPublished) return;
4415
4416 mDefaultInetConditionPublished = newInetCondition;
4417 sendInetConditionBroadcast(nai.networkInfo);
4418 }
4419
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004420 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4421 if (mLockdownTracker != null) {
4422 if (nai != null && nai.isVPN()) {
4423 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4424 } else {
4425 mLockdownTracker.onNetworkInfoChanged();
4426 }
4427 }
4428 }
4429
Robert Greenwalt7b816022014-04-18 15:25:25 -07004430 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4431 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004432 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004433 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004434 synchronized (networkAgent) {
4435 oldInfo = networkAgent.networkInfo;
4436 networkAgent.networkInfo = newInfo;
4437 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004438 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004439
4440 if (oldInfo != null && oldInfo.getState() == state) {
4441 if (VDBG) log("ignoring duplicate network state non-change");
4442 return;
4443 }
4444 if (DBG) {
4445 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4446 (oldInfo == null ? "null" : oldInfo.getState()) +
4447 " to " + state);
4448 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004449
Paul Jenseneec75412014-08-04 12:21:19 -04004450 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004451 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004452 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004453 if (networkAgent.isVPN()) {
4454 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004455 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4456 (networkAgent.networkMisc == null ||
4457 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004458 } else {
4459 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4460 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004461 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004462 loge("Error creating network " + networkAgent.network.netId + ": "
4463 + e.getMessage());
4464 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004465 }
Paul Jenseneec75412014-08-04 12:21:19 -04004466 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004467 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004468 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004469
Paul Jensenca8f16a2014-05-09 12:47:55 -04004470 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004471 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004472
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004473 if (networkAgent.isVPN()) {
4474 // Temporarily disable the default proxy (not global).
4475 synchronized (mProxyLock) {
4476 if (!mDefaultProxyDisabled) {
4477 mDefaultProxyDisabled = true;
4478 if (mGlobalProxy == null && mDefaultProxy != null) {
4479 sendProxyBroadcast(null);
4480 }
4481 }
4482 }
4483 // TODO: support proxy per network.
4484 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004485
Paul Jensen2161a8e2014-09-11 11:00:39 -04004486 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004487 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004488
4489 // This has to happen after matching the requests, because callbacks are just requests.
4490 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004491 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004492 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004493 if (networkAgent.isVPN()) {
4494 synchronized (mProxyLock) {
4495 if (mDefaultProxyDisabled) {
4496 mDefaultProxyDisabled = false;
4497 if (mGlobalProxy == null && mDefaultProxy != null) {
4498 sendProxyBroadcast(mDefaultProxy);
4499 }
4500 }
4501 }
4502 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004503 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4504 state == NetworkInfo.State.SUSPENDED) {
4505 // going into or coming out of SUSPEND: rescore and notify
4506 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004507 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004508 }
4509 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4510 ConnectivityManager.CALLBACK_SUSPENDED :
4511 ConnectivityManager.CALLBACK_RESUMED));
4512 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004513 }
4514 }
4515
Robert Greenwaltac96c522014-06-03 16:43:57 -07004516 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4517 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004518 if (score < 0) {
4519 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4520 "). Bumping score to min of 0");
4521 score = 0;
4522 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004523
Paul Jensen2161a8e2014-09-11 11:00:39 -04004524 final int oldScore = nai.getCurrentScore();
4525 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004526
Paul Jensen85cf78e2015-06-25 13:25:07 -04004527 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004528
Paul Jensenc8b9a742014-09-30 15:37:41 -04004529 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004530 }
4531
Robert Greenwalt9258c642014-03-26 16:47:06 -07004532 // notify only this one new request of the current state
4533 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4534 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4535 // TODO - read state from monitor to decide what to send.
4536// if (nai.networkMonitor.isLingering()) {
4537// notifyType = NetworkCallbacks.LOSING;
4538// } else if (nai.networkMonitor.isEvaluating()) {
4539// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4540// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004541 if (nri.mPendingIntent == null) {
4542 callCallbackForRequest(nri, nai, notifyType);
4543 } else {
4544 sendPendingIntentForRequest(nri, nai, notifyType);
4545 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004546 }
4547
Robert Greenwalt8d482522015-06-24 13:23:42 -07004548 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004549 // The NetworkInfo we actually send out has no bearing on the real
4550 // state of affairs. For example, if the default connection is mobile,
4551 // and a request for HIPRI has just gone away, we need to pretend that
4552 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4553 // the state to DISCONNECTED, even though the network is of type MOBILE
4554 // and is still connected.
4555 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4556 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004557 if (state != DetailedState.DISCONNECTED) {
4558 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004559 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004560 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004561 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004562 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4563 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4564 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4565 if (info.isFailover()) {
4566 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4567 nai.networkInfo.setFailover(false);
4568 }
4569 if (info.getReason() != null) {
4570 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4571 }
4572 if (info.getExtraInfo() != null) {
4573 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4574 }
4575 NetworkAgentInfo newDefaultAgent = null;
4576 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004577 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004578 if (newDefaultAgent != null) {
4579 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4580 newDefaultAgent.networkInfo);
4581 } else {
4582 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4583 }
4584 }
4585 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4586 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004587 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004588 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004589 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004590 }
4591 }
4592 }
4593
Robert Greenwalt7b816022014-04-18 15:25:25 -07004594 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004595 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004596 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004597 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4598 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4599 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004600 if (nri.mPendingIntent == null) {
4601 callCallbackForRequest(nri, networkAgent, notifyType);
4602 } else {
4603 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4604 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004605 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004606 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004607
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004608 private String notifyTypeToName(int notifyType) {
4609 switch (notifyType) {
4610 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4611 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4612 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4613 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4614 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4615 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4616 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4617 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4618 }
4619 return "UNKNOWN";
4620 }
4621
Jeff Sharkey69736342014-12-08 14:50:12 -08004622 /**
4623 * Notify other system services that set of active ifaces has changed.
4624 */
4625 private void notifyIfacesChanged() {
4626 try {
4627 mStatsService.forceUpdateIfaces();
4628 } catch (Exception ignored) {
4629 }
4630 }
4631
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004632 @Override
4633 public boolean addVpnAddress(String address, int prefixLength) {
4634 throwIfLockdownEnabled();
4635 int user = UserHandle.getUserId(Binder.getCallingUid());
4636 synchronized (mVpns) {
4637 return mVpns.get(user).addAddress(address, prefixLength);
4638 }
4639 }
4640
4641 @Override
4642 public boolean removeVpnAddress(String address, int prefixLength) {
4643 throwIfLockdownEnabled();
4644 int user = UserHandle.getUserId(Binder.getCallingUid());
4645 synchronized (mVpns) {
4646 return mVpns.get(user).removeAddress(address, prefixLength);
4647 }
4648 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004649
4650 @Override
4651 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4652 throwIfLockdownEnabled();
4653 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004654 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004655 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004656 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004657 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004658 if (success) {
4659 notifyIfacesChanged();
4660 }
4661 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004662 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004663
4664 @Override
4665 public void factoryReset() {
4666 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004667
4668 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4669 return;
4670 }
4671
Robin Lee3b3dd942015-05-12 18:14:58 +01004672 final int userId = UserHandle.getCallingUserId();
4673
Stuart Scottf1fb3972015-04-02 18:00:02 -07004674 // Turn airplane mode off
4675 setAirplaneMode(false);
4676
Stuart Scotte3e314d2015-04-20 14:07:45 -07004677 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4678 // Untether
4679 for (String tether : getTetheredIfaces()) {
4680 untether(tether);
4681 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004682 }
4683
Stuart Scotte3e314d2015-04-20 14:07:45 -07004684 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4685 // Turn VPN off
4686 VpnConfig vpnConfig = getVpnConfig(userId);
4687 if (vpnConfig != null) {
4688 if (vpnConfig.legacy) {
4689 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4690 } else {
4691 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4692 // in the future without user intervention.
4693 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004694
Stuart Scotte3e314d2015-04-20 14:07:45 -07004695 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4696 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004697 }
4698 }
4699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700}