blob: 5044ba9ee91ddcce3ab9c662991aefadbda9e4d4 [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 // Arguments to rematchNetworkAndRequests()
224 private enum NascentState {
225 // Indicates a network was just validated for the first time. If the network is found to
226 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
227 JUST_VALIDATED,
228 // Indicates a network was not validated for the first time immediately prior to this call.
229 NOT_JUST_VALIDATED
230 };
231 private enum ReapUnvalidatedNetworks {
232 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
233 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
234 // known that there may be unvalidated networks that could potentially be reaped, and when
235 // all networks have been rematched against all NetworkRequests.
236 REAP,
237 // Don't reap unvalidated networks. This should be passed when it's known that there are
238 // no unvalidated networks that could potentially be reaped, and when some networks have
239 // not yet been rematched against all NetworkRequests.
240 DONT_REAP
241 };
242
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700243 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700244 * used internally to change our mobile data enabled flag
245 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700246 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700247
248 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700249 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700250 * from one net to another. Clear happens when we get a new
251 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
252 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700253 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700254 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700255
Robert Greenwalt434203a2010-10-11 16:00:27 -0700256 /**
257 * used internally to reload global proxy settings
258 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700259 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700260
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700261 /**
Wink Saville628b0852011-08-04 15:01:58 -0700262 * used internally to send a sticky broadcast delayed.
263 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700264 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700265
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700266 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400267 * PAC manager has received new port.
268 */
269 private static final int EVENT_PROXY_HAS_CHANGED = 16;
270
Robert Greenwalte049c232014-04-11 15:53:27 -0700271 /**
272 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700273 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700274 */
275 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
276
Robert Greenwalt7b816022014-04-18 15:25:25 -0700277 /**
278 * used internally when registering NetworkAgents
279 * obj = Messenger
280 */
281 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
282
Robert Greenwalt9258c642014-03-26 16:47:06 -0700283 /**
284 * used to add a network request
285 * includes a NetworkRequestInfo
286 */
287 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
288
289 /**
290 * indicates a timeout period is over - check if we had a network yet or not
291 * and if not, call the timeout calback (but leave the request live until they
292 * cancel it.
293 * includes a NetworkRequestInfo
294 */
295 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
296
297 /**
298 * used to add a network listener - no request
299 * includes a NetworkRequestInfo
300 */
301 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
302
303 /**
304 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400305 * arg1 = UID of caller
306 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700307 */
308 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
309
Robert Greenwalta67be032014-05-16 15:49:14 -0700310 /**
311 * used internally when registering NetworkFactories
312 * obj = Messenger
313 */
314 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
315
Robert Greenwalt27711812014-06-25 16:45:57 -0700316 /**
317 * used internally to expire a wakelock when transitioning
318 * from one net to another. Expire happens when we fail to find
319 * a new network (typically after 1 minute) -
320 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
321 * a replacement network.
322 */
323 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
324
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700325 /**
326 * Used internally to indicate the system is ready.
327 */
328 private static final int EVENT_SYSTEM_READY = 25;
329
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800330 /**
331 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400332 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800333 */
334 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
335
336 /**
337 * used to remove a pending intent and its associated network request.
338 * arg1 = UID of caller
339 * obj = PendingIntent
340 */
341 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
342
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900343 /**
344 * used to specify whether a network should be used even if unvalidated.
345 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
346 * arg2 = whether to remember this choice in the future (1 or 0)
347 * obj = network
348 */
349 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
350
351 /**
352 * used to ask the user to confirm a connection to an unvalidated network.
353 * obj = network
354 */
355 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700356
Erik Klineda4bfa82015-04-30 12:58:40 +0900357 /**
358 * used internally to (re)configure mobile data always-on settings.
359 */
360 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
361
Paul Jensen694f2b82015-06-17 14:15:39 -0400362 /**
363 * used to add a network listener with a pending intent
364 * obj = NetworkRequestInfo
365 */
366 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
367
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700368 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700369 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700370 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700371 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700372
Mike Lockwood0f79b542009-08-14 14:18:49 -0400373 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800374 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400375
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700376 private PowerManager.WakeLock mNetTransitionWakeLock;
377 private String mNetTransitionWakeLockCausedBy = "";
378 private int mNetTransitionWakeLockSerialNumber;
379 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800380 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700381
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700382 private InetAddress mDefaultDns;
383
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700384 // used in DBG mode to track inet condition reports
385 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
386 private ArrayList mInetLog;
387
Robert Greenwalt434203a2010-10-11 16:00:27 -0700388 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400389 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700390 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700391 private boolean mDefaultProxyDisabled = false;
392
Robert Greenwalt434203a2010-10-11 16:00:27 -0700393 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400394 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700395
Jason Monk602b2322013-07-03 17:04:33 -0400396 private PacManager mPacManager = null;
397
Erik Klineda4bfa82015-04-30 12:58:40 +0900398 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700399
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400400 private UserManager mUserManager;
401
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700402 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700403 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700404
Robert Greenwalt50393202011-06-21 17:26:14 -0700405 // the set of network types that can only be enabled by system/sig apps
406 List mProtectedNetworks;
407
John Spurlockbf991a82013-06-24 14:20:23 -0400408 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700409
Wink Savilleab9321d2013-06-29 21:10:57 -0700410 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400411
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700412 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
413 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700414 private final static int MAX_NET_ID = 65535;
415 private int mNextNetId = MIN_NET_ID;
416
Robert Greenwalt34524f02014-05-18 16:22:10 -0700417 // sequence number of NetworkRequests
418 private int mNextNetworkRequestId = 1;
419
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700420 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
421 private static final int MAX_VALIDATION_LOGS = 10;
422 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
423 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
424
425 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
426 synchronized(mValidationLogs) {
427 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
428 mValidationLogs.removeLast();
429 }
430 mValidationLogs.addFirst(new Pair(network, log));
431 }
432 }
433
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700434 /**
435 * Implements support for the legacy "one network per network type" model.
436 *
437 * We used to have a static array of NetworkStateTrackers, one for each
438 * network type, but that doesn't work any more now that we can have,
439 * for example, more that one wifi network. This class stores all the
440 * NetworkAgentInfo objects that support a given type, but the legacy
441 * API will only see the first one.
442 *
443 * It serves two main purposes:
444 *
445 * 1. Provide information about "the network for a given type" (since this
446 * API only supports one).
447 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
448 * the first network for a given type changes, or if the default network
449 * changes.
450 */
451 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900452
453 private static final boolean DBG = true;
454 private static final boolean VDBG = false;
455 private static final String TAG = "CSLegacyTypeTracker";
456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 /**
458 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
459 * Each list holds references to all NetworkAgentInfos that are used to
460 * satisfy requests for that network type.
461 *
462 * This array is built out at startup such that an unsupported network
463 * doesn't get an ArrayList instance, making this a tristate:
464 * unsupported, supported but not active and active.
465 *
466 * The actual lists are populated when we scan the network types that
467 * are supported on this device.
468 */
469 private ArrayList<NetworkAgentInfo> mTypeLists[];
470
471 public LegacyTypeTracker() {
472 mTypeLists = (ArrayList<NetworkAgentInfo>[])
473 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
474 }
475
476 public void addSupportedType(int type) {
477 if (mTypeLists[type] != null) {
478 throw new IllegalStateException(
479 "legacy list for type " + type + "already initialized");
480 }
481 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
482 }
483
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700484 public boolean isTypeSupported(int type) {
485 return isNetworkTypeValid(type) && mTypeLists[type] != null;
486 }
487
488 public NetworkAgentInfo getNetworkForType(int type) {
489 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
490 return mTypeLists[type].get(0);
491 } else {
492 return null;
493 }
494 }
495
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900496 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type,
497 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 if (DBG) {
499 log("Sending " + (connected ? "connected" : "disconnected") +
500 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900501 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900502 }
503 }
504
505 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700506 public void add(int type, NetworkAgentInfo nai) {
507 if (!isTypeSupported(type)) {
508 return; // Invalid network type.
509 }
510 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
511
512 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
513 if (list.contains(nai)) {
514 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
515 return;
516 }
517
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900518 list.add(nai);
519
520 // 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 +0900521 final boolean isDefaultNetwork = isDefaultNetwork(nai);
522 if (list.size() == 1 || isDefaultNetwork) {
523 maybeLogBroadcast(nai, true, type, isDefaultNetwork);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700524 sendLegacyNetworkBroadcast(nai, true, type);
525 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700526 }
527
Lorenzo Colittia793a672014-07-31 23:20:17 +0900528 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900529 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900530 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
531 if (list == null || list.isEmpty()) {
532 return;
533 }
534
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900535 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900536
537 if (!list.remove(nai)) {
538 return;
539 }
540
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900541 if (wasFirstNetwork || wasDefault) {
542 maybeLogBroadcast(nai, false, type, wasDefault);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900543 sendLegacyNetworkBroadcast(nai, false, type);
544 }
545
546 if (!list.isEmpty() && wasFirstNetwork) {
547 if (DBG) log("Other network available for type " + type +
548 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900549 final NetworkAgentInfo replacement = list.get(0);
550 maybeLogBroadcast(replacement, false, type, isDefaultNetwork(replacement));
551 sendLegacyNetworkBroadcast(replacement, false, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900552 }
553 }
554
555 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900556 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
557 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700558 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900559 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 }
561 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700562
Lorenzo Colittia793a672014-07-31 23:20:17 +0900563 private String naiToString(NetworkAgentInfo nai) {
564 String name = (nai != null) ? nai.name() : "null";
565 String state = (nai.networkInfo != null) ?
566 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
567 "???/???";
568 return name + " " + state;
569 }
570
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700571 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900572 pw.println("mLegacyTypeTracker:");
573 pw.increaseIndent();
574 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700575 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900576 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700577 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900578 pw.println();
579 pw.println("Current state:");
580 pw.increaseIndent();
581 for (int type = 0; type < mTypeLists.length; type++) {
582 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
583 for (NetworkAgentInfo nai : mTypeLists[type]) {
584 pw.println(type + " " + naiToString(nai));
585 }
586 }
587 pw.decreaseIndent();
588 pw.decreaseIndent();
589 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700590 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900591
592 // This class needs its own log method because it has a different TAG.
593 private void log(String s) {
594 Slog.d(TAG, s);
595 }
596
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 }
598 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
599
Jeff Sharkey899223b2012-08-04 15:24:58 -0700600 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700601 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800602 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800603
Erik Klineda4bfa82015-04-30 12:58:40 +0900604 mDefaultRequest = createInternetRequestForTransport(-1);
605 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
606 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
607
608 mDefaultMobileDataRequest = createInternetRequestForTransport(
609 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700610
Wink Savillebb08caf2010-09-02 19:23:52 -0700611 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
612 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700613 mHandler = new InternalHandler(handlerThread.getLooper());
614 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700615
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800616 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800617 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
618 String id = Settings.Secure.getString(context.getContentResolver(),
619 Settings.Secure.ANDROID_ID);
620 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700621 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800622 SystemProperties.set("net.hostname", name);
623 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800624 }
625
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700626 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700627 String dns = Settings.Global.getString(context.getContentResolver(),
628 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700629 if (dns == null || dns.length() == 0) {
630 dns = context.getResources().getString(
631 com.android.internal.R.string.config_default_dns_server);
632 }
633 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800634 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
635 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800636 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700637 }
638
Jeremy Joslin79294842014-12-03 17:15:28 -0800639 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
640 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
641
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700642 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700643 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800644 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700645 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700646 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700647 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700648
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700649 try {
650 mPolicyManager.registerListener(mPolicyListener);
651 } catch (RemoteException e) {
652 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700653 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700654 }
655
656 final PowerManager powerManager = (PowerManager) context.getSystemService(
657 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700658 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
659 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
660 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800661 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700662
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700663 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700664
Wink Saville51f456f2013-04-23 14:26:51 -0700665 // TODO: What is the "correct" way to do determine if this is a wifi only device?
666 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
667 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700668 String[] naStrings = context.getResources().getStringArray(
669 com.android.internal.R.array.networkAttributes);
670 for (String naString : naStrings) {
671 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700672 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700673 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700674 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800675 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700676 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700677 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700678 }
Wink Saville51f456f2013-04-23 14:26:51 -0700679 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
680 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
681 n.type);
682 continue;
683 }
Wink Saville975c8482011-04-07 14:23:45 -0700684 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800685 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700686 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700687 continue;
688 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700689 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700690
Wink Saville975c8482011-04-07 14:23:45 -0700691 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700692 mNetworksDefined++;
693 } catch(Exception e) {
694 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700695 }
696 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700697
698 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
699 if (mNetConfigs[TYPE_VPN] == null) {
700 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
701 // don't need to add TYPE_VPN to mNetConfigs.
702 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
703 mNetworksDefined++; // used only in the log() statement below.
704 }
705
Wink Saville5e56bc52013-07-29 15:00:57 -0700706 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700707
Robert Greenwalt50393202011-06-21 17:26:14 -0700708 mProtectedNetworks = new ArrayList<Integer>();
709 int[] protectedNetworks = context.getResources().getIntArray(
710 com.android.internal.R.array.config_protectedNetworks);
711 for (int p : protectedNetworks) {
712 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
713 mProtectedNetworks.add(p);
714 } else {
715 if (DBG) loge("Ignoring protectedNetwork " + p);
716 }
717 }
718
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700719 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
720 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700721
Robert Greenwaltfab501672014-07-23 11:44:01 -0700722 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800723
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700724 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
725
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700726 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700727 IntentFilter intentFilter = new IntentFilter();
728 intentFilter.addAction(Intent.ACTION_USER_STARTING);
729 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
730 mContext.registerReceiverAsUser(
731 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900732
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700733 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700734 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700735 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700736 } catch (RemoteException e) {
737 loge("Error registering observer :" + e);
738 }
739
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700740 if (DBG) {
741 mInetLog = new ArrayList();
742 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700743
Erik Klineda4bfa82015-04-30 12:58:40 +0900744 mSettingsObserver = new SettingsObserver(mContext, mHandler);
745 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800746
John Spurlockbf991a82013-06-24 14:20:23 -0400747 mDataConnectionStats = new DataConnectionStats(mContext);
748 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400749
Jason Monkdecd2952013-10-10 14:02:51 -0400750 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700751
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400752 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700754
Erik Klineda4bfa82015-04-30 12:58:40 +0900755 private NetworkRequest createInternetRequestForTransport(int transportType) {
756 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900757 netCap.addCapability(NET_CAPABILITY_INTERNET);
758 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900759 if (transportType > -1) {
760 netCap.addTransportType(transportType);
761 }
762 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
763 }
764
765 private void handleMobileDataAlwaysOn() {
766 final boolean enable = (Settings.Global.getInt(
767 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
768 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
769 if (enable == isEnabled) {
770 return; // Nothing to do.
771 }
772
773 if (enable) {
774 handleRegisterNetworkRequest(new NetworkRequestInfo(
775 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
776 } else {
777 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
778 }
779 }
780
781 private void registerSettingsCallbacks() {
782 // Watch for global HTTP proxy changes.
783 mSettingsObserver.observe(
784 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
785 EVENT_APPLY_GLOBAL_HTTP_PROXY);
786
787 // Watch for whether or not to keep mobile data always on.
788 mSettingsObserver.observe(
789 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
790 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
791 }
792
Robert Greenwalt34524f02014-05-18 16:22:10 -0700793 private synchronized int nextNetworkRequestId() {
794 return mNextNetworkRequestId++;
795 }
796
Paul Jensen67b0b072015-06-10 11:22:17 -0400797 @VisibleForTesting
798 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400799 synchronized (mNetworkForNetId) {
800 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
801 int netId = mNextNetId;
802 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
803 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500804 if (!mNetIdInUse.get(netId)) {
805 mNetIdInUse.put(netId, true);
806 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400807 }
808 }
809 }
810 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700811 }
812
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800813 private NetworkState getFilteredNetworkState(int networkType, int uid) {
814 NetworkInfo info = null;
815 LinkProperties lp = null;
816 NetworkCapabilities nc = null;
817 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800818 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800819
820 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
821 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
822 if (nai != null) {
823 synchronized (nai) {
824 info = new NetworkInfo(nai.networkInfo);
825 lp = new LinkProperties(nai.linkProperties);
826 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400827 // Network objects are outwardly immutable so there is no point to duplicating.
828 // Duplicating also precludes sharing socket factories and connection pools.
829 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800830 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800831 }
832 info.setType(networkType);
833 } else {
834 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
835 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
836 info.setIsAvailable(true);
837 lp = new LinkProperties();
838 nc = new NetworkCapabilities();
839 network = null;
840 }
841 info = getFilteredNetworkInfo(info, lp, uid);
842 }
843
Jeff Sharkey32566012014-12-02 18:30:14 -0800844 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400845 }
846
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800847 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
848 if (network == null) {
849 return null;
850 }
851 synchronized (mNetworkForNetId) {
852 return mNetworkForNetId.get(network.netId);
853 }
854 };
855
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900856 private Network[] getVpnUnderlyingNetworks(int uid) {
857 if (!mLockdownEnabled) {
858 int user = UserHandle.getUserId(uid);
859 synchronized (mVpns) {
860 Vpn vpn = mVpns.get(user);
861 if (vpn != null && vpn.appliesToUid(uid)) {
862 return vpn.getUnderlyingNetworks();
863 }
864 }
865 }
866 return null;
867 }
868
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800869 private NetworkState getUnfilteredActiveNetworkState(int uid) {
870 NetworkInfo info = null;
871 LinkProperties lp = null;
872 NetworkCapabilities nc = null;
873 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800874 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800875
876 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800877
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900878 final Network[] networks = getVpnUnderlyingNetworks(uid);
879 if (networks != null) {
880 // getUnderlyingNetworks() returns:
881 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
882 // empty array => the VPN explicitly said "no default network".
883 // non-empty array => the VPN specified one or more default networks; we use the
884 // first one.
885 if (networks.length > 0) {
886 nai = getNetworkAgentInfoForNetwork(networks[0]);
887 } else {
888 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800889 }
890 }
891
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800892 if (nai != null) {
893 synchronized (nai) {
894 info = new NetworkInfo(nai.networkInfo);
895 lp = new LinkProperties(nai.linkProperties);
896 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400897 // Network objects are outwardly immutable so there is no point to duplicating.
898 // Duplicating also precludes sharing socket factories and connection pools.
899 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800900 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800901 }
902 }
903
Jeff Sharkey32566012014-12-02 18:30:14 -0800904 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400905 }
906
907 /**
908 * Check if UID should be blocked from using the network with the given LinkProperties.
909 */
910 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700911 final boolean networkCostly;
912 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700913
Robert Greenwalt12e67352014-05-13 21:41:06 -0700914 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700915 synchronized (mRulesLock) {
916 networkCostly = mMeteredIfaces.contains(iface);
917 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700918 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700919
Amith Yamasani15e472352015-04-24 19:06:07 -0700920 if ((uidRules & RULE_REJECT_ALL) != 0
921 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700922 return true;
923 }
924
925 // no restrictive rules; network is visible
926 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700927 }
928
929 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700930 * Return a filtered {@link NetworkInfo}, potentially marked
931 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800932 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700933 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
935 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400936 // network is blocked; clone and override state
937 info = new NetworkInfo(info);
938 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900939 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900940 log("returning Blocked NetworkInfo for ifname=" +
941 lp.getInterfaceName() + ", uid=" + uid);
942 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700943 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800944 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700945 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900946 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700947 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700948 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700949 }
950
951 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 * Return NetworkInfo for the active (i.e., connected) network interface.
953 * It is assumed that at most one network is active at a time. If more
954 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700955 * @return the info for the active network, or {@code null} if none is
956 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700958 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700960 enforceAccessPermission();
961 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800962 NetworkState state = getUnfilteredActiveNetworkState(uid);
963 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 }
965
Paul Jensen31a94f42015-02-13 14:18:39 -0500966 @Override
967 public Network getActiveNetwork() {
968 enforceAccessPermission();
969 final int uid = Binder.getCallingUid();
970 final int user = UserHandle.getUserId(uid);
971 int vpnNetId = NETID_UNSET;
972 synchronized (mVpns) {
973 final Vpn vpn = mVpns.get(user);
974 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
975 }
976 NetworkAgentInfo nai;
977 if (vpnNetId != NETID_UNSET) {
978 synchronized (mNetworkForNetId) {
979 nai = mNetworkForNetId.get(vpnNetId);
980 }
981 if (nai != null) return nai.network;
982 }
983 nai = getDefaultNetwork();
984 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
985 return nai != null ? nai.network : null;
986 }
987
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700988 public NetworkInfo getActiveNetworkInfoUnfiltered() {
989 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800990 final int uid = Binder.getCallingUid();
991 NetworkState state = getUnfilteredActiveNetworkState(uid);
992 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700993 }
994
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700995 @Override
996 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
997 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800998 NetworkState state = getUnfilteredActiveNetworkState(uid);
999 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001000 }
1001
1002 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 public NetworkInfo getNetworkInfo(int networkType) {
1004 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001005 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001006 if (getVpnUnderlyingNetworks(uid) != null) {
1007 // A VPN is active, so we may need to return one of its underlying networks. This
1008 // information is not available in LegacyTypeTracker, so we have to get it from
1009 // getUnfilteredActiveNetworkState.
1010 NetworkState state = getUnfilteredActiveNetworkState(uid);
1011 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1012 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1013 }
1014 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 NetworkState state = getFilteredNetworkState(networkType, uid);
1016 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 }
1018
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001019 @Override
1020 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1021 enforceAccessPermission();
1022 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001023 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001024 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1025 if (nai != null) {
1026 synchronized (nai) {
1027 info = new NetworkInfo(nai.networkInfo);
1028 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001029 }
1030 }
1031 return info;
1032 }
1033
1034 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 public NetworkInfo[] getAllNetworkInfo() {
1036 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001037 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001038 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1039 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001040 NetworkInfo info = getNetworkInfo(networkType);
1041 if (info != null) {
1042 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001045 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 }
1047
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001048 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001049 public Network getNetworkForType(int networkType) {
1050 enforceAccessPermission();
1051 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001052 NetworkState state = getFilteredNetworkState(networkType, uid);
1053 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1054 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001055 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001056 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001057 }
1058
1059 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001060 public Network[] getAllNetworks() {
1061 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001062 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001063 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001064 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001065 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001066 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001067 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001068 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001069 }
1070
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001071 @Override
1072 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1073 // The basic principle is: if an app's traffic could possibly go over a
1074 // network, without the app doing anything multinetwork-specific,
1075 // (hence, by "default"), then include that network's capabilities in
1076 // the array.
1077 //
1078 // In the normal case, app traffic only goes over the system's default
1079 // network connection, so that's the only network returned.
1080 //
1081 // With a VPN in force, some app traffic may go into the VPN, and thus
1082 // over whatever underlying networks the VPN specifies, while other app
1083 // traffic may go over the system default network (e.g.: a split-tunnel
1084 // VPN, or an app disallowed by the VPN), so the set of networks
1085 // returned includes the VPN's underlying networks and the system
1086 // default.
1087 enforceAccessPermission();
1088
1089 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1090
1091 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001092 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001093 if (nc != null) {
1094 result.put(nai.network, nc);
1095 }
1096
1097 if (!mLockdownEnabled) {
1098 synchronized (mVpns) {
1099 Vpn vpn = mVpns.get(userId);
1100 if (vpn != null) {
1101 Network[] networks = vpn.getUnderlyingNetworks();
1102 if (networks != null) {
1103 for (Network network : networks) {
1104 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001105 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001106 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001107 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001108 }
1109 }
1110 }
1111 }
1112 }
1113 }
1114
1115 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1116 out = result.values().toArray(out);
1117 return out;
1118 }
1119
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001120 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001121 public boolean isNetworkSupported(int networkType) {
1122 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001123 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001124 }
1125
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001126 /**
1127 * Return LinkProperties for the active (i.e., connected) default
1128 * network interface. It is assumed that at most one default network
1129 * is active at a time. If more than one is active, it is indeterminate
1130 * which will be returned.
1131 * @return the ip properties for the active network, or {@code null} if
1132 * none is active
1133 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001134 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001135 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001136 enforceAccessPermission();
1137 final int uid = Binder.getCallingUid();
1138 NetworkState state = getUnfilteredActiveNetworkState(uid);
1139 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001140 }
1141
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001142 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001143 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001144 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001145 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1146 if (nai != null) {
1147 synchronized (nai) {
1148 return new LinkProperties(nai.linkProperties);
1149 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001150 }
1151 return null;
1152 }
1153
Robert Greenwalt12e67352014-05-13 21:41:06 -07001154 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001155 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001156 public LinkProperties getLinkProperties(Network network) {
1157 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001158 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001159 if (nai != null) {
1160 synchronized (nai) {
1161 return new LinkProperties(nai.linkProperties);
1162 }
1163 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001164 return null;
1165 }
1166
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001167 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001168 if (nai != null) {
1169 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001170 if (nai.networkCapabilities != null) {
1171 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001172 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001173 }
1174 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001175 return null;
1176 }
1177
1178 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001179 public NetworkCapabilities getNetworkCapabilities(Network network) {
1180 enforceAccessPermission();
1181 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1182 }
1183
1184 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001185 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001186 // Require internal since we're handing out IMSI details
1187 enforceConnectivityInternalPermission();
1188
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001189 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001190 for (Network network : getAllNetworks()) {
1191 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1192 if (nai != null) {
1193 synchronized (nai) {
1194 final String subscriberId = (nai.networkMisc != null)
1195 ? nai.networkMisc.subscriberId : null;
1196 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1197 nai.networkCapabilities, network, subscriberId, null));
1198 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001199 }
1200 }
1201 return result.toArray(new NetworkState[result.size()]);
1202 }
1203
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001204 @Override
1205 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1206 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001207 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001208 final long token = Binder.clearCallingIdentity();
1209 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001210 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1211 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001212 try {
1213 return mPolicyManager.getNetworkQuotaInfo(state);
1214 } catch (RemoteException e) {
1215 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001216 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001217 return null;
1218 } finally {
1219 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001220 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001221 }
1222
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001223 @Override
1224 public boolean isActiveNetworkMetered() {
1225 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001226 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001227 final long token = Binder.clearCallingIdentity();
1228 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001229 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001230 } finally {
1231 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001232 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001233 }
1234
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001235 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1236 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1237 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001238 try {
1239 return mPolicyManager.isNetworkMetered(state);
1240 } catch (RemoteException e) {
1241 }
1242 }
1243 return false;
1244 }
1245
Jeff Sharkey216c1812012-08-05 14:29:23 -07001246 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1247 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001248 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001249 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001250 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001251 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001252 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001253
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001254 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 * Ensure that a network route exists to deliver traffic to the specified
1256 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001257 * @param networkType the type of the network over which traffic to the
1258 * specified host is to be routed
1259 * @param hostAddress the IP address of the host to which the route is
1260 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 * @return {@code true} on success, {@code false} on failure
1262 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001263 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001265 if (mProtectedNetworks.contains(networkType)) {
1266 enforceConnectivityInternalPermission();
1267 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001268
Chad Brubakerc0234532014-02-14 13:24:29 -08001269 InetAddress addr;
1270 try {
1271 addr = InetAddress.getByAddress(hostAddress);
1272 } catch (UnknownHostException e) {
1273 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1274 return false;
1275 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001278 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 return false;
1280 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001281
1282 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1283 if (nai == null) {
1284 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1285 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1286 } else {
1287 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1288 }
1289 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001290 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001291
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001292 DetailedState netState;
1293 synchronized (nai) {
1294 netState = nai.networkInfo.getDetailedState();
1295 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001296
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001297 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001298 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001299 log("requestRouteToHostAddress on down network "
1300 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001301 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001302 }
1303 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001305
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001306 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001307 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001308 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001309 LinkProperties lp;
1310 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001311 synchronized (nai) {
1312 lp = nai.linkProperties;
1313 netId = nai.network.netId;
1314 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001315 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001316 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1317 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001318 } finally {
1319 Binder.restoreCallingIdentity(token);
1320 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001321 }
1322
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001323 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001324 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001325 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001326 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001327 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001328 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001329 if (bestRoute.getGateway().equals(addr)) {
1330 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001331 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001332 } else {
1333 // if we will connect to this through another route, add a direct route
1334 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001335 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001336 }
1337 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001338 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001339 try {
1340 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1341 } catch (Exception e) {
1342 // never crash - catch them all
1343 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001344 return false;
1345 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001346 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 }
1348
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001349 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1350 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001351 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001352 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001353 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001354 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001355 }
1356
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001357 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001358 // skip update when we've already applied rules
1359 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1360 if (oldRules == uidRules) return;
1361
1362 mUidRules.put(uid, uidRules);
1363 }
1364
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001365 // TODO: notify UID when it has requested targeted updates
1366 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001367
1368 @Override
1369 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001370 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001371 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001372 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001373 }
1374
1375 synchronized (mRulesLock) {
1376 mMeteredIfaces.clear();
1377 for (String iface : meteredIfaces) {
1378 mMeteredIfaces.add(iface);
1379 }
1380 }
1381 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001382
1383 @Override
1384 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1385 // caller is NPMS, since we only register with them
1386 if (LOGD_RULES) {
1387 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1388 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001389 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001390 };
1391
Robin Lee3b3dd942015-05-12 18:14:58 +01001392 /**
1393 * Require that the caller is either in the same user or has appropriate permission to interact
1394 * across users.
1395 *
1396 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1397 */
1398 private void enforceCrossUserPermission(int userId) {
1399 if (userId == UserHandle.getCallingUserId()) {
1400 // Not a cross-user call.
1401 return;
1402 }
1403 mContext.enforceCallingOrSelfPermission(
1404 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1405 "ConnectivityService");
1406 }
1407
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001408 private void enforceInternetPermission() {
1409 mContext.enforceCallingOrSelfPermission(
1410 android.Manifest.permission.INTERNET,
1411 "ConnectivityService");
1412 }
1413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001415 mContext.enforceCallingOrSelfPermission(
1416 android.Manifest.permission.ACCESS_NETWORK_STATE,
1417 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419
1420 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001421 mContext.enforceCallingOrSelfPermission(
1422 android.Manifest.permission.CHANGE_NETWORK_STATE,
1423 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001426 private void enforceTetherAccessPermission() {
1427 mContext.enforceCallingOrSelfPermission(
1428 android.Manifest.permission.ACCESS_NETWORK_STATE,
1429 "ConnectivityService");
1430 }
1431
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001432 private void enforceConnectivityInternalPermission() {
1433 mContext.enforceCallingOrSelfPermission(
1434 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1435 "ConnectivityService");
1436 }
1437
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001438 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001439 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001440 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001441 }
1442
1443 private void sendInetConditionBroadcast(NetworkInfo info) {
1444 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1445 }
1446
Wink Saville628b0852011-08-04 15:01:58 -07001447 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001448 if (mLockdownTracker != null) {
1449 info = mLockdownTracker.augmentNetworkInfo(info);
1450 }
1451
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001452 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001453 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001454 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 if (info.isFailover()) {
1456 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1457 info.setFailover(false);
1458 }
1459 if (info.getReason() != null) {
1460 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1461 }
1462 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001463 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1464 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001466 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001467 return intent;
1468 }
1469
1470 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1471 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1472 }
1473
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001474 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001475 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1476 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1477 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001478 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001479 final long ident = Binder.clearCallingIdentity();
1480 try {
1481 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1482 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1483 } finally {
1484 Binder.restoreCallingIdentity(ident);
1485 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001486 }
1487
Mike Lockwood0f79b542009-08-14 14:18:49 -04001488 private void sendStickyBroadcast(Intent intent) {
1489 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001490 if (!mSystemReady) {
1491 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001492 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001493 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001494 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001495 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001496 }
1497
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001498 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001499 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1500 final IBatteryStats bs = BatteryStatsService.getService();
1501 try {
1502 NetworkInfo ni = intent.getParcelableExtra(
1503 ConnectivityManager.EXTRA_NETWORK_INFO);
1504 bs.noteConnectivityChanged(intent.getIntExtra(
1505 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1506 ni != null ? ni.getState().toString() : "?");
1507 } catch (RemoteException e) {
1508 }
1509 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001510 try {
1511 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1512 } finally {
1513 Binder.restoreCallingIdentity(ident);
1514 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001515 }
1516 }
1517
1518 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001519 loadGlobalProxy();
1520
Mike Lockwood0f79b542009-08-14 14:18:49 -04001521 synchronized(this) {
1522 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001523 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001524 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001525 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001526 }
1527 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001528 // load the global proxy at startup
1529 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001530
1531 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1532 // for user to unlock device.
1533 if (!updateLockdownVpn()) {
1534 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1535 mContext.registerReceiver(mUserPresentReceiver, filter);
1536 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001537
Erik Klineda4bfa82015-04-30 12:58:40 +09001538 // Configure whether mobile data is always on.
1539 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1540
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001541 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001542
1543 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001546 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1547 @Override
1548 public void onReceive(Context context, Intent intent) {
1549 // Try creating lockdown tracker, since user present usually means
1550 // unlocked keystore.
1551 if (updateLockdownVpn()) {
1552 mContext.unregisterReceiver(this);
1553 }
1554 }
1555 };
1556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001558 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001559 *
1560 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001561 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001562 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001563 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1564 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001565
1566 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001567 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001568
Robert Greenwalt7b816022014-04-18 15:25:25 -07001569 if (networkAgent.networkCapabilities.hasTransport(
1570 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001571 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1572 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001573 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001574 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001575 } else if (networkAgent.networkCapabilities.hasTransport(
1576 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001577 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1578 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001579 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001580 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001581 } else {
1582 // do not track any other networks
1583 timeout = 0;
1584 }
1585
Robert Greenwalt7b816022014-04-18 15:25:25 -07001586 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001587 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001588 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001589 } catch (Exception e) {
1590 // You shall not crash!
1591 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001592 }
1593 }
1594 }
1595
1596 /**
1597 * Remove data activity tracking when network disconnects.
1598 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001599 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1600 final String iface = networkAgent.linkProperties.getInterfaceName();
1601 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001602
Robert Greenwalt7b816022014-04-18 15:25:25 -07001603 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1604 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001605 try {
1606 // the call fails silently if no idletimer setup for this interface
1607 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001608 } catch (Exception e) {
1609 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001610 }
1611 }
1612 }
1613
1614 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001615 * Reads the network specific MTU size from reources.
1616 * and set it on it's iface.
1617 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001618 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1619 final String iface = newLp.getInterfaceName();
1620 final int mtu = newLp.getMtu();
1621 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1622 if (VDBG) log("identical MTU - not setting");
1623 return;
1624 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001625
Robert Greenwalt43074032014-08-15 17:53:05 -07001626 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001627 loge("Unexpected mtu value: " + mtu + ", " + iface);
1628 return;
1629 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001630
w1997615afd812014-08-05 15:18:11 -07001631 // Cannot set MTU without interface name
1632 if (TextUtils.isEmpty(iface)) {
1633 loge("Setting MTU size with null iface.");
1634 return;
1635 }
1636
Robert Greenwalt7b816022014-04-18 15:25:25 -07001637 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001638 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001639 mNetd.setMtu(iface, mtu);
1640 } catch (Exception e) {
1641 Slog.e(TAG, "exception in setMtu()" + e);
1642 }
1643 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001644
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001645 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001646 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1647
1648 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001649 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001650 protected int getDefaultTcpRwnd() {
1651 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1652 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001653
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001654 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1655 if (isDefaultNetwork(nai) == false) {
1656 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001657 }
1658
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001659 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1660 String[] values = null;
1661 if (tcpBufferSizes != null) {
1662 values = tcpBufferSizes.split(",");
1663 }
1664
1665 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001666 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001667 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1668 values = tcpBufferSizes.split(",");
1669 }
1670
1671 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1672
1673 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001674 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001675
1676 final String prefix = "/sys/kernel/ipv4/tcp_";
1677 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1678 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1679 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1680 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1681 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1682 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1683 mCurrentTcpBufferSizes = tcpBufferSizes;
1684 } catch (IOException e) {
1685 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001686 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001687
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001688 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001689 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001690 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1691 if (rwndValue != 0) {
1692 SystemProperties.set(sysctlKey, rwndValue.toString());
1693 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001694 }
1695
Mattias Falk8b47b362011-08-23 14:15:13 +02001696 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001697 /*
1698 * Tell the VMs to toss their DNS caches
1699 */
1700 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1701 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001702 /*
1703 * Connectivity events can happen before boot has completed ...
1704 */
1705 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001706 final long ident = Binder.clearCallingIdentity();
1707 try {
1708 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1709 } finally {
1710 Binder.restoreCallingIdentity(ident);
1711 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001712 }
1713
Robert Greenwalt562cc542014-05-15 18:07:26 -07001714 @Override
1715 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001716 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1717 NETWORK_RESTORE_DELAY_PROP_NAME);
1718 if(restoreDefaultNetworkDelayStr != null &&
1719 restoreDefaultNetworkDelayStr.length() != 0) {
1720 try {
1721 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1722 } catch (NumberFormatException e) {
1723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001725 // if the system property isn't set, use the value for the apn type
1726 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1727
1728 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1729 (mNetConfigs[networkType] != null)) {
1730 ret = mNetConfigs[networkType].restoreTime;
1731 }
1732 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 }
1734
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001735 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001736 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001737 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001738 }
1739 return false;
1740 }
1741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001743 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1744 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001745 if (mContext.checkCallingOrSelfPermission(
1746 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001748 pw.println("Permission Denial: can't dump ConnectivityService " +
1749 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1750 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 return;
1752 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001753
Erik Kline379747a2015-06-05 17:47:34 +09001754 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001755 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001756 final long DIAG_TIME_MS = 5000;
1757 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1758 // Start gathering diagnostic information.
1759 netDiags.add(new NetworkDiagnostics(
1760 nai.network,
1761 new LinkProperties(nai.linkProperties),
1762 DIAG_TIME_MS));
1763 }
1764
1765 for (NetworkDiagnostics netDiag : netDiags) {
1766 pw.println();
1767 netDiag.waitForMeasurements();
1768 netDiag.dump(pw);
1769 }
1770
1771 return;
1772 }
1773
Lorenzo Colittie3805462015-06-03 11:18:24 +09001774 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001775 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001776 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001777 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001778 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001779 pw.println();
1780
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001781 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1782 pw.print("Active default network: ");
1783 if (defaultNai == null) {
1784 pw.println("none");
1785 } else {
1786 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001788 pw.println();
1789
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001790 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001791 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001792 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1793 pw.println(nai.toString());
1794 pw.increaseIndent();
1795 pw.println("Requests:");
1796 pw.increaseIndent();
1797 for (int i = 0; i < nai.networkRequests.size(); i++) {
1798 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001799 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001800 pw.decreaseIndent();
1801 pw.println("Lingered:");
1802 pw.increaseIndent();
1803 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1804 pw.decreaseIndent();
1805 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001806 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001807 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001808 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001809
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001810 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001811 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001812 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1813 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001814 }
1815 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001816 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001817
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001818 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001819
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001820 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001821 pw.print("mNetTransitionWakeLock: currently " +
1822 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1823 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1824 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1825 } else {
1826 pw.println(", last requested never");
1827 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001828 }
1829 pw.println();
1830
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001831 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001832
Lorenzo Colittie3805462015-06-03 11:18:24 +09001833 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001834 pw.println();
1835 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001836 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001837 for(int i = 0; i < mInetLog.size(); i++) {
1838 pw.println(mInetLog.get(i));
1839 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001840 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001841 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001842
1843 if (argsContain(args, "--short") == false) {
1844 pw.println();
1845 synchronized (mValidationLogs) {
1846 pw.println("mValidationLogs (most recent first):");
1847 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1848 pw.println(p.first);
1849 pw.increaseIndent();
1850 p.second.dump(fd, pw, args);
1851 pw.decreaseIndent();
1852 }
1853 }
1854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
1856
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001857 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001858 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001859 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001860 if (officialNai != null && officialNai.equals(nai)) return true;
1861 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001862 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001863 " - " + nai);
1864 }
1865 return false;
1866 }
1867
Paul Jensenc8b9a742014-09-30 15:37:41 -04001868 private boolean isRequest(NetworkRequest request) {
1869 return mNetworkRequests.get(request).isRequest;
1870 }
1871
Robert Greenwalt42acef32009-08-12 16:08:25 -07001872 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001873 private class NetworkStateTrackerHandler extends Handler {
1874 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001875 super(looper);
1876 }
1877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 @Override
1879 public void handleMessage(Message msg) {
1880 NetworkInfo info;
1881 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001882 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001883 handleAsyncChannelHalfConnect(msg);
1884 break;
1885 }
1886 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1887 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1888 if (nai != null) nai.asyncChannel.disconnect();
1889 break;
1890 }
1891 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1892 handleAsyncChannelDisconnected(msg);
1893 break;
1894 }
1895 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1896 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1897 if (nai == null) {
1898 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1899 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001900 final NetworkCapabilities networkCapabilities =
1901 (NetworkCapabilities)msg.obj;
1902 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1903 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1904 Slog.wtf(TAG, "BUG: " + nai + " has stateful capability.");
1905 }
1906 updateCapabilities(nai, networkCapabilities,
1907 NascentState.NOT_JUST_VALIDATED);
Robert Greenwalte049c232014-04-11 15:53:27 -07001908 }
1909 break;
1910 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001911 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1912 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1913 if (nai == null) {
1914 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1915 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001916 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001917 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001918 "; created=" + nai.created);
1919 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001920 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001921 synchronized (nai) {
1922 nai.linkProperties = (LinkProperties)msg.obj;
1923 }
Paul Jenseneec75412014-08-04 12:21:19 -04001924 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001925 }
1926 break;
1927 }
1928 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1929 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1930 if (nai == null) {
1931 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1932 break;
1933 }
1934 info = (NetworkInfo) msg.obj;
1935 updateNetworkInfo(nai, info);
1936 break;
1937 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001938 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1939 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1940 if (nai == null) {
1941 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1942 break;
1943 }
1944 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001945 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001946 break;
1947 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001948 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1949 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1950 if (nai == null) {
1951 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1952 break;
1953 }
1954 try {
1955 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001956 } catch (Exception e) {
1957 // Never crash!
1958 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001959 }
1960 break;
1961 }
1962 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1963 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1964 if (nai == null) {
1965 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1966 break;
1967 }
1968 try {
1969 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001970 } catch (Exception e) {
1971 // Never crash!
1972 loge("Exception in removeVpnUidRanges: " + e);
1973 }
1974 break;
1975 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001976 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1977 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1978 if (nai == null) {
1979 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1980 break;
1981 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001982 if (nai.created && !nai.networkMisc.explicitlySelected) {
1983 loge("ERROR: created network explicitly selected.");
1984 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001985 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001986 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001987 break;
1988 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001989 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001990 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001991 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1992 final boolean valid =
1993 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04001994 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
1995 if (valid != nai.lastValidated) {
1996 final int oldScore = nai.getCurrentScore();
1997 final NascentState nascent = (valid && !nai.everValidated) ?
1998 NascentState.JUST_VALIDATED : NascentState.NOT_JUST_VALIDATED;
1999 nai.lastValidated = valid;
2000 nai.everValidated |= valid;
2001 updateCapabilities(nai, nai.networkCapabilities, nascent);
2002 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2003 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002004 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002005 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002006 // Let the NetworkAgent know the state of its network
2007 nai.asyncChannel.sendMessage(
2008 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2009 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2010 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002011 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002012 break;
2013 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002014 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002015 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002016 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2017 handleLingerComplete(nai);
2018 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002019 break;
2020 }
Paul Jensen869868be2014-05-15 10:33:05 -04002021 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002022 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002023 final boolean visible = (msg.arg1 != 0);
2024 final NetworkAgentInfo nai;
2025 synchronized (mNetworkForNetId) {
2026 nai = mNetworkForNetId.get(netId);
2027 }
2028 // If captive portal status has changed, update capabilities.
2029 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2030 nai.lastCaptivePortalDetected = visible;
2031 nai.everCaptivePortalDetected |= visible;
Paul Jensen1c7ba022015-06-16 14:27:36 -04002032 updateCapabilities(nai, nai.networkCapabilities,
2033 NascentState.NOT_JUST_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002034 }
2035 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002036 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002037 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002038 if (nai == null) {
2039 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2040 break;
2041 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002042 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002043 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2044 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002045 }
Paul Jensen869868be2014-05-15 10:33:05 -04002046 break;
2047 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002048 }
2049 }
2050 }
2051
Paul Jensen0cc17322014-11-25 15:26:53 -05002052 // Cancel any lingering so the linger timeout doesn't teardown a network.
2053 // This should be called when a network begins satisfying a NetworkRequest.
2054 // Note: depending on what state the NetworkMonitor is in (e.g.,
2055 // if it's awaiting captive portal login, or if validation failed), this
2056 // may trigger a re-evaluation of the network.
2057 private void unlinger(NetworkAgentInfo nai) {
2058 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002059 // If network has never been validated, it cannot have been lingered, so don't bother
2060 // needlessly triggering a re-evaluation.
2061 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002062 nai.networkLingered.clear();
2063 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2064 }
2065
Robert Greenwalt7b816022014-04-18 15:25:25 -07002066 private void handleAsyncChannelHalfConnect(Message msg) {
2067 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002068 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002069 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2070 if (VDBG) log("NetworkFactory connected");
2071 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002072 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002073 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002074 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002075 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002076 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002077 }
2078 } else {
2079 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002080 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002081 }
2082 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2083 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2084 if (VDBG) log("NetworkAgent connected");
2085 // A network agent has requested a connection. Establish the connection.
2086 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2087 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2088 } else {
2089 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002090 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002091 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002092 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002093 synchronized (mNetworkForNetId) {
2094 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002095 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002096 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002097 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002098 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002099 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002100 }
2101 }
2102 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002103
Robert Greenwalt7b816022014-04-18 15:25:25 -07002104 private void handleAsyncChannelDisconnected(Message msg) {
2105 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2106 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002107 if (DBG) {
2108 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2109 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002110 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002111 // TODO - if we move the logic to the network agent (have them disconnect
2112 // because they lost all their requests or because their score isn't good)
2113 // then they would disconnect organically, report their new state and then
2114 // disconnect the channel.
2115 if (nai.networkInfo.isConnected()) {
2116 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2117 null, null);
2118 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002119 final boolean wasDefault = isDefaultNetwork(nai);
2120 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002121 mDefaultInetConditionPublished = 0;
2122 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002123 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002124 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002125 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002126 mNetworkAgentInfos.remove(msg.replyTo);
2127 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002128 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002129 // Remove the NetworkAgent, but don't mark the netId as
2130 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002131 mNetworkForNetId.remove(nai.network.netId);
2132 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 // Since we've lost the network, go through all the requests that
2134 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002135 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002136 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002137 for (int i = 0; i < nai.networkRequests.size(); i++) {
2138 NetworkRequest request = nai.networkRequests.valueAt(i);
2139 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2140 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002141 if (DBG) {
2142 log("Checking for replacement network to handle request " + request );
2143 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002144 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002145 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002146 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002147 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2148 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002149 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002150 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002151 alternative = existing;
2152 }
2153 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002154 if (alternative != null) {
2155 if (DBG) log(" found replacement in " + alternative.name());
2156 if (!toActivate.contains(alternative)) {
2157 toActivate.add(alternative);
2158 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002159 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002160 }
2161 }
2162 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2163 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002164 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002165 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002167 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002168 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002169 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002170 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2171 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002172 }
Paul Jensen62d30802015-06-17 14:42:30 -04002173 if (nai.created) {
2174 // Tell netd to clean up the configuration for this network
2175 // (routing rules, DNS, etc).
2176 // This may be slow as it requires a lot of netd shelling out to ip and
2177 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2178 // after we've rematched networks with requests which should make a potential
2179 // fallback network the default or requested a new network from the
2180 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2181 // long time.
2182 try {
2183 mNetd.removeNetwork(nai.network.netId);
2184 } catch (Exception e) {
2185 loge("Exception removing network: " + e);
2186 }
2187 }
2188 synchronized (mNetworkForNetId) {
2189 mNetIdInUse.delete(nai.network.netId);
2190 }
2191 } else {
2192 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2193 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002194 }
2195 }
2196
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002197 // If this method proves to be too slow then we can maintain a separate
2198 // pendingIntent => NetworkRequestInfo map.
2199 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2200 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2201 Intent intent = pendingIntent.getIntent();
2202 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2203 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2204 if (existingPendingIntent != null &&
2205 existingPendingIntent.getIntent().filterEquals(intent)) {
2206 return entry.getValue();
2207 }
2208 }
2209 return null;
2210 }
2211
2212 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2213 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2214
2215 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2216 if (existingRequest != null) { // remove the existing request.
2217 if (DBG) log("Replacing " + existingRequest.request + " with "
2218 + nri.request + " because their intents matched.");
2219 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2220 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002221 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002222 }
2223
Erik Klineda4bfa82015-04-30 12:58:40 +09002224 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002225 mNetworkRequests.put(nri.request, nri);
2226
Paul Jensen0cc17322014-11-25 15:26:53 -05002227 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2228
Robert Greenwalt9258c642014-03-26 16:47:06 -07002229 // Check for the best currently alive network that satisfies this request
2230 NetworkAgentInfo bestNetwork = null;
2231 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002232 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002233 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002234 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002235 if (!nri.isRequest) {
2236 // Not setting bestNetwork here as a listening NetworkRequest may be
2237 // satisfied by multiple Networks. Instead the request is added to
2238 // each satisfying Network and notified about each.
Paul Jensen3d911462015-06-12 06:40:24 -04002239 if (!network.addRequest(nri.request)) {
2240 Slog.wtf(TAG, "BUG: " + network.name() + " already has " + nri.request);
2241 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002242 notifyNetworkCallback(network, nri);
2243 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002244 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002245 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002246 }
2247 }
2248 }
2249 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002250 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002251 unlinger(bestNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04002252 if (!bestNetwork.addRequest(nri.request)) {
2253 Slog.wtf(TAG, "BUG: " + bestNetwork.name() + " already has " + nri.request);
2254 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07002255 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002256 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002257 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002258 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2259 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002260 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002261
Lorenzo Colittia793a672014-07-31 23:20:17 +09002262 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002263 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002264 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002265 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002266 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002267 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002268 }
2269 }
2270 }
2271
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002272 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2273 int callingUid) {
2274 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2275 if (nri != null) {
2276 handleReleaseNetworkRequest(nri.request, callingUid);
2277 }
2278 }
2279
Paul Jensen99364842014-12-09 11:43:45 -05002280 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2281 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2282 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2283 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2284 private boolean unneeded(NetworkAgentInfo nai) {
2285 if (!nai.created || nai.isVPN()) return false;
2286 boolean unneeded = true;
2287 if (nai.everValidated) {
2288 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2289 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2290 try {
2291 if (isRequest(nr)) unneeded = false;
2292 } catch (Exception e) {
2293 loge("Request " + nr + " not found in mNetworkRequests.");
2294 loge(" it came from request list of " + nai.name());
2295 }
2296 }
2297 } else {
2298 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2299 // If this Network is already the highest scoring Network for a request, or if
2300 // there is hope for it to become one if it validated, then it is needed.
2301 if (nri.isRequest && nai.satisfies(nri.request) &&
2302 (nai.networkRequests.get(nri.request.requestId) != null ||
2303 // Note that this catches two important cases:
2304 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2305 // is currently satisfying the request. This is desirable when
2306 // cellular ends up validating but WiFi does not.
2307 // 2. Unvalidated WiFi will not be reaped when validated cellular
2308 // is currently satsifying the request. This is desirable when
2309 // WiFi ends up validating and out scoring cellular.
2310 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2311 nai.getCurrentScoreAsValidated())) {
2312 unneeded = false;
2313 break;
2314 }
2315 }
2316 }
2317 return unneeded;
2318 }
2319
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002320 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2321 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002322 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002323 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002324 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2325 return;
2326 }
2327 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002328 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002329 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002330 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002331 // Find all networks that are satisfying this request and remove the request
2332 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002333 // TODO - it's my understanding that for a request there is only a single
2334 // network satisfying it, so this loop is wasteful
2335 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002336 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2337 if (nai.networkRequests.get(nri.request.requestId) != null) {
2338 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002339 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002340 log(" Removing from current network " + nai.name() +
2341 ", leaving " + nai.networkRequests.size() +
2342 " requests.");
2343 }
Paul Jensen99364842014-12-09 11:43:45 -05002344 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002345 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002346 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002347 } else {
2348 // suspect there should only be one pass through here
2349 // but if any were kept do the check below
2350 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002351 }
2352 }
2353 }
2354
Robert Greenwalt51481852015-01-08 14:43:31 -08002355 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2356 if (nai != null) {
2357 mNetworkForRequestId.remove(nri.request.requestId);
2358 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002359 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002360 // that a network connected to serve it, even though the network was already
2361 // connected. Now that this request has gone away, we might have to pretend
2362 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002363 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002364 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2365 boolean doRemove = true;
2366 if (wasKept) {
2367 // check if any of the remaining requests for this network are for the
2368 // same legacy type - if so, don't remove the nai
2369 for (int i = 0; i < nai.networkRequests.size(); i++) {
2370 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2371 if (otherRequest.legacyType == nri.request.legacyType &&
2372 isRequest(otherRequest)) {
2373 if (DBG) log(" still have other legacy request - leaving");
2374 doRemove = false;
2375 }
2376 }
2377 }
2378
2379 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002380 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002381 }
2382 }
2383
Robert Greenwalta67be032014-05-16 15:49:14 -07002384 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002385 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2386 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002387 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002388 } else {
2389 // listens don't have a singular affectedNetwork. Check all networks to see
2390 // if this listen request applies and remove it.
2391 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2392 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002393 }
2394 }
2395 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2396 }
2397 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002398
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002399 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2400 enforceConnectivityInternalPermission();
2401 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2402 accept ? 1 : 0, always ? 1: 0, network));
2403 }
2404
2405 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2406 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2407 " accept=" + accept + " always=" + always);
2408
2409 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2410 if (nai == null) {
2411 // Nothing to do.
2412 return;
2413 }
2414
2415 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002416 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002417 return;
2418 }
2419
2420 if (!nai.networkMisc.explicitlySelected) {
2421 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2422 }
2423
2424 if (accept != nai.networkMisc.acceptUnvalidated) {
2425 int oldScore = nai.getCurrentScore();
2426 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen1c7ba022015-06-16 14:27:36 -04002427 rematchAllNetworksAndRequests(nai, oldScore, NascentState.NOT_JUST_VALIDATED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002428 sendUpdatedScoreToFactories(nai);
2429 }
2430
2431 if (always) {
2432 nai.asyncChannel.sendMessage(
2433 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2434 }
2435
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002436 if (!accept) {
2437 // Tell the NetworkAgent that the network does not have Internet access (because that's
2438 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2439 // the future. We do this now because NetworkMonitor might not yet have finished
2440 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2441 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2442 NetworkAgent.INVALID_NETWORK, 0, null);
2443 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2444 // to reconnect to it immediately. http://b/20739299
2445 }
2446
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002447 }
2448
2449 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002450 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002451 mHandler.sendMessageDelayed(
2452 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2453 PROMPT_UNVALIDATED_DELAY_MS);
2454 }
2455
2456 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002457 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002458 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2459
2460 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2461 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002462 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002463 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002464 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2465 return;
2466 }
2467
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002468 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002469 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002470 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2471 intent.setClassName("com.android.settings",
2472 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002473
2474 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2475 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2476 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002477 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002478 }
2479
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002480 private class InternalHandler extends Handler {
2481 public InternalHandler(Looper looper) {
2482 super(looper);
2483 }
2484
2485 @Override
2486 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002487 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002488 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002489 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002490 String causedBy = null;
2491 synchronized (ConnectivityService.this) {
2492 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2493 mNetTransitionWakeLock.isHeld()) {
2494 mNetTransitionWakeLock.release();
2495 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002496 } else {
2497 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002498 }
2499 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002500 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2501 log("Failed to find a new network - expiring NetTransition Wakelock");
2502 } else {
2503 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2504 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002505 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002506 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002507 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002508 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002509 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002510 break;
2511 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002512 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002513 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002514 sendStickyBroadcast(intent);
2515 break;
2516 }
Jason Monkdecd2952013-10-10 14:02:51 -04002517 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002518 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002519 break;
2520 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002521 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002522 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2523 break;
2524 }
2525 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2526 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002527 break;
2528 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002529 case EVENT_REGISTER_NETWORK_AGENT: {
2530 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2531 break;
2532 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002533 case EVENT_REGISTER_NETWORK_REQUEST:
2534 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002535 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002536 break;
2537 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002538 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2539 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002540 handleRegisterNetworkRequestWithIntent(msg);
2541 break;
2542 }
2543 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2544 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2545 break;
2546 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002547 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002548 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002549 break;
2550 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002551 case EVENT_SET_ACCEPT_UNVALIDATED: {
2552 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2553 break;
2554 }
2555 case EVENT_PROMPT_UNVALIDATED: {
2556 handlePromptUnvalidated((Network) msg.obj);
2557 break;
2558 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002559 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2560 handleMobileDataAlwaysOn();
2561 break;
2562 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002563 case EVENT_SYSTEM_READY: {
2564 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2565 nai.networkMonitor.systemReady = true;
2566 }
2567 break;
2568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 }
2570 }
2571 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002572
2573 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002574 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002575 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002576 if (isTetheringSupported()) {
2577 return mTethering.tether(iface);
2578 } else {
2579 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2580 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002581 }
2582
2583 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002584 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002585 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002586
2587 if (isTetheringSupported()) {
2588 return mTethering.untether(iface);
2589 } else {
2590 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2591 }
2592 }
2593
2594 // javadoc from interface
2595 public int getLastTetherError(String iface) {
2596 enforceTetherAccessPermission();
2597
2598 if (isTetheringSupported()) {
2599 return mTethering.getLastTetherError(iface);
2600 } else {
2601 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2602 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002603 }
2604
2605 // TODO - proper iface API for selection by property, inspection, etc
2606 public String[] getTetherableUsbRegexs() {
2607 enforceTetherAccessPermission();
2608 if (isTetheringSupported()) {
2609 return mTethering.getTetherableUsbRegexs();
2610 } else {
2611 return new String[0];
2612 }
2613 }
2614
2615 public String[] getTetherableWifiRegexs() {
2616 enforceTetherAccessPermission();
2617 if (isTetheringSupported()) {
2618 return mTethering.getTetherableWifiRegexs();
2619 } else {
2620 return new String[0];
2621 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002622 }
2623
Danica Chang6fdd0c62010-08-11 14:54:43 -07002624 public String[] getTetherableBluetoothRegexs() {
2625 enforceTetherAccessPermission();
2626 if (isTetheringSupported()) {
2627 return mTethering.getTetherableBluetoothRegexs();
2628 } else {
2629 return new String[0];
2630 }
2631 }
2632
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002633 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002634 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002635 if (isTetheringSupported()) {
2636 return mTethering.setUsbTethering(enable);
2637 } else {
2638 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2639 }
2640 }
2641
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002642 // TODO - move iface listing, queries, etc to new module
2643 // javadoc from interface
2644 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002645 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002646 return mTethering.getTetherableIfaces();
2647 }
2648
2649 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002650 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002651 return mTethering.getTetheredIfaces();
2652 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002653
Robert Greenwalt5a735062010-03-02 17:25:02 -08002654 public String[] getTetheringErroredIfaces() {
2655 enforceTetherAccessPermission();
2656 return mTethering.getErroredIfaces();
2657 }
2658
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002659 public String[] getTetheredDhcpRanges() {
2660 enforceConnectivityInternalPermission();
2661 return mTethering.getTetheredDhcpRanges();
2662 }
2663
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002664 // if ro.tether.denied = true we default to no tethering
2665 // gservices could set the secure setting to 1 though to enable it on a build where it
2666 // had previously been turned off.
2667 public boolean isTetheringSupported() {
2668 enforceTetherAccessPermission();
2669 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002670 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002671 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2672 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002673 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2674 mTethering.getTetherableWifiRegexs().length != 0 ||
2675 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2676 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002677 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002678
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002679 // Called when we lose the default network and have no replacement yet.
2680 // This will automatically be cleared after X seconds or a new default network
2681 // becomes CONNECTED, whichever happens first. The timer is started by the
2682 // first caller and not restarted by subsequent callers.
2683 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002684 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002685 synchronized (this) {
2686 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002687 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002688 mNetTransitionWakeLock.acquire();
2689 mNetTransitionWakeLockCausedBy = forWhom;
2690 }
2691 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002692 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002693 mNetTransitionWakeLockTimeout);
2694 return;
2695 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002696
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002697 // 100 percent is full good, 0 is full bad.
2698 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002699 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002700 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002701 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002702 }
2703
Paul Jensenbfd17b72015-04-07 12:43:13 -04002704 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002705 enforceAccessPermission();
2706 enforceInternetPermission();
2707
Paul Jensenbfd17b72015-04-07 12:43:13 -04002708 NetworkAgentInfo nai;
2709 if (network == null) {
2710 nai = getDefaultNetwork();
2711 } else {
2712 nai = getNetworkAgentInfoForNetwork(network);
2713 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002714 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2715 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2716 return;
2717 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002718 // Revalidate if the app report does not match our current validated state.
2719 if (hasConnectivity == nai.lastValidated) return;
2720 final int uid = Binder.getCallingUid();
2721 if (DBG) {
2722 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2723 ") by " + uid);
2724 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002725 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002726 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2727 // which isn't meant to work on uncreated networks.
2728 if (!nai.created) return;
2729
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002730 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002731
2732 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2733 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002734 }
2735
Paul Jensen25a217c2015-02-27 22:55:47 -05002736 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2737 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2738 enforceConnectivityInternalPermission();
2739 }
2740 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2741 if (nai == null) return;
2742 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2743 actionToken);
2744 }
2745
Paul Jensencee9b512015-05-06 07:32:40 -04002746 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002747 // this information is already available as a world read/writable jvm property
2748 // so this API change wouldn't have a benifit. It also breaks the passing
2749 // of proxy info to all the JVMs.
2750 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002751 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002752 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002753 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2754 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002755 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002756 }
2757
Paul Jensencee9b512015-05-06 07:32:40 -04002758 public ProxyInfo getProxyForNetwork(Network network) {
2759 if (network == null) return getDefaultProxy();
2760 final ProxyInfo globalProxy = getGlobalProxy();
2761 if (globalProxy != null) return globalProxy;
2762 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2763 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2764 // caller may not have.
2765 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2766 if (nai == null) return null;
2767 synchronized (nai) {
2768 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2769 if (proxyInfo == null) return null;
2770 return new ProxyInfo(proxyInfo);
2771 }
2772 }
2773
Paul Jensene0bef712014-12-10 15:12:18 -05002774 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2775 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2776 // proxy is null then there is no proxy in place).
2777 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2778 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2779 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2780 proxy = null;
2781 }
2782 return proxy;
2783 }
2784
2785 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2786 // better for determining if a new proxy broadcast is necessary:
2787 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2788 // avoid unnecessary broadcasts.
2789 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2790 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2791 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2792 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2793 // all set.
2794 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2795 a = canonicalizeProxyInfo(a);
2796 b = canonicalizeProxyInfo(b);
2797 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2798 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2799 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2800 }
2801
Jason Monk207900c2014-04-25 15:00:09 -04002802 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002803 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002804
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002805 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002806 if (proxyProperties == mGlobalProxy) return;
2807 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2808 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2809
2810 String host = "";
2811 int port = 0;
2812 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002813 String pacFileUrl = "";
2814 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002815 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002816 if (!proxyProperties.isValid()) {
2817 if (DBG)
2818 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2819 return;
2820 }
Jason Monk207900c2014-04-25 15:00:09 -04002821 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002822 host = mGlobalProxy.getHost();
2823 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002824 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002825 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002826 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002827 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002828 } else {
2829 mGlobalProxy = null;
2830 }
2831 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002832 final long token = Binder.clearCallingIdentity();
2833 try {
2834 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2835 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2836 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2837 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002838 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002839 } finally {
2840 Binder.restoreCallingIdentity(token);
2841 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002842
Jason Monkcf0f97a2014-10-02 15:39:38 -04002843 if (mGlobalProxy == null) {
2844 proxyProperties = mDefaultProxy;
2845 }
2846 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002847 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002848 }
2849
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002850 private void loadGlobalProxy() {
2851 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002852 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2853 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2854 String exclList = Settings.Global.getString(res,
2855 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002856 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2857 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002858 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002859 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002860 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002861 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002862 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002863 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002864 if (!proxyProperties.isValid()) {
2865 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2866 return;
2867 }
2868
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002869 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002870 mGlobalProxy = proxyProperties;
2871 }
2872 }
2873 }
2874
Jason Monk207900c2014-04-25 15:00:09 -04002875 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002876 // this information is already available as a world read/writable jvm property
2877 // so this API change wouldn't have a benifit. It also breaks the passing
2878 // of proxy info to all the JVMs.
2879 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002880 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002881 return mGlobalProxy;
2882 }
2883 }
2884
Jason Monk207900c2014-04-25 15:00:09 -04002885 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002886 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002887 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002888 proxy = null;
2889 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002890 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002891 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002892 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002893 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002894 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2895 return;
2896 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002897
2898 // This call could be coming from the PacManager, containing the port of the local
2899 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2900 // global (to get the correct local port), and send a broadcast.
2901 // TODO: Switch PacManager to have its own message to send back rather than
2902 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002903 if ((mGlobalProxy != null) && (proxy != null)
2904 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002905 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2906 mGlobalProxy = proxy;
2907 sendProxyBroadcast(mGlobalProxy);
2908 return;
2909 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002910 mDefaultProxy = proxy;
2911
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002912 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002913 if (!mDefaultProxyDisabled) {
2914 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002915 }
2916 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002917 }
2918
Paul Jensene0bef712014-12-10 15:12:18 -05002919 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2920 // This method gets called when any network changes proxy, but the broadcast only ever contains
2921 // the default proxy (even if it hasn't changed).
2922 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2923 // world where an app might be bound to a non-default network.
2924 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2925 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2926 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2927
2928 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2929 sendProxyBroadcast(getDefaultProxy());
2930 }
2931 }
2932
Robert Greenwalt434203a2010-10-11 16:00:27 -07002933 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002934 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2935 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002936 if (!TextUtils.isEmpty(proxy)) {
2937 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002938 if (data.length == 0) {
2939 return;
2940 }
2941
Robert Greenwalt434203a2010-10-11 16:00:27 -07002942 String proxyHost = data[0];
2943 int proxyPort = 8080;
2944 if (data.length > 1) {
2945 try {
2946 proxyPort = Integer.parseInt(data[1]);
2947 } catch (NumberFormatException e) {
2948 return;
2949 }
2950 }
Jason Monk207900c2014-04-25 15:00:09 -04002951 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002952 setGlobalProxy(p);
2953 }
2954 }
2955
Jason Monk207900c2014-04-25 15:00:09 -04002956 private void sendProxyBroadcast(ProxyInfo proxy) {
2957 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002958 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002959 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002960 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002961 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2962 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002963 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002964 final long ident = Binder.clearCallingIdentity();
2965 try {
2966 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2967 } finally {
2968 Binder.restoreCallingIdentity(ident);
2969 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002970 }
2971
2972 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002973 final private HashMap<Uri, Integer> mUriEventMap;
2974 final private Context mContext;
2975 final private Handler mHandler;
2976
2977 SettingsObserver(Context context, Handler handler) {
2978 super(null);
2979 mUriEventMap = new HashMap<Uri, Integer>();
2980 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002981 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002982 }
2983
Erik Klineda4bfa82015-04-30 12:58:40 +09002984 void observe(Uri uri, int what) {
2985 mUriEventMap.put(uri, what);
2986 final ContentResolver resolver = mContext.getContentResolver();
2987 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002988 }
2989
2990 @Override
2991 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002992 Slog.wtf(TAG, "Should never be reached.");
2993 }
2994
2995 @Override
2996 public void onChange(boolean selfChange, Uri uri) {
2997 final Integer what = mUriEventMap.get(uri);
2998 if (what != null) {
2999 mHandler.obtainMessage(what.intValue()).sendToTarget();
3000 } else {
3001 loge("No matching event to send for URI=" + uri);
3002 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003003 }
3004 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003005
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003006 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003007 Slog.d(TAG, s);
3008 }
3009
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003010 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003011 Slog.e(TAG, s);
3012 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003013
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003014 private static <T> T checkNotNull(T value, String message) {
3015 if (value == null) {
3016 throw new NullPointerException(message);
3017 }
3018 return value;
3019 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003020
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003021 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003022 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003023 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3024 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3025 *
3026 * @param oldPackage Package name of the application which currently controls VPN, which will
3027 * be replaced. If there is no such application, this should should either be
3028 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3029 * @param newPackage Package name of the application which should gain control of VPN, or
3030 * {@code null} to disable.
3031 * @param userId User for whom to prepare the new VPN.
3032 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003033 * @hide
3034 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003035 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003036 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3037 int userId) {
3038 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003039 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003040
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003041 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003042 Vpn vpn = mVpns.get(userId);
3043 if (vpn != null) {
3044 return vpn.prepare(oldPackage, newPackage);
3045 } else {
3046 return false;
3047 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003048 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003049 }
3050
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003051 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003052 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3053 * This method is used by system-privileged apps.
3054 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3055 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3056 *
3057 * @param packageName The package for which authorization state should change.
3058 * @param userId User for whom {@code packageName} is installed.
3059 * @param authorized {@code true} if this app should be able to start a VPN connection without
3060 * explicit user approval, {@code false} if not.
3061 *
Jeff Davidson05542602014-08-11 14:07:27 -07003062 * @hide
3063 */
3064 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003065 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3066 enforceCrossUserPermission(userId);
3067
Jeff Davidson05542602014-08-11 14:07:27 -07003068 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003069 Vpn vpn = mVpns.get(userId);
3070 if (vpn != null) {
3071 vpn.setPackageAuthorization(packageName, authorized);
3072 }
Jeff Davidson05542602014-08-11 14:07:27 -07003073 }
3074 }
3075
3076 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003077 * Configure a TUN interface and return its file descriptor. Parameters
3078 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003079 * and not available in ConnectivityManager. Permissions are checked in
3080 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003081 * @hide
3082 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003083 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003084 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003085 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003086 int user = UserHandle.getUserId(Binder.getCallingUid());
3087 synchronized(mVpns) {
3088 return mVpns.get(user).establish(config);
3089 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003090 }
3091
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003092 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003093 * Start legacy VPN, controlling native daemons as needed. Creates a
3094 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003095 */
3096 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003097 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003098 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003099 final LinkProperties egress = getActiveLinkProperties();
3100 if (egress == null) {
3101 throw new IllegalStateException("Missing active network connection");
3102 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003103 int user = UserHandle.getUserId(Binder.getCallingUid());
3104 synchronized(mVpns) {
3105 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3106 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003107 }
3108
3109 /**
3110 * Return the information of the ongoing legacy VPN. This method is used
3111 * by VpnSettings and not available in ConnectivityManager. Permissions
3112 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003113 */
3114 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003115 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3116 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003117 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003118 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003119 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003120 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003121 }
3122
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003123 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003124 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3125 * and not available in ConnectivityManager.
3126 */
3127 @Override
3128 public VpnInfo[] getAllVpnInfo() {
3129 enforceConnectivityInternalPermission();
3130 if (mLockdownEnabled) {
3131 return new VpnInfo[0];
3132 }
3133
3134 synchronized(mVpns) {
3135 List<VpnInfo> infoList = new ArrayList<>();
3136 for (int i = 0; i < mVpns.size(); i++) {
3137 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3138 if (info != null) {
3139 infoList.add(info);
3140 }
3141 }
3142 return infoList.toArray(new VpnInfo[infoList.size()]);
3143 }
3144 }
3145
3146 /**
3147 * @return VPN information for accounting, or null if we can't retrieve all required
3148 * information, e.g primary underlying iface.
3149 */
3150 @Nullable
3151 private VpnInfo createVpnInfo(Vpn vpn) {
3152 VpnInfo info = vpn.getVpnInfo();
3153 if (info == null) {
3154 return null;
3155 }
3156 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3157 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3158 // the underlyingNetworks list.
3159 if (underlyingNetworks == null) {
3160 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3161 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3162 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3163 }
3164 } else if (underlyingNetworks.length > 0) {
3165 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3166 if (linkProperties != null) {
3167 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3168 }
3169 }
3170 return info.primaryUnderlyingIface == null ? null : info;
3171 }
3172
3173 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003174 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3175 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003176 * Permissions are checked in Vpn class.
3177 * @hide
3178 */
3179 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003180 public VpnConfig getVpnConfig(int userId) {
3181 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003182 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003183 Vpn vpn = mVpns.get(userId);
3184 if (vpn != null) {
3185 return vpn.getVpnConfig();
3186 } else {
3187 return null;
3188 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003189 }
3190 }
3191
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003192 @Override
3193 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003194 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3195 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3196 return false;
3197 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003198
3199 // Tear down existing lockdown if profile was removed
3200 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3201 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003202 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003203 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3204 return false;
3205 }
3206
3207 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3208 final VpnProfile profile = VpnProfile.decode(
3209 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003210 int user = UserHandle.getUserId(Binder.getCallingUid());
3211 synchronized(mVpns) {
3212 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3213 profile));
3214 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003215 } else {
3216 setLockdownTracker(null);
3217 }
3218
3219 return true;
3220 }
3221
3222 /**
3223 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3224 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3225 */
3226 private void setLockdownTracker(LockdownVpnTracker tracker) {
3227 // Shutdown any existing tracker
3228 final LockdownVpnTracker existing = mLockdownTracker;
3229 mLockdownTracker = null;
3230 if (existing != null) {
3231 existing.shutdown();
3232 }
3233
3234 try {
3235 if (tracker != null) {
3236 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003237 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003238 mLockdownTracker = tracker;
3239 mLockdownTracker.init();
3240 } else {
3241 mNetd.setFirewallEnabled(false);
3242 }
3243 } catch (RemoteException e) {
3244 // ignored; NMS lives inside system_server
3245 }
3246 }
3247
3248 private void throwIfLockdownEnabled() {
3249 if (mLockdownEnabled) {
3250 throw new IllegalStateException("Unavailable in lockdown mode");
3251 }
3252 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003253
Wink Savilleab9321d2013-06-29 21:10:57 -07003254 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003255 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003256 // TODO: Remove? Any reason to trigger a provisioning check?
3257 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003258 }
3259
3260 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003261 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003262
Paul Jensen89e0f092014-09-15 15:59:36 -04003263 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003264 if (DBG) {
3265 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003266 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003267 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003268 Intent intent = new Intent(action);
3269 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003270 // Concatenate the range of types onto the range of NetIDs.
3271 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003272 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003273 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003274 }
3275
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003276 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003277 * Show or hide network provisioning notifications.
3278 *
3279 * We use notifications for two purposes: to notify that a network requires sign in
3280 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3281 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3282 * particular network we can display the notification type that was most recently requested.
3283 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3284 * might first display NO_INTERNET, and then when the captive portal check completes, display
3285 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003286 *
3287 * @param id an identifier that uniquely identifies this notification. This must match
3288 * between show and hide calls. We use the NetID value but for legacy callers
3289 * we concatenate the range of types with the range of NetIDs.
3290 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003291 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003292 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3293 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003294 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003295 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3296 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003297 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003298 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003299
3300 Resources r = Resources.getSystem();
3301 NotificationManager notificationManager = (NotificationManager) mContext
3302 .getSystemService(Context.NOTIFICATION_SERVICE);
3303
3304 if (visible) {
3305 CharSequence title;
3306 CharSequence details;
3307 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003308 if (notifyType == NotificationType.NO_INTERNET &&
3309 networkType == ConnectivityManager.TYPE_WIFI) {
3310 title = r.getString(R.string.wifi_no_internet, 0);
3311 details = r.getString(R.string.wifi_no_internet_detailed);
3312 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3313 } else if (notifyType == NotificationType.SIGN_IN) {
3314 switch (networkType) {
3315 case ConnectivityManager.TYPE_WIFI:
3316 title = r.getString(R.string.wifi_available_sign_in, 0);
3317 details = r.getString(R.string.network_available_sign_in_detailed,
3318 extraInfo);
3319 icon = R.drawable.stat_notify_wifi_in_range;
3320 break;
3321 case ConnectivityManager.TYPE_MOBILE:
3322 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3323 title = r.getString(R.string.network_available_sign_in, 0);
3324 // TODO: Change this to pull from NetworkInfo once a printable
3325 // name has been added to it
3326 details = mTelephonyManager.getNetworkOperatorName();
3327 icon = R.drawable.stat_notify_rssi_in_range;
3328 break;
3329 default:
3330 title = r.getString(R.string.network_available_sign_in, 0);
3331 details = r.getString(R.string.network_available_sign_in_detailed,
3332 extraInfo);
3333 icon = R.drawable.stat_notify_rssi_in_range;
3334 break;
3335 }
3336 } else {
3337 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3338 + getNetworkTypeName(networkType));
3339 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003340 }
3341
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003342 Notification notification = new Notification.Builder(mContext)
3343 .setWhen(0)
3344 .setSmallIcon(icon)
3345 .setAutoCancel(true)
3346 .setTicker(title)
3347 .setColor(mContext.getColor(
3348 com.android.internal.R.color.system_notification_accent_color))
3349 .setContentTitle(title)
3350 .setContentText(details)
3351 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003352 .setLocalOnly(true)
3353 .setPriority(highPriority ?
3354 Notification.PRIORITY_HIGH :
3355 Notification.PRIORITY_DEFAULT)
3356 .setDefaults(Notification.DEFAULT_ALL)
3357 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003358 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003359
Wink Saville948282b2013-08-29 08:55:16 -07003360 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003361 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003362 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003363 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003364 npe.printStackTrace();
3365 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003366 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003367 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003368 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003369 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003370 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003371 npe.printStackTrace();
3372 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003373 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003374 }
3375
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003376 /** Location to an updatable file listing carrier provisioning urls.
3377 * An example:
3378 *
3379 * <?xml version="1.0" encoding="utf-8"?>
3380 * <provisioningUrls>
3381 * <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 -07003382 * </provisioningUrls>
3383 */
3384 private static final String PROVISIONING_URL_PATH =
3385 "/data/misc/radio/provisioning_urls.xml";
3386 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003387
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003388 /** XML tag for root element. */
3389 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3390 /** XML tag for individual url */
3391 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003392 /** XML attribute for mcc */
3393 private static final String ATTR_MCC = "mcc";
3394 /** XML attribute for mnc */
3395 private static final String ATTR_MNC = "mnc";
3396
Paul Jensen434dde82015-06-11 09:43:30 -04003397 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003398 FileReader fileReader = null;
3399 XmlPullParser parser = null;
3400 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003401
3402 try {
3403 fileReader = new FileReader(mProvisioningUrlFile);
3404 parser = Xml.newPullParser();
3405 parser.setInput(fileReader);
3406 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3407
3408 while (true) {
3409 XmlUtils.nextElement(parser);
3410
3411 String element = parser.getName();
3412 if (element == null) break;
3413
Paul Jensen434dde82015-06-11 09:43:30 -04003414 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003415 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3416 try {
3417 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3418 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3419 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3420 parser.next();
3421 if (parser.getEventType() == XmlPullParser.TEXT) {
3422 return parser.getText();
3423 }
3424 }
3425 }
3426 } catch (NumberFormatException e) {
3427 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3428 }
3429 }
3430 }
3431 return null;
3432 } catch (FileNotFoundException e) {
3433 loge("Carrier Provisioning Urls file not found");
3434 } catch (XmlPullParserException e) {
3435 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3436 } catch (IOException e) {
3437 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3438 } finally {
3439 if (fileReader != null) {
3440 try {
3441 fileReader.close();
3442 } catch (IOException e) {}
3443 }
3444 }
3445 return null;
3446 }
3447
Wink Saville42d4f082013-07-20 20:31:59 -07003448 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003449 public String getMobileProvisioningUrl() {
3450 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003451 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003452 if (TextUtils.isEmpty(url)) {
3453 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003454 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003455 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003456 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003457 }
Wink Saville8cf35602013-07-10 23:00:07 -07003458 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003459 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003460 String phoneNumber = mTelephonyManager.getLine1Number();
3461 if (TextUtils.isEmpty(phoneNumber)) {
3462 phoneNumber = "0000000000";
3463 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003464 url = String.format(url,
3465 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3466 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003467 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003468 }
3469
Wink Savilleab9321d2013-06-29 21:10:57 -07003470 return url;
3471 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003472
Wink Saville948282b2013-08-29 08:55:16 -07003473 @Override
3474 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003475 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003476 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003477 final long ident = Binder.clearCallingIdentity();
3478 try {
3479 setProvNotificationVisible(visible, networkType, action);
3480 } finally {
3481 Binder.restoreCallingIdentity(ident);
3482 }
Wink Saville948282b2013-08-29 08:55:16 -07003483 }
Wink Saville7788c612013-08-29 14:57:08 -07003484
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003485 @Override
3486 public void setAirplaneMode(boolean enable) {
3487 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003488 final long ident = Binder.clearCallingIdentity();
3489 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003490 final ContentResolver cr = mContext.getContentResolver();
3491 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3492 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3493 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003494 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003495 } finally {
3496 Binder.restoreCallingIdentity(ident);
3497 }
3498 }
3499
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003500 private void onUserStart(int userId) {
3501 synchronized(mVpns) {
3502 Vpn userVpn = mVpns.get(userId);
3503 if (userVpn != null) {
3504 loge("Starting user already has a VPN");
3505 return;
3506 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003507 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003508 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003509 }
3510 }
3511
3512 private void onUserStop(int userId) {
3513 synchronized(mVpns) {
3514 Vpn userVpn = mVpns.get(userId);
3515 if (userVpn == null) {
3516 loge("Stopping user has no VPN");
3517 return;
3518 }
3519 mVpns.delete(userId);
3520 }
3521 }
3522
3523 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3524 @Override
3525 public void onReceive(Context context, Intent intent) {
3526 final String action = intent.getAction();
3527 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3528 if (userId == UserHandle.USER_NULL) return;
3529
3530 if (Intent.ACTION_USER_STARTING.equals(action)) {
3531 onUserStart(userId);
3532 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3533 onUserStop(userId);
3534 }
3535 }
3536 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003537
Robert Greenwalta67be032014-05-16 15:49:14 -07003538 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3539 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003540 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3541 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003542
Robert Greenwalta67be032014-05-16 15:49:14 -07003543 private static class NetworkFactoryInfo {
3544 public final String name;
3545 public final Messenger messenger;
3546 public final AsyncChannel asyncChannel;
3547
3548 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3549 this.name = name;
3550 this.messenger = messenger;
3551 this.asyncChannel = asyncChannel;
3552 }
3553 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003554
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003555 /**
3556 * Tracks info about the requester.
3557 * Also used to notice when the calling process dies so we can self-expire
3558 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003559 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3560 static final boolean REQUEST = true;
3561 static final boolean LISTEN = false;
3562
3563 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003564 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003565 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003566 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003567 final int mPid;
3568 final int mUid;
3569 final Messenger messenger;
3570 final boolean isRequest;
3571
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003572 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3573 request = r;
3574 mPendingIntent = pi;
3575 messenger = null;
3576 mBinder = null;
3577 mPid = getCallingPid();
3578 mUid = getCallingUid();
3579 this.isRequest = isRequest;
3580 }
3581
Robert Greenwalt9258c642014-03-26 16:47:06 -07003582 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3583 super();
3584 messenger = m;
3585 request = r;
3586 mBinder = binder;
3587 mPid = getCallingPid();
3588 mUid = getCallingUid();
3589 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003590 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003591
3592 try {
3593 mBinder.linkToDeath(this, 0);
3594 } catch (RemoteException e) {
3595 binderDied();
3596 }
3597 }
3598
3599 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003600 if (mBinder != null) {
3601 mBinder.unlinkToDeath(this, 0);
3602 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003603 }
3604
3605 public void binderDied() {
3606 log("ConnectivityService NetworkRequestInfo binderDied(" +
3607 request + ", " + mBinder + ")");
3608 releaseNetworkRequest(request);
3609 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003610
3611 public String toString() {
3612 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003613 mPid + " for " + request +
3614 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003615 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003616 }
3617
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003618 private void ensureImmutableCapabilities(NetworkCapabilities networkCapabilities) {
3619 if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
3620 throw new IllegalArgumentException(
3621 "Cannot request network with NET_CAPABILITY_VALIDATED");
3622 }
3623 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
3624 throw new IllegalArgumentException(
3625 "Cannot request network with NET_CAPABILITY_CAPTIVE_PORTAL");
3626 }
3627 }
3628
Robert Greenwalt9258c642014-03-26 16:47:06 -07003629 @Override
3630 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003631 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003632 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003633 enforceNetworkRequestPermissions(networkCapabilities);
3634 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003635 ensureImmutableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003636
Robert Greenwalt6078b502014-06-11 16:05:07 -07003637 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003638 throw new IllegalArgumentException("Bad timeout specified");
3639 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003640
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003641 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3642 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003643 if (DBG) log("requestNetwork for " + networkRequest);
3644 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3645 NetworkRequestInfo.REQUEST);
3646
3647 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003648 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003649 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003650 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003651 }
3652 return networkRequest;
3653 }
3654
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003655 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003656 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003657 enforceConnectivityInternalPermission();
3658 } else {
3659 enforceChangePermission();
3660 }
3661 }
3662
fenglub15e72b2015-03-20 11:29:56 -07003663 @Override
fengludb571472015-04-21 17:12:05 -07003664 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003665 enforceAccessPermission();
3666 NetworkAgentInfo nai = null;
3667 if (network == null) {
3668 return false;
3669 }
3670 synchronized (mNetworkForNetId) {
3671 nai = mNetworkForNetId.get(network.netId);
3672 }
3673 if (nai != null) {
3674 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3675 return true;
3676 }
3677 return false;
3678 }
3679
3680
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003681 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3682 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003683 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003684 final int uidRules;
3685 final int uid = Binder.getCallingUid();
3686 synchronized(mRulesLock) {
3687 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3688 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003689 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003690 // we could silently fail or we can filter the available nets to only give
3691 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003692 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003693 }
3694 }
3695 }
3696
Robert Greenwalt9258c642014-03-26 16:47:06 -07003697 @Override
3698 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3699 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003700 checkNotNull(operation, "PendingIntent cannot be null.");
3701 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3702 enforceNetworkRequestPermissions(networkCapabilities);
3703 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003704 ensureImmutableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003705
3706 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3707 nextNetworkRequestId());
3708 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3709 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3710 NetworkRequestInfo.REQUEST);
3711 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3712 nri));
3713 return networkRequest;
3714 }
3715
Jeremy Joslin79294842014-12-03 17:15:28 -08003716 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3717 mHandler.sendMessageDelayed(
3718 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3719 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3720 }
3721
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003722 @Override
3723 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003724 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003725 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3726 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003727 }
3728
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003729 // In order to implement the compatibility measure for pre-M apps that call
3730 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3731 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3732 // This ensures it has permission to do so.
3733 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3734 if (nc == null) {
3735 return false;
3736 }
3737 int[] transportTypes = nc.getTransportTypes();
3738 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3739 return false;
3740 }
3741 try {
3742 mContext.enforceCallingOrSelfPermission(
3743 android.Manifest.permission.ACCESS_WIFI_STATE,
3744 "ConnectivityService");
3745 } catch (SecurityException e) {
3746 return false;
3747 }
3748 return true;
3749 }
3750
Robert Greenwalt9258c642014-03-26 16:47:06 -07003751 @Override
3752 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3753 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003754 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3755 enforceAccessPermission();
3756 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003757
3758 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003759 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003760 if (DBG) log("listenForNetwork for " + networkRequest);
3761 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3762 NetworkRequestInfo.LISTEN);
3763
3764 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3765 return networkRequest;
3766 }
3767
3768 @Override
3769 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3770 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003771 checkNotNull(operation, "PendingIntent cannot be null.");
3772 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3773 enforceAccessPermission();
3774 }
3775
3776 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3777 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3778 if (DBG) log("pendingListenForNetwork for " + networkRequest + " to trigger " + operation);
3779 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3780 NetworkRequestInfo.LISTEN);
3781
3782 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003783 }
3784
3785 @Override
3786 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003787 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3788 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003789 }
3790
3791 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003792 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003793 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003794 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3795 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003796 }
3797
Robert Greenwalta67be032014-05-16 15:49:14 -07003798 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003799 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003800 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3801 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3802 }
3803
3804 @Override
3805 public void unregisterNetworkFactory(Messenger messenger) {
3806 enforceConnectivityInternalPermission();
3807 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3808 }
3809
3810 private void handleUnregisterNetworkFactory(Messenger messenger) {
3811 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3812 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003813 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003814 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003815 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003816 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003817 }
3818
Robert Greenwalt7b816022014-04-18 15:25:25 -07003819 /**
3820 * NetworkAgentInfo supporting a request by requestId.
3821 * These have already been vetted (their Capabilities satisfy the request)
3822 * and the are the highest scored network available.
3823 * the are keyed off the Requests requestId.
3824 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003825 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003826 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3827 new SparseArray<NetworkAgentInfo>();
3828
Paul Jensen31a94f42015-02-13 14:18:39 -05003829 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3830 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003831 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3832 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003833 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3834 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3835 // there may not be a strict 1:1 correlation between the two.
3836 @GuardedBy("mNetworkForNetId")
3837 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003838
Robert Greenwalt7b816022014-04-18 15:25:25 -07003839 // NetworkAgentInfo keyed off its connecting messenger
3840 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003841 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003842 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3843 new HashMap<Messenger, NetworkAgentInfo>();
3844
Paul Jensen2c311d62014-11-17 12:34:51 -05003845 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003846 private final NetworkRequest mDefaultRequest;
3847
Erik Klineda4bfa82015-04-30 12:58:40 +09003848 // Request used to optionally keep mobile data active even when higher
3849 // priority networks like Wi-Fi are active.
3850 private final NetworkRequest mDefaultMobileDataRequest;
3851
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003852 private NetworkAgentInfo getDefaultNetwork() {
3853 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3854 }
3855
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003856 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003857 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003858 }
3859
Paul Jensen31a94f42015-02-13 14:18:39 -05003860 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003861 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003862 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003863 enforceConnectivityInternalPermission();
3864
Paul Jensen2c311d62014-11-17 12:34:51 -05003865 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3866 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003867 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003868 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3869 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3870 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003871 synchronized (this) {
3872 nai.networkMonitor.systemReady = mSystemReady;
3873 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003874 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003875 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003876 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003877 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003878 }
3879
3880 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3881 if (VDBG) log("Got NetworkAgent Messenger");
3882 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003883 synchronized (mNetworkForNetId) {
3884 mNetworkForNetId.put(na.network.netId, na);
3885 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003886 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3887 NetworkInfo networkInfo = na.networkInfo;
3888 na.networkInfo = null;
3889 updateNetworkInfo(na, networkInfo);
3890 }
3891
3892 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3893 LinkProperties newLp = networkAgent.linkProperties;
3894 int netId = networkAgent.network.netId;
3895
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003896 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3897 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003898 if (networkAgent.clatd != null) {
3899 networkAgent.clatd.fixupLinkProperties(oldLp);
3900 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003901
Paul Jensen992f2522014-04-28 10:33:11 -04003902 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003903 updateMtu(newLp, oldLp);
3904 // TODO - figure out what to do for clat
3905// for (LinkProperties lp : newLp.getStackedLinks()) {
3906// updateMtu(lp, null);
3907// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003908 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003909
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003910 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3911 // In L, we used it only when the network had Internet access but provided no DNS servers.
3912 // For now, just disable it, and if disabling it doesn't break things, remove it.
3913 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3914 // NET_CAPABILITY_INTERNET);
3915 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003916 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003917 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3918
Paul Jensen3b759822014-05-13 11:44:01 -04003919 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003920 if (isDefaultNetwork(networkAgent)) {
3921 handleApplyDefaultProxy(newLp.getHttpProxy());
3922 } else {
3923 updateProxy(newLp, oldLp, networkAgent);
3924 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003925 // TODO - move this check to cover the whole function
3926 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003927 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003928 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3929 }
Paul Jensen3b759822014-05-13 11:44:01 -04003930 }
3931
Lorenzo Colitti95439462014-10-09 13:44:48 +09003932 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3933 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3934 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003935
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003936 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003937 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3938 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003939 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003940 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003941 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003942 }
Paul Jensen992f2522014-04-28 10:33:11 -04003943
3944 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3945 CompareResult<String> interfaceDiff = new CompareResult<String>();
3946 if (oldLp != null) {
3947 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3948 } else if (newLp != null) {
3949 interfaceDiff.added = newLp.getAllInterfaceNames();
3950 }
3951 for (String iface : interfaceDiff.added) {
3952 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003953 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003954 mNetd.addInterfaceToNetwork(iface, netId);
3955 } catch (Exception e) {
3956 loge("Exception adding interface: " + e);
3957 }
3958 }
3959 for (String iface : interfaceDiff.removed) {
3960 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003961 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003962 mNetd.removeInterfaceFromNetwork(iface, netId);
3963 } catch (Exception e) {
3964 loge("Exception removing interface: " + e);
3965 }
3966 }
3967 }
3968
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003969 /**
3970 * Have netd update routes from oldLp to newLp.
3971 * @return true if routes changed between oldLp and newLp
3972 */
3973 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003974 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3975 if (oldLp != null) {
3976 routeDiff = oldLp.compareAllRoutes(newLp);
3977 } else if (newLp != null) {
3978 routeDiff.added = newLp.getAllRoutes();
3979 }
3980
3981 // add routes before removing old in case it helps with continuous connectivity
3982
3983 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3984 for (RouteInfo route : routeDiff.added) {
3985 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003986 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003987 try {
3988 mNetd.addRoute(netId, route);
3989 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003990 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3991 loge("Exception in addRoute for non-gateway: " + e);
3992 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003993 }
3994 }
3995 for (RouteInfo route : routeDiff.added) {
3996 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003997 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003998 try {
3999 mNetd.addRoute(netId, route);
4000 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004001 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4002 loge("Exception in addRoute for gateway: " + e);
4003 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004004 }
4005 }
4006
4007 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004008 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004009 try {
4010 mNetd.removeRoute(netId, route);
4011 } catch (Exception e) {
4012 loge("Exception in removeRoute: " + e);
4013 }
4014 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004015 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004016 }
Erik Kline41368502015-06-17 13:19:54 +09004017
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004018 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4019 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004020 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09004021 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004022 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004023 dnses = new ArrayList();
4024 dnses.add(mDefaultDns);
4025 if (DBG) {
4026 loge("no dns provided for netId " + netId + ", so using defaults");
4027 }
4028 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004029 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004030 try {
4031 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4032 newLp.getDomains());
4033 } catch (Exception e) {
4034 loge("Exception in setDnsServersForNetwork: " + e);
4035 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004036 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
4037 if (defaultNai != null && defaultNai.network.netId == netId) {
4038 setDefaultDnsSystemProperties(dnses);
4039 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004040 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004041 } else if (flush) {
4042 try {
4043 mNetd.flushNetworkDnsCache(netId);
4044 } catch (Exception e) {
4045 loge("Exception in flushNetworkDnsCache: " + e);
4046 }
4047 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004048 }
4049 }
4050
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004051 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4052 int last = 0;
4053 for (InetAddress dns : dnses) {
4054 ++last;
4055 String key = "net.dns" + last;
4056 String value = dns.getHostAddress();
4057 SystemProperties.set(key, value);
4058 }
4059 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4060 String key = "net.dns" + i;
4061 SystemProperties.set(key, "");
4062 }
4063 mNumDnsEntries = last;
4064 }
4065
Paul Jensen3d194ea2015-06-16 14:27:36 -04004066 /**
4067 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4068 * augmented with any stateful capabilities implied from {@code networkAgent}
4069 * (e.g., validated status and captive portal status).
4070 *
4071 * @param networkAgent the network having its capabilities updated.
4072 * @param networkCapabilities the new network capabilities.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004073 * @param nascent indicates whether {@code networkAgent} was validated
4074 * (i.e. had everValidated set for the first time) immediately prior to this call.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004075 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07004076 private void updateCapabilities(NetworkAgentInfo networkAgent,
Paul Jensen1c7ba022015-06-16 14:27:36 -04004077 NetworkCapabilities networkCapabilities, NascentState nascent) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004078 // Don't modify caller's NetworkCapabilities.
4079 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4080 if (networkAgent.lastValidated) {
4081 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4082 } else {
4083 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4084 }
4085 if (networkAgent.lastCaptivePortalDetected) {
4086 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4087 } else {
4088 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4089 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004090 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
4091 synchronized (networkAgent) {
4092 networkAgent.networkCapabilities = networkCapabilities;
4093 }
Paul Jensen1c7ba022015-06-16 14:27:36 -04004094 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore(), nascent);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004095 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004096 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004097 }
4098
Paul Jensenc8b9a742014-09-30 15:37:41 -04004099 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4100 for (int i = 0; i < nai.networkRequests.size(); i++) {
4101 NetworkRequest nr = nai.networkRequests.valueAt(i);
4102 // Don't send listening requests to factories. b/17393458
4103 if (!isRequest(nr)) continue;
4104 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4105 }
4106 }
4107
Robert Greenwalt7b816022014-04-18 15:25:25 -07004108 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4109 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004110 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004111 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4112 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004113 }
4114 }
4115
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004116 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4117 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004118 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004119 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004120 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4121 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004122 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004123 sendIntent(nri.mPendingIntent, intent);
4124 }
4125 // else not handled
4126 }
4127
4128 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4129 mPendingIntentWakeLock.acquire();
4130 try {
4131 if (DBG) log("Sending " + pendingIntent);
4132 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4133 } catch (PendingIntent.CanceledException e) {
4134 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4135 mPendingIntentWakeLock.release();
4136 releasePendingNetworkRequest(pendingIntent);
4137 }
4138 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4139 }
4140
4141 @Override
4142 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4143 String resultData, Bundle resultExtras) {
4144 if (DBG) log("Finished sending " + pendingIntent);
4145 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004146 // Release with a delay so the receiving client has an opportunity to put in its
4147 // own request.
4148 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004149 }
4150
Robert Greenwalt9258c642014-03-26 16:47:06 -07004151 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004152 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004153 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004154 Bundle bundle = new Bundle();
4155 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4156 new NetworkRequest(nri.request));
4157 Message msg = Message.obtain();
4158 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4159 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4160 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4161 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004162 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004163 case ConnectivityManager.CALLBACK_LOSING: {
4164 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4165 break;
4166 }
4167 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4168 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4169 new NetworkCapabilities(networkAgent.networkCapabilities));
4170 break;
4171 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004172 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004173 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4174 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004175 break;
4176 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004177 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004178 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004179 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004180 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004181 if (VDBG) {
4182 log("sending notification " + notifyTypeToName(notificationType) +
4183 " for " + nri.request);
4184 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004185 nri.messenger.send(msg);
4186 } catch (RemoteException e) {
4187 // may occur naturally in the race of binder death.
4188 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4189 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004190 }
4191
Paul Jensenc8b9a742014-09-30 15:37:41 -04004192 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4193 for (int i = 0; i < nai.networkRequests.size(); i++) {
4194 NetworkRequest nr = nai.networkRequests.valueAt(i);
4195 // Ignore listening requests.
4196 if (!isRequest(nr)) continue;
4197 loge("Dead network still had at least " + nr);
4198 break;
4199 }
4200 nai.asyncChannel.disconnect();
4201 }
4202
Robert Greenwalt7b816022014-04-18 15:25:25 -07004203 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4204 if (oldNetwork == null) {
4205 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4206 return;
4207 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004208 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4209 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004210 }
4211
Paul Jensen27b02b72014-07-14 12:03:33 -04004212 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004213 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004214 setupDataActivityTracking(newNetwork);
4215 try {
4216 mNetd.setDefaultNetId(newNetwork.network.netId);
4217 } catch (Exception e) {
4218 loge("Exception setting default network :" + e);
4219 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004220 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004221 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004222 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004223 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004224 }
4225
Paul Jensen2161a8e2014-09-11 11:00:39 -04004226 // Handles a network appearing or improving its score.
4227 //
4228 // - Evaluates all current NetworkRequests that can be
4229 // satisfied by newNetwork, and reassigns to newNetwork
4230 // any such requests for which newNetwork is the best.
4231 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004232 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004233 // needed. A network is needed if it is the best network for
4234 // one or more NetworkRequests, or if it is a VPN.
4235 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004236 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004237 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4238 //
4239 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4240 // networks that have no chance (i.e. even if validated)
4241 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004242 //
4243 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4244 // it does not remove NetworkRequests that other Networks could better satisfy.
4245 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4246 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4247 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004248 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004249 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004250 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004251 // torn down if unneeded.
4252 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4253 // performed to tear down unvalidated networks that have no chance (i.e. even if
4254 // validated) of becoming the highest scoring network.
4255 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4256 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004257 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004258 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004259 loge("ERROR: nascent network not validated.");
4260 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004261 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004262 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004263 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004264 if (DBG) log("rematching " + newNetwork.name());
4265 // Find and migrate to this Network any NetworkRequests for
4266 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004267 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004268 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004269 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004270 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004271 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4272 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004273 if (DBG) {
4274 log("Network " + newNetwork.name() + " was already satisfying" +
4275 " request " + nri.request.requestId + ". No change.");
4276 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004277 keep = true;
4278 continue;
4279 }
4280
4281 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004282 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004283 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004284 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004285 // This is not a request, it's a callback listener.
4286 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004287 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004288 continue;
4289 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004290
Robert Greenwalt7b816022014-04-18 15:25:25 -07004291 // next check if it's better than any current network we're using for
4292 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004293 if (VDBG) {
4294 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004295 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4296 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004297 }
4298 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004299 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004300 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004301 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004302 currentNetwork.networkRequests.remove(nri.request.requestId);
4303 currentNetwork.networkLingered.add(nri.request);
4304 affectedNetworks.add(currentNetwork);
4305 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004306 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004307 }
Paul Jensen573a0352015-01-08 10:49:34 -05004308 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004309 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004310 if (!newNetwork.addRequest(nri.request)) {
4311 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4312 }
4313 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004314 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004315 // Tell NetworkFactories about the new score, so they can stop
4316 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004317 // TODO - this could get expensive if we have alot of requests for this
4318 // network. Think about if there is a way to reduce this. Push
4319 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004320 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004321 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004322 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004323 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004324 }
4325 }
4326 }
4327 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004328 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004329 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004330 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004331 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4332 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4333 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004334 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004335 }
4336 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004337 if (keep) {
4338 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004339 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004340 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004341 synchronized (ConnectivityService.this) {
4342 // have a new default network, release the transition wakelock in
4343 // a second if it's held. The second pause is to allow apps
4344 // to reconnect over the new network
4345 if (mNetTransitionWakeLock.isHeld()) {
4346 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4347 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4348 mNetTransitionWakeLockSerialNumber, 0),
4349 1000);
4350 }
4351 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004352 }
4353
4354 // do this after the default net is switched, but
4355 // before LegacyTypeTracker sends legacy broadcasts
Paul Jensen3d911462015-06-12 06:40:24 -04004356 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
Robert Greenwalt152ed372014-12-17 17:19:53 -08004357
4358 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004359 // Maintain the illusion: since the legacy API only
4360 // understands one network at a time, we must pretend
4361 // that the current default network disconnected before
4362 // the new one connected.
4363 if (oldDefaultNetwork != null) {
4364 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004365 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004366 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004367 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004368 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4369 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004370 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004371
4372 // Notify battery stats service about this network, both the normal
4373 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004374 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004375 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004376 final IBatteryStats bs = BatteryStatsService.getService();
4377 final int type = newNetwork.networkInfo.getType();
4378
4379 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4380 bs.noteNetworkInterfaceType(baseIface, type);
4381 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4382 final String stackedIface = stacked.getInterfaceName();
4383 bs.noteNetworkInterfaceType(stackedIface, type);
4384 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4385 }
4386 } catch (RemoteException ignored) {
4387 }
4388
Robert Greenwalt152ed372014-12-17 17:19:53 -08004389 // This has to happen after the notifyNetworkCallbacks as that tickles each
4390 // ConnectivityManager instance so that legacy requests correctly bind dns
4391 // requests to this network. The legacy users are listening for this bcast
4392 // and will generally do a dns request so they can ensureRouteToHost and if
4393 // they do that before the callbacks happen they'll use the default network.
4394 //
4395 // TODO: Is there still a race here? We send the broadcast
4396 // after sending the callback, but if the app can receive the
4397 // broadcast before the callback, it might still break.
4398 //
4399 // This *does* introduce a race where if the user uses the new api
4400 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4401 // they may get old info. Reverse this after the old startUsing api is removed.
4402 // This is on top of the multiple intent sequencing referenced in the todo above.
4403 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4404 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4405 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4406 // legacy type tracker filters out repeat adds
4407 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4408 }
4409 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004410
4411 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4412 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4413 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4414 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4415 if (newNetwork.isVPN()) {
4416 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4417 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004418 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004419 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004420 // validated (and get evaluated against peers, one losing here), or get reaped (see
4421 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4422 // network. Networks that have been up for a while and are validated should be torn
4423 // down via the lingering process so communication on that network is given time to
4424 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004425 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004426 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004427 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004428 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4429 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004430 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004431 if (DBG) log("Reaping " + nai.name());
4432 teardownUnneededNetwork(nai);
4433 }
4434 }
4435 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004436 }
4437
Paul Jensen1c7ba022015-06-16 14:27:36 -04004438 /**
4439 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4440 * being disconnected.
4441 * @param changed If only one Network's score or capabilities have been modified since the last
4442 * time this function was called, pass this Network in this argument, otherwise pass
4443 * null.
4444 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4445 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4446 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4447 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4448 * network's score.
4449 * @param nascent indicates if {@code changed} has just been validated.
4450 */
4451 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore,
4452 NascentState nascent) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004453 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4454 // to avoid the slowness. It is not simply enough to process just "changed", for
4455 // example in the case where "changed"'s score decreases and another network should begin
4456 // satifying a NetworkRequest that "changed" currently satisfies.
4457
4458 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4459 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4460 // rematchNetworkAndRequests() handles.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004461 if (changed != null &&
4462 (oldScore < changed.getCurrentScore() || nascent == NascentState.JUST_VALIDATED)) {
4463 rematchNetworkAndRequests(changed, nascent, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004464 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004465 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4466 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4467 NascentState.NOT_JUST_VALIDATED,
4468 // Only reap the last time through the loop. Reaping before all rematching
4469 // is complete could incorrectly teardown a network that hasn't yet been
4470 // rematched.
4471 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4472 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004473 }
4474 }
4475 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004476
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004477 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004478 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004479 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004480 // For now only update icons for default connection.
4481 // TODO: Update WiFi and cellular icons separately. b/17237507
4482 if (!isDefaultNetwork(nai)) return;
4483
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004484 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004485 // Don't repeat publish.
4486 if (newInetCondition == mDefaultInetConditionPublished) return;
4487
4488 mDefaultInetConditionPublished = newInetCondition;
4489 sendInetConditionBroadcast(nai.networkInfo);
4490 }
4491
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004492 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4493 if (mLockdownTracker != null) {
4494 if (nai != null && nai.isVPN()) {
4495 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4496 } else {
4497 mLockdownTracker.onNetworkInfoChanged();
4498 }
4499 }
4500 }
4501
Robert Greenwalt7b816022014-04-18 15:25:25 -07004502 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4503 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004504 NetworkInfo oldInfo = null;
4505 synchronized (networkAgent) {
4506 oldInfo = networkAgent.networkInfo;
4507 networkAgent.networkInfo = newInfo;
4508 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004509 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004510
4511 if (oldInfo != null && oldInfo.getState() == state) {
4512 if (VDBG) log("ignoring duplicate network state non-change");
4513 return;
4514 }
4515 if (DBG) {
4516 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4517 (oldInfo == null ? "null" : oldInfo.getState()) +
4518 " to " + state);
4519 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004520
Paul Jenseneec75412014-08-04 12:21:19 -04004521 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004522 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004523 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004524 if (networkAgent.isVPN()) {
4525 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004526 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4527 (networkAgent.networkMisc == null ||
4528 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004529 } else {
4530 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4531 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004533 loge("Error creating network " + networkAgent.network.netId + ": "
4534 + e.getMessage());
4535 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004536 }
Paul Jenseneec75412014-08-04 12:21:19 -04004537 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004538 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004539 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004540
Paul Jensenca8f16a2014-05-09 12:47:55 -04004541 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004542 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004543
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004544 if (networkAgent.isVPN()) {
4545 // Temporarily disable the default proxy (not global).
4546 synchronized (mProxyLock) {
4547 if (!mDefaultProxyDisabled) {
4548 mDefaultProxyDisabled = true;
4549 if (mGlobalProxy == null && mDefaultProxy != null) {
4550 sendProxyBroadcast(null);
4551 }
4552 }
4553 }
4554 // TODO: support proxy per network.
4555 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004556
Paul Jensen2161a8e2014-09-11 11:00:39 -04004557 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004558 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4559 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004560
4561 // This has to happen after matching the requests, because callbacks are just requests.
4562 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004563 } else if (state == NetworkInfo.State.DISCONNECTED ||
4564 state == NetworkInfo.State.SUSPENDED) {
4565 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004566 if (networkAgent.isVPN()) {
4567 synchronized (mProxyLock) {
4568 if (mDefaultProxyDisabled) {
4569 mDefaultProxyDisabled = false;
4570 if (mGlobalProxy == null && mDefaultProxy != null) {
4571 sendProxyBroadcast(mDefaultProxy);
4572 }
4573 }
4574 }
4575 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004576 }
4577 }
4578
Robert Greenwaltac96c522014-06-03 16:43:57 -07004579 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4580 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004581 if (score < 0) {
4582 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4583 "). Bumping score to min of 0");
4584 score = 0;
4585 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004586
Paul Jensen2161a8e2014-09-11 11:00:39 -04004587 final int oldScore = nai.getCurrentScore();
4588 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004589
Paul Jensen1c7ba022015-06-16 14:27:36 -04004590 rematchAllNetworksAndRequests(nai, oldScore, NascentState.NOT_JUST_VALIDATED);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004591
Paul Jensenc8b9a742014-09-30 15:37:41 -04004592 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004593 }
4594
Robert Greenwalt9258c642014-03-26 16:47:06 -07004595 // notify only this one new request of the current state
4596 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4597 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4598 // TODO - read state from monitor to decide what to send.
4599// if (nai.networkMonitor.isLingering()) {
4600// notifyType = NetworkCallbacks.LOSING;
4601// } else if (nai.networkMonitor.isEvaluating()) {
4602// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4603// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004604 if (nri.mPendingIntent == null) {
4605 callCallbackForRequest(nri, nai, notifyType);
4606 } else {
4607 sendPendingIntentForRequest(nri, nai, notifyType);
4608 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004609 }
4610
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004611 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004612 // The NetworkInfo we actually send out has no bearing on the real
4613 // state of affairs. For example, if the default connection is mobile,
4614 // and a request for HIPRI has just gone away, we need to pretend that
4615 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4616 // the state to DISCONNECTED, even though the network is of type MOBILE
4617 // and is still connected.
4618 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4619 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004620 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004621 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004622 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004623 } else {
Feixiong Zhang376133f2015-06-01 18:07:58 -07004624 info.setDetailedState(DetailedState.DISCONNECTED, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004625 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4626 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4627 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4628 if (info.isFailover()) {
4629 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4630 nai.networkInfo.setFailover(false);
4631 }
4632 if (info.getReason() != null) {
4633 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4634 }
4635 if (info.getExtraInfo() != null) {
4636 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4637 }
4638 NetworkAgentInfo newDefaultAgent = null;
4639 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4640 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4641 if (newDefaultAgent != null) {
4642 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4643 newDefaultAgent.networkInfo);
4644 } else {
4645 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4646 }
4647 }
4648 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4649 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004650 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004651 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004652 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004653 }
4654 }
4655 }
4656
Robert Greenwalt7b816022014-04-18 15:25:25 -07004657 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004658 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004659 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004660 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4661 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4662 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004663 if (nri.mPendingIntent == null) {
4664 callCallbackForRequest(nri, networkAgent, notifyType);
4665 } else {
4666 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4667 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004668 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004669 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004670
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004671 private String notifyTypeToName(int notifyType) {
4672 switch (notifyType) {
4673 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4674 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4675 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4676 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4677 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4678 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4679 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4680 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4681 }
4682 return "UNKNOWN";
4683 }
4684
Jeff Sharkey69736342014-12-08 14:50:12 -08004685 /**
4686 * Notify other system services that set of active ifaces has changed.
4687 */
4688 private void notifyIfacesChanged() {
4689 try {
4690 mStatsService.forceUpdateIfaces();
4691 } catch (Exception ignored) {
4692 }
4693 }
4694
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004695 @Override
4696 public boolean addVpnAddress(String address, int prefixLength) {
4697 throwIfLockdownEnabled();
4698 int user = UserHandle.getUserId(Binder.getCallingUid());
4699 synchronized (mVpns) {
4700 return mVpns.get(user).addAddress(address, prefixLength);
4701 }
4702 }
4703
4704 @Override
4705 public boolean removeVpnAddress(String address, int prefixLength) {
4706 throwIfLockdownEnabled();
4707 int user = UserHandle.getUserId(Binder.getCallingUid());
4708 synchronized (mVpns) {
4709 return mVpns.get(user).removeAddress(address, prefixLength);
4710 }
4711 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004712
4713 @Override
4714 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4715 throwIfLockdownEnabled();
4716 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004717 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004718 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004719 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004720 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004721 if (success) {
4722 notifyIfacesChanged();
4723 }
4724 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004725 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004726
4727 @Override
4728 public void factoryReset() {
4729 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004730
4731 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4732 return;
4733 }
4734
Robin Lee3b3dd942015-05-12 18:14:58 +01004735 final int userId = UserHandle.getCallingUserId();
4736
Stuart Scottf1fb3972015-04-02 18:00:02 -07004737 // Turn airplane mode off
4738 setAirplaneMode(false);
4739
Stuart Scotte3e314d2015-04-20 14:07:45 -07004740 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4741 // Untether
4742 for (String tether : getTetheredIfaces()) {
4743 untether(tether);
4744 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004745 }
4746
Stuart Scotte3e314d2015-04-20 14:07:45 -07004747 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4748 // Turn VPN off
4749 VpnConfig vpnConfig = getVpnConfig(userId);
4750 if (vpnConfig != null) {
4751 if (vpnConfig.legacy) {
4752 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4753 } else {
4754 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4755 // in the future without user intervention.
4756 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004757
Stuart Scotte3e314d2015-04-20 14:07:45 -07004758 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4759 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004760 }
4761 }
4762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004763}