blob: 2d5141eda96263da6013c15c2a84e886987896d4 [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;
Joe Onorato8a9b2202010-02-26 18:56:32 -080096import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070097import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -050098import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070099import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700100import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
Wink Savilleab9321d2013-06-29 21:10:57 -0700102import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400103import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400104import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700105import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700106import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700107import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700108import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800109import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700110import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700111import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700112import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700113import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700114import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700115import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400116import com.android.server.connectivity.DataConnectionStats;
Erik Kline379747a2015-06-05 17:47:34 +0900117import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900118import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700119import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400120import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400121import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700122import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800123import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700124import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700125import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700126import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700127import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700128import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700129
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700130import org.xmlpull.v1.XmlPullParser;
131import org.xmlpull.v1.XmlPullParserException;
132
133import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700135import java.io.FileNotFoundException;
136import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700137import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700139import java.net.Inet4Address;
Erik Kline41368502015-06-17 13:19:54 +0900140import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700141import java.net.InetAddress;
142import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700143import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700144import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700145import java.util.Collection;
Erik Kline41368502015-06-17 13:19:54 +0900146import java.util.Collections;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700147import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700148import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500149import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700150import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700151import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700152import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700153import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
155/**
156 * @hide
157 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800158public class ConnectivityService extends IConnectivityManager.Stub
159 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700160 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700162 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700163 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Jake Hamby786e71a2014-02-06 14:43:50 -0800165 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700166
Jeff Sharkey899223b2012-08-04 15:24:58 -0700167 // TODO: create better separation between radio types and network types
168
Robert Greenwalt42acef32009-08-12 16:08:25 -0700169 // how long to wait before switching back to a radio's default network
170 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
171 // system property that can override the above value
172 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
173 "android.telephony.apn-restore";
174
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900175 // How long to wait before putting up a "This network doesn't have an Internet connection,
176 // connect anyway?" dialog after the user selects a network that doesn't validate.
177 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
178
Jeremy Joslin79294842014-12-03 17:15:28 -0800179 // How long to delay to removal of a pending intent based request.
180 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
181 private final int mReleasePendingIntentDelayMs;
182
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800183 private Tethering mTethering;
184
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700185 private final PermissionMonitor mPermissionMonitor;
186
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700187 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700188
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700189 @GuardedBy("mVpns")
190 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700191
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700192 private boolean mLockdownEnabled;
193 private LockdownVpnTracker mLockdownTracker;
194
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700195 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
196 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700197 /** Currently active network rules by UID. */
198 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700199 /** Set of ifaces that are costly. */
200 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700201
Erik Klineda4bfa82015-04-30 12:58:40 +0900202 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700204 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700205 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800207 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
209 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700210 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700212 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800213 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700214 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700215
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700216 private String mCurrentTcpBufferSizes;
217
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700218 private static final int ENABLED = 1;
219 private static final int DISABLED = 0;
220
Paul Jensenb10e37f2014-11-25 12:33:08 -0500221 // Arguments to rematchNetworkAndRequests()
222 private enum NascentState {
223 // Indicates a network was just validated for the first time. If the network is found to
224 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
225 JUST_VALIDATED,
226 // Indicates a network was not validated for the first time immediately prior to this call.
227 NOT_JUST_VALIDATED
228 };
229 private enum ReapUnvalidatedNetworks {
230 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
231 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
232 // known that there may be unvalidated networks that could potentially be reaped, and when
233 // all networks have been rematched against all NetworkRequests.
234 REAP,
235 // Don't reap unvalidated networks. This should be passed when it's known that there are
236 // no unvalidated networks that could potentially be reaped, and when some networks have
237 // not yet been rematched against all NetworkRequests.
238 DONT_REAP
239 };
240
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700242 * used internally to change our mobile data enabled flag
243 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700244 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700245
246 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700247 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700248 * from one net to another. Clear happens when we get a new
249 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
250 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700251 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700252 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700253
Robert Greenwalt434203a2010-10-11 16:00:27 -0700254 /**
255 * used internally to reload global proxy settings
256 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700257 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700258
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700259 /**
Wink Saville628b0852011-08-04 15:01:58 -0700260 * used internally to send a sticky broadcast delayed.
261 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700262 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700263
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700264 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400265 * PAC manager has received new port.
266 */
267 private static final int EVENT_PROXY_HAS_CHANGED = 16;
268
Robert Greenwalte049c232014-04-11 15:53:27 -0700269 /**
270 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700271 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700272 */
273 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
274
Robert Greenwalt7b816022014-04-18 15:25:25 -0700275 /**
276 * used internally when registering NetworkAgents
277 * obj = Messenger
278 */
279 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
280
Robert Greenwalt9258c642014-03-26 16:47:06 -0700281 /**
282 * used to add a network request
283 * includes a NetworkRequestInfo
284 */
285 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
286
287 /**
288 * indicates a timeout period is over - check if we had a network yet or not
289 * and if not, call the timeout calback (but leave the request live until they
290 * cancel it.
291 * includes a NetworkRequestInfo
292 */
293 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
294
295 /**
296 * used to add a network listener - no request
297 * includes a NetworkRequestInfo
298 */
299 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
300
301 /**
302 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400303 * arg1 = UID of caller
304 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700305 */
306 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
307
Robert Greenwalta67be032014-05-16 15:49:14 -0700308 /**
309 * used internally when registering NetworkFactories
310 * obj = Messenger
311 */
312 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
313
Robert Greenwalt27711812014-06-25 16:45:57 -0700314 /**
315 * used internally to expire a wakelock when transitioning
316 * from one net to another. Expire happens when we fail to find
317 * a new network (typically after 1 minute) -
318 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
319 * a replacement network.
320 */
321 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
322
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700323 /**
324 * Used internally to indicate the system is ready.
325 */
326 private static final int EVENT_SYSTEM_READY = 25;
327
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800328 /**
329 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400330 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800331 */
332 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
333
334 /**
335 * used to remove a pending intent and its associated network request.
336 * arg1 = UID of caller
337 * obj = PendingIntent
338 */
339 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
340
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900341 /**
342 * used to specify whether a network should be used even if unvalidated.
343 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
344 * arg2 = whether to remember this choice in the future (1 or 0)
345 * obj = network
346 */
347 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
348
349 /**
350 * used to ask the user to confirm a connection to an unvalidated network.
351 * obj = network
352 */
353 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700354
Erik Klineda4bfa82015-04-30 12:58:40 +0900355 /**
356 * used internally to (re)configure mobile data always-on settings.
357 */
358 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
359
Paul Jensen694f2b82015-06-17 14:15:39 -0400360 /**
361 * used to add a network listener with a pending intent
362 * obj = NetworkRequestInfo
363 */
364 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
365
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700366 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700367 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700368 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700369 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700370
Mike Lockwood0f79b542009-08-14 14:18:49 -0400371 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800372 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400373
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700374 private PowerManager.WakeLock mNetTransitionWakeLock;
375 private String mNetTransitionWakeLockCausedBy = "";
376 private int mNetTransitionWakeLockSerialNumber;
377 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800378 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700379
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700380 private InetAddress mDefaultDns;
381
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700382 // used in DBG mode to track inet condition reports
383 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
384 private ArrayList mInetLog;
385
Robert Greenwalt434203a2010-10-11 16:00:27 -0700386 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400387 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700388 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700389 private boolean mDefaultProxyDisabled = false;
390
Robert Greenwalt434203a2010-10-11 16:00:27 -0700391 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400392 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700393
Jason Monk602b2322013-07-03 17:04:33 -0400394 private PacManager mPacManager = null;
395
Erik Klineda4bfa82015-04-30 12:58:40 +0900396 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700397
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400398 private UserManager mUserManager;
399
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700400 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700401 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700402
Robert Greenwalt50393202011-06-21 17:26:14 -0700403 // the set of network types that can only be enabled by system/sig apps
404 List mProtectedNetworks;
405
John Spurlockbf991a82013-06-24 14:20:23 -0400406 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700407
Wink Savilleab9321d2013-06-29 21:10:57 -0700408 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400409
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700410 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
411 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700412 private final static int MAX_NET_ID = 65535;
413 private int mNextNetId = MIN_NET_ID;
414
Robert Greenwalt34524f02014-05-18 16:22:10 -0700415 // sequence number of NetworkRequests
416 private int mNextNetworkRequestId = 1;
417
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700418 /**
419 * Implements support for the legacy "one network per network type" model.
420 *
421 * We used to have a static array of NetworkStateTrackers, one for each
422 * network type, but that doesn't work any more now that we can have,
423 * for example, more that one wifi network. This class stores all the
424 * NetworkAgentInfo objects that support a given type, but the legacy
425 * API will only see the first one.
426 *
427 * It serves two main purposes:
428 *
429 * 1. Provide information about "the network for a given type" (since this
430 * API only supports one).
431 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
432 * the first network for a given type changes, or if the default network
433 * changes.
434 */
435 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900436
437 private static final boolean DBG = true;
438 private static final boolean VDBG = false;
439 private static final String TAG = "CSLegacyTypeTracker";
440
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700441 /**
442 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
443 * Each list holds references to all NetworkAgentInfos that are used to
444 * satisfy requests for that network type.
445 *
446 * This array is built out at startup such that an unsupported network
447 * doesn't get an ArrayList instance, making this a tristate:
448 * unsupported, supported but not active and active.
449 *
450 * The actual lists are populated when we scan the network types that
451 * are supported on this device.
452 */
453 private ArrayList<NetworkAgentInfo> mTypeLists[];
454
455 public LegacyTypeTracker() {
456 mTypeLists = (ArrayList<NetworkAgentInfo>[])
457 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
458 }
459
460 public void addSupportedType(int type) {
461 if (mTypeLists[type] != null) {
462 throw new IllegalStateException(
463 "legacy list for type " + type + "already initialized");
464 }
465 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
466 }
467
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700468 public boolean isTypeSupported(int type) {
469 return isNetworkTypeValid(type) && mTypeLists[type] != null;
470 }
471
472 public NetworkAgentInfo getNetworkForType(int type) {
473 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
474 return mTypeLists[type].get(0);
475 } else {
476 return null;
477 }
478 }
479
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900480 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type,
481 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900482 if (DBG) {
483 log("Sending " + (connected ? "connected" : "disconnected") +
484 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900485 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900486 }
487 }
488
489 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700490 public void add(int type, NetworkAgentInfo nai) {
491 if (!isTypeSupported(type)) {
492 return; // Invalid network type.
493 }
494 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
495
496 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
497 if (list.contains(nai)) {
498 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
499 return;
500 }
501
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900502 list.add(nai);
503
504 // 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 +0900505 final boolean isDefaultNetwork = isDefaultNetwork(nai);
506 if (list.size() == 1 || isDefaultNetwork) {
507 maybeLogBroadcast(nai, true, type, isDefaultNetwork);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700508 sendLegacyNetworkBroadcast(nai, true, type);
509 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700510 }
511
Lorenzo Colittia793a672014-07-31 23:20:17 +0900512 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900513 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900514 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
515 if (list == null || list.isEmpty()) {
516 return;
517 }
518
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900519 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900520
521 if (!list.remove(nai)) {
522 return;
523 }
524
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900525 if (wasFirstNetwork || wasDefault) {
526 maybeLogBroadcast(nai, false, type, wasDefault);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900527 sendLegacyNetworkBroadcast(nai, false, type);
528 }
529
530 if (!list.isEmpty() && wasFirstNetwork) {
531 if (DBG) log("Other network available for type " + type +
532 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 final NetworkAgentInfo replacement = list.get(0);
534 maybeLogBroadcast(replacement, false, type, isDefaultNetwork(replacement));
535 sendLegacyNetworkBroadcast(replacement, false, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900536 }
537 }
538
539 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900540 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
541 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700542 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900543 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700544 }
545 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700546
Lorenzo Colittia793a672014-07-31 23:20:17 +0900547 private String naiToString(NetworkAgentInfo nai) {
548 String name = (nai != null) ? nai.name() : "null";
549 String state = (nai.networkInfo != null) ?
550 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
551 "???/???";
552 return name + " " + state;
553 }
554
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700555 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900556 pw.println("mLegacyTypeTracker:");
557 pw.increaseIndent();
558 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700559 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900560 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700561 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900562 pw.println();
563 pw.println("Current state:");
564 pw.increaseIndent();
565 for (int type = 0; type < mTypeLists.length; type++) {
566 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
567 for (NetworkAgentInfo nai : mTypeLists[type]) {
568 pw.println(type + " " + naiToString(nai));
569 }
570 }
571 pw.decreaseIndent();
572 pw.decreaseIndent();
573 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700574 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900575
576 // This class needs its own log method because it has a different TAG.
577 private void log(String s) {
578 Slog.d(TAG, s);
579 }
580
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700581 }
582 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
583
Jeff Sharkey899223b2012-08-04 15:24:58 -0700584 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700585 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800586 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800587
Erik Klineda4bfa82015-04-30 12:58:40 +0900588 mDefaultRequest = createInternetRequestForTransport(-1);
589 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
590 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
591
592 mDefaultMobileDataRequest = createInternetRequestForTransport(
593 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700594
Wink Savillebb08caf2010-09-02 19:23:52 -0700595 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
596 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700597 mHandler = new InternalHandler(handlerThread.getLooper());
598 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700599
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800600 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800601 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
602 String id = Settings.Secure.getString(context.getContentResolver(),
603 Settings.Secure.ANDROID_ID);
604 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700605 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800606 SystemProperties.set("net.hostname", name);
607 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800608 }
609
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700610 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700611 String dns = Settings.Global.getString(context.getContentResolver(),
612 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700613 if (dns == null || dns.length() == 0) {
614 dns = context.getResources().getString(
615 com.android.internal.R.string.config_default_dns_server);
616 }
617 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800618 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
619 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800620 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700621 }
622
Jeremy Joslin79294842014-12-03 17:15:28 -0800623 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
624 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
625
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700626 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700627 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800628 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700629 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700630 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700631 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700632
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700633 try {
634 mPolicyManager.registerListener(mPolicyListener);
635 } catch (RemoteException e) {
636 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700637 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700638 }
639
640 final PowerManager powerManager = (PowerManager) context.getSystemService(
641 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700642 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
643 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
644 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800645 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700646
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700647 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700648
Wink Saville51f456f2013-04-23 14:26:51 -0700649 // TODO: What is the "correct" way to do determine if this is a wifi only device?
650 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
651 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700652 String[] naStrings = context.getResources().getStringArray(
653 com.android.internal.R.array.networkAttributes);
654 for (String naString : naStrings) {
655 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700656 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700657 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700658 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800659 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700660 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700661 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700662 }
Wink Saville51f456f2013-04-23 14:26:51 -0700663 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
664 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
665 n.type);
666 continue;
667 }
Wink Saville975c8482011-04-07 14:23:45 -0700668 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800669 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700670 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700671 continue;
672 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700673 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700674
Wink Saville975c8482011-04-07 14:23:45 -0700675 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700676 mNetworksDefined++;
677 } catch(Exception e) {
678 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700679 }
680 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700681
682 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
683 if (mNetConfigs[TYPE_VPN] == null) {
684 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
685 // don't need to add TYPE_VPN to mNetConfigs.
686 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
687 mNetworksDefined++; // used only in the log() statement below.
688 }
689
Wink Saville5e56bc52013-07-29 15:00:57 -0700690 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700691
Robert Greenwalt50393202011-06-21 17:26:14 -0700692 mProtectedNetworks = new ArrayList<Integer>();
693 int[] protectedNetworks = context.getResources().getIntArray(
694 com.android.internal.R.array.config_protectedNetworks);
695 for (int p : protectedNetworks) {
696 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
697 mProtectedNetworks.add(p);
698 } else {
699 if (DBG) loge("Ignoring protectedNetwork " + p);
700 }
701 }
702
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700703 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
704 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700705
Robert Greenwaltfab501672014-07-23 11:44:01 -0700706 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800707
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700708 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
709
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700710 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700711 IntentFilter intentFilter = new IntentFilter();
712 intentFilter.addAction(Intent.ACTION_USER_STARTING);
713 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
714 mContext.registerReceiverAsUser(
715 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900716
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700717 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700718 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700719 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700720 } catch (RemoteException e) {
721 loge("Error registering observer :" + e);
722 }
723
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700724 if (DBG) {
725 mInetLog = new ArrayList();
726 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700727
Erik Klineda4bfa82015-04-30 12:58:40 +0900728 mSettingsObserver = new SettingsObserver(mContext, mHandler);
729 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800730
John Spurlockbf991a82013-06-24 14:20:23 -0400731 mDataConnectionStats = new DataConnectionStats(mContext);
732 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400733
Jason Monkdecd2952013-10-10 14:02:51 -0400734 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700735
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400736 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700738
Erik Klineda4bfa82015-04-30 12:58:40 +0900739 private NetworkRequest createInternetRequestForTransport(int transportType) {
740 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900741 netCap.addCapability(NET_CAPABILITY_INTERNET);
742 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900743 if (transportType > -1) {
744 netCap.addTransportType(transportType);
745 }
746 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
747 }
748
749 private void handleMobileDataAlwaysOn() {
750 final boolean enable = (Settings.Global.getInt(
751 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
752 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
753 if (enable == isEnabled) {
754 return; // Nothing to do.
755 }
756
757 if (enable) {
758 handleRegisterNetworkRequest(new NetworkRequestInfo(
759 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
760 } else {
761 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
762 }
763 }
764
765 private void registerSettingsCallbacks() {
766 // Watch for global HTTP proxy changes.
767 mSettingsObserver.observe(
768 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
769 EVENT_APPLY_GLOBAL_HTTP_PROXY);
770
771 // Watch for whether or not to keep mobile data always on.
772 mSettingsObserver.observe(
773 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
774 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
775 }
776
Robert Greenwalt34524f02014-05-18 16:22:10 -0700777 private synchronized int nextNetworkRequestId() {
778 return mNextNetworkRequestId++;
779 }
780
Paul Jensen67b0b072015-06-10 11:22:17 -0400781 @VisibleForTesting
782 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400783 synchronized (mNetworkForNetId) {
784 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
785 int netId = mNextNetId;
786 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
787 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500788 if (!mNetIdInUse.get(netId)) {
789 mNetIdInUse.put(netId, true);
790 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400791 }
792 }
793 }
794 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700795 }
796
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800797 private NetworkState getFilteredNetworkState(int networkType, int uid) {
798 NetworkInfo info = null;
799 LinkProperties lp = null;
800 NetworkCapabilities nc = null;
801 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800802 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800803
804 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
805 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
806 if (nai != null) {
807 synchronized (nai) {
808 info = new NetworkInfo(nai.networkInfo);
809 lp = new LinkProperties(nai.linkProperties);
810 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400811 // Network objects are outwardly immutable so there is no point to duplicating.
812 // Duplicating also precludes sharing socket factories and connection pools.
813 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800814 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800815 }
816 info.setType(networkType);
817 } else {
818 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
819 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
820 info.setIsAvailable(true);
821 lp = new LinkProperties();
822 nc = new NetworkCapabilities();
823 network = null;
824 }
825 info = getFilteredNetworkInfo(info, lp, uid);
826 }
827
Jeff Sharkey32566012014-12-02 18:30:14 -0800828 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400829 }
830
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800831 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
832 if (network == null) {
833 return null;
834 }
835 synchronized (mNetworkForNetId) {
836 return mNetworkForNetId.get(network.netId);
837 }
838 };
839
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900840 private Network[] getVpnUnderlyingNetworks(int uid) {
841 if (!mLockdownEnabled) {
842 int user = UserHandle.getUserId(uid);
843 synchronized (mVpns) {
844 Vpn vpn = mVpns.get(user);
845 if (vpn != null && vpn.appliesToUid(uid)) {
846 return vpn.getUnderlyingNetworks();
847 }
848 }
849 }
850 return null;
851 }
852
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800853 private NetworkState getUnfilteredActiveNetworkState(int uid) {
854 NetworkInfo info = null;
855 LinkProperties lp = null;
856 NetworkCapabilities nc = null;
857 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800858 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800859
860 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800861
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900862 final Network[] networks = getVpnUnderlyingNetworks(uid);
863 if (networks != null) {
864 // getUnderlyingNetworks() returns:
865 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
866 // empty array => the VPN explicitly said "no default network".
867 // non-empty array => the VPN specified one or more default networks; we use the
868 // first one.
869 if (networks.length > 0) {
870 nai = getNetworkAgentInfoForNetwork(networks[0]);
871 } else {
872 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800873 }
874 }
875
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800876 if (nai != null) {
877 synchronized (nai) {
878 info = new NetworkInfo(nai.networkInfo);
879 lp = new LinkProperties(nai.linkProperties);
880 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400881 // Network objects are outwardly immutable so there is no point to duplicating.
882 // Duplicating also precludes sharing socket factories and connection pools.
883 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800884 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800885 }
886 }
887
Jeff Sharkey32566012014-12-02 18:30:14 -0800888 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400889 }
890
891 /**
892 * Check if UID should be blocked from using the network with the given LinkProperties.
893 */
894 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700895 final boolean networkCostly;
896 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700897
Robert Greenwalt12e67352014-05-13 21:41:06 -0700898 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700899 synchronized (mRulesLock) {
900 networkCostly = mMeteredIfaces.contains(iface);
901 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700902 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700903
Amith Yamasani15e472352015-04-24 19:06:07 -0700904 if ((uidRules & RULE_REJECT_ALL) != 0
905 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700906 return true;
907 }
908
909 // no restrictive rules; network is visible
910 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700911 }
912
913 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700914 * Return a filtered {@link NetworkInfo}, potentially marked
915 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800916 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700917 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800918 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
919 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400920 // network is blocked; clone and override state
921 info = new NetworkInfo(info);
922 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900923 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900924 log("returning Blocked NetworkInfo for ifname=" +
925 lp.getInterfaceName() + ", uid=" + uid);
926 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700927 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800928 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700929 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900930 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700931 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700932 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700933 }
934
935 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 * Return NetworkInfo for the active (i.e., connected) network interface.
937 * It is assumed that at most one network is active at a time. If more
938 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700939 * @return the info for the active network, or {@code null} if none is
940 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700942 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700944 enforceAccessPermission();
945 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800946 NetworkState state = getUnfilteredActiveNetworkState(uid);
947 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
949
Paul Jensen31a94f42015-02-13 14:18:39 -0500950 @Override
951 public Network getActiveNetwork() {
952 enforceAccessPermission();
953 final int uid = Binder.getCallingUid();
954 final int user = UserHandle.getUserId(uid);
955 int vpnNetId = NETID_UNSET;
956 synchronized (mVpns) {
957 final Vpn vpn = mVpns.get(user);
958 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
959 }
960 NetworkAgentInfo nai;
961 if (vpnNetId != NETID_UNSET) {
962 synchronized (mNetworkForNetId) {
963 nai = mNetworkForNetId.get(vpnNetId);
964 }
965 if (nai != null) return nai.network;
966 }
967 nai = getDefaultNetwork();
968 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
969 return nai != null ? nai.network : null;
970 }
971
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700972 public NetworkInfo getActiveNetworkInfoUnfiltered() {
973 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800974 final int uid = Binder.getCallingUid();
975 NetworkState state = getUnfilteredActiveNetworkState(uid);
976 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700977 }
978
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700979 @Override
980 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
981 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800982 NetworkState state = getUnfilteredActiveNetworkState(uid);
983 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700984 }
985
986 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 public NetworkInfo getNetworkInfo(int networkType) {
988 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700989 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900990 if (getVpnUnderlyingNetworks(uid) != null) {
991 // A VPN is active, so we may need to return one of its underlying networks. This
992 // information is not available in LegacyTypeTracker, so we have to get it from
993 // getUnfilteredActiveNetworkState.
994 NetworkState state = getUnfilteredActiveNetworkState(uid);
995 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
996 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
997 }
998 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800999 NetworkState state = getFilteredNetworkState(networkType, uid);
1000 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 }
1002
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001003 @Override
1004 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1005 enforceAccessPermission();
1006 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001007 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001008 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1009 if (nai != null) {
1010 synchronized (nai) {
1011 info = new NetworkInfo(nai.networkInfo);
1012 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001013 }
1014 }
1015 return info;
1016 }
1017
1018 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 public NetworkInfo[] getAllNetworkInfo() {
1020 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001021 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001022 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1023 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001024 NetworkInfo info = getNetworkInfo(networkType);
1025 if (info != null) {
1026 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001029 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 }
1031
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001032 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001033 public Network getNetworkForType(int networkType) {
1034 enforceAccessPermission();
1035 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001036 NetworkState state = getFilteredNetworkState(networkType, uid);
1037 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1038 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001039 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001040 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001041 }
1042
1043 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001044 public Network[] getAllNetworks() {
1045 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001046 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001047 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001048 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001049 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001050 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001051 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001052 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001053 }
1054
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001055 @Override
1056 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1057 // The basic principle is: if an app's traffic could possibly go over a
1058 // network, without the app doing anything multinetwork-specific,
1059 // (hence, by "default"), then include that network's capabilities in
1060 // the array.
1061 //
1062 // In the normal case, app traffic only goes over the system's default
1063 // network connection, so that's the only network returned.
1064 //
1065 // With a VPN in force, some app traffic may go into the VPN, and thus
1066 // over whatever underlying networks the VPN specifies, while other app
1067 // traffic may go over the system default network (e.g.: a split-tunnel
1068 // VPN, or an app disallowed by the VPN), so the set of networks
1069 // returned includes the VPN's underlying networks and the system
1070 // default.
1071 enforceAccessPermission();
1072
1073 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1074
1075 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001076 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001077 if (nc != null) {
1078 result.put(nai.network, nc);
1079 }
1080
1081 if (!mLockdownEnabled) {
1082 synchronized (mVpns) {
1083 Vpn vpn = mVpns.get(userId);
1084 if (vpn != null) {
1085 Network[] networks = vpn.getUnderlyingNetworks();
1086 if (networks != null) {
1087 for (Network network : networks) {
1088 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001089 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001090 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001091 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001092 }
1093 }
1094 }
1095 }
1096 }
1097 }
1098
1099 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1100 out = result.values().toArray(out);
1101 return out;
1102 }
1103
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001104 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001105 public boolean isNetworkSupported(int networkType) {
1106 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001107 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001108 }
1109
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001110 /**
1111 * Return LinkProperties for the active (i.e., connected) default
1112 * network interface. It is assumed that at most one default network
1113 * is active at a time. If more than one is active, it is indeterminate
1114 * which will be returned.
1115 * @return the ip properties for the active network, or {@code null} if
1116 * none is active
1117 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001118 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001119 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001120 enforceAccessPermission();
1121 final int uid = Binder.getCallingUid();
1122 NetworkState state = getUnfilteredActiveNetworkState(uid);
1123 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001124 }
1125
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001126 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001127 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001128 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001129 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1130 if (nai != null) {
1131 synchronized (nai) {
1132 return new LinkProperties(nai.linkProperties);
1133 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001134 }
1135 return null;
1136 }
1137
Robert Greenwalt12e67352014-05-13 21:41:06 -07001138 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001139 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001140 public LinkProperties getLinkProperties(Network network) {
1141 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001142 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001143 if (nai != null) {
1144 synchronized (nai) {
1145 return new LinkProperties(nai.linkProperties);
1146 }
1147 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001148 return null;
1149 }
1150
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001151 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001152 if (nai != null) {
1153 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001154 if (nai.networkCapabilities != null) {
1155 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001156 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001157 }
1158 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001159 return null;
1160 }
1161
1162 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001163 public NetworkCapabilities getNetworkCapabilities(Network network) {
1164 enforceAccessPermission();
1165 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1166 }
1167
1168 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001169 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001170 // Require internal since we're handing out IMSI details
1171 enforceConnectivityInternalPermission();
1172
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001173 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001174 for (Network network : getAllNetworks()) {
1175 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1176 if (nai != null) {
1177 synchronized (nai) {
1178 final String subscriberId = (nai.networkMisc != null)
1179 ? nai.networkMisc.subscriberId : null;
1180 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1181 nai.networkCapabilities, network, subscriberId, null));
1182 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001183 }
1184 }
1185 return result.toArray(new NetworkState[result.size()]);
1186 }
1187
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001188 @Override
1189 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1190 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001191 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001192 final long token = Binder.clearCallingIdentity();
1193 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001194 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1195 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001196 try {
1197 return mPolicyManager.getNetworkQuotaInfo(state);
1198 } catch (RemoteException e) {
1199 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001200 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001201 return null;
1202 } finally {
1203 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001204 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001205 }
1206
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001207 @Override
1208 public boolean isActiveNetworkMetered() {
1209 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001210 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001211 final long token = Binder.clearCallingIdentity();
1212 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001213 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001214 } finally {
1215 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001216 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001217 }
1218
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001219 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1220 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1221 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001222 try {
1223 return mPolicyManager.isNetworkMetered(state);
1224 } catch (RemoteException e) {
1225 }
1226 }
1227 return false;
1228 }
1229
Jeff Sharkey216c1812012-08-05 14:29:23 -07001230 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1231 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001232 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001233 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001234 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001235 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001236 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001237
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001238 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 * Ensure that a network route exists to deliver traffic to the specified
1240 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001241 * @param networkType the type of the network over which traffic to the
1242 * specified host is to be routed
1243 * @param hostAddress the IP address of the host to which the route is
1244 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 * @return {@code true} on success, {@code false} on failure
1246 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001247 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001249 if (mProtectedNetworks.contains(networkType)) {
1250 enforceConnectivityInternalPermission();
1251 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001252
Chad Brubakerc0234532014-02-14 13:24:29 -08001253 InetAddress addr;
1254 try {
1255 addr = InetAddress.getByAddress(hostAddress);
1256 } catch (UnknownHostException e) {
1257 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1258 return false;
1259 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001262 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 return false;
1264 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001265
1266 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1267 if (nai == null) {
1268 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1269 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1270 } else {
1271 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1272 }
1273 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001274 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001275
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001276 DetailedState netState;
1277 synchronized (nai) {
1278 netState = nai.networkInfo.getDetailedState();
1279 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001280
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001281 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001282 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001283 log("requestRouteToHostAddress on down network "
1284 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001285 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001286 }
1287 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001289
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001290 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001291 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001292 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001293 LinkProperties lp;
1294 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001295 synchronized (nai) {
1296 lp = nai.linkProperties;
1297 netId = nai.network.netId;
1298 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001299 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001300 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1301 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001302 } finally {
1303 Binder.restoreCallingIdentity(token);
1304 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001305 }
1306
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001307 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001308 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001309 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001310 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001311 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001312 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001313 if (bestRoute.getGateway().equals(addr)) {
1314 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001315 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001316 } else {
1317 // if we will connect to this through another route, add a direct route
1318 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001319 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001320 }
1321 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001322 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001323 try {
1324 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1325 } catch (Exception e) {
1326 // never crash - catch them all
1327 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001328 return false;
1329 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001330 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001333 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1334 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001335 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001336 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001337 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001338 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001339 }
1340
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001341 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001342 // skip update when we've already applied rules
1343 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1344 if (oldRules == uidRules) return;
1345
1346 mUidRules.put(uid, uidRules);
1347 }
1348
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001349 // TODO: notify UID when it has requested targeted updates
1350 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001351
1352 @Override
1353 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001354 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001355 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001356 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001357 }
1358
1359 synchronized (mRulesLock) {
1360 mMeteredIfaces.clear();
1361 for (String iface : meteredIfaces) {
1362 mMeteredIfaces.add(iface);
1363 }
1364 }
1365 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001366
1367 @Override
1368 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1369 // caller is NPMS, since we only register with them
1370 if (LOGD_RULES) {
1371 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1372 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001373 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001374 };
1375
Robin Lee3b3dd942015-05-12 18:14:58 +01001376 /**
1377 * Require that the caller is either in the same user or has appropriate permission to interact
1378 * across users.
1379 *
1380 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1381 */
1382 private void enforceCrossUserPermission(int userId) {
1383 if (userId == UserHandle.getCallingUserId()) {
1384 // Not a cross-user call.
1385 return;
1386 }
1387 mContext.enforceCallingOrSelfPermission(
1388 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1389 "ConnectivityService");
1390 }
1391
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001392 private void enforceInternetPermission() {
1393 mContext.enforceCallingOrSelfPermission(
1394 android.Manifest.permission.INTERNET,
1395 "ConnectivityService");
1396 }
1397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001399 mContext.enforceCallingOrSelfPermission(
1400 android.Manifest.permission.ACCESS_NETWORK_STATE,
1401 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 }
1403
1404 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001405 mContext.enforceCallingOrSelfPermission(
1406 android.Manifest.permission.CHANGE_NETWORK_STATE,
1407 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
1409
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001410 private void enforceTetherAccessPermission() {
1411 mContext.enforceCallingOrSelfPermission(
1412 android.Manifest.permission.ACCESS_NETWORK_STATE,
1413 "ConnectivityService");
1414 }
1415
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001416 private void enforceConnectivityInternalPermission() {
1417 mContext.enforceCallingOrSelfPermission(
1418 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1419 "ConnectivityService");
1420 }
1421
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001422 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001423 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001424 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001425 }
1426
1427 private void sendInetConditionBroadcast(NetworkInfo info) {
1428 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1429 }
1430
Wink Saville628b0852011-08-04 15:01:58 -07001431 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001432 if (mLockdownTracker != null) {
1433 info = mLockdownTracker.augmentNetworkInfo(info);
1434 }
1435
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001436 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001437 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001438 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 if (info.isFailover()) {
1440 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1441 info.setFailover(false);
1442 }
1443 if (info.getReason() != null) {
1444 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1445 }
1446 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001447 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1448 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001450 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001451 return intent;
1452 }
1453
1454 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1455 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1456 }
1457
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001458 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001459 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1460 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1461 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001462 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001463 final long ident = Binder.clearCallingIdentity();
1464 try {
1465 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1466 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1467 } finally {
1468 Binder.restoreCallingIdentity(ident);
1469 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001470 }
1471
Mike Lockwood0f79b542009-08-14 14:18:49 -04001472 private void sendStickyBroadcast(Intent intent) {
1473 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001474 if (!mSystemReady) {
1475 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001476 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001477 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001478 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001479 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001480 }
1481
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001482 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001483 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1484 final IBatteryStats bs = BatteryStatsService.getService();
1485 try {
1486 NetworkInfo ni = intent.getParcelableExtra(
1487 ConnectivityManager.EXTRA_NETWORK_INFO);
1488 bs.noteConnectivityChanged(intent.getIntExtra(
1489 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1490 ni != null ? ni.getState().toString() : "?");
1491 } catch (RemoteException e) {
1492 }
1493 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001494 try {
1495 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1496 } finally {
1497 Binder.restoreCallingIdentity(ident);
1498 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001499 }
1500 }
1501
1502 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001503 loadGlobalProxy();
1504
Mike Lockwood0f79b542009-08-14 14:18:49 -04001505 synchronized(this) {
1506 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001507 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001508 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001509 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001510 }
1511 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001512 // load the global proxy at startup
1513 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001514
1515 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1516 // for user to unlock device.
1517 if (!updateLockdownVpn()) {
1518 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1519 mContext.registerReceiver(mUserPresentReceiver, filter);
1520 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001521
Erik Klineda4bfa82015-04-30 12:58:40 +09001522 // Configure whether mobile data is always on.
1523 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1524
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001525 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001526
1527 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 }
1529
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001530 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1531 @Override
1532 public void onReceive(Context context, Intent intent) {
1533 // Try creating lockdown tracker, since user present usually means
1534 // unlocked keystore.
1535 if (updateLockdownVpn()) {
1536 mContext.unregisterReceiver(this);
1537 }
1538 }
1539 };
1540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001542 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001543 *
1544 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001545 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001546 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001547 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1548 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001549
1550 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001551 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001552
Robert Greenwalt7b816022014-04-18 15:25:25 -07001553 if (networkAgent.networkCapabilities.hasTransport(
1554 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001555 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1556 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001557 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001558 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001559 } else if (networkAgent.networkCapabilities.hasTransport(
1560 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001561 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1562 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001563 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001564 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001565 } else {
1566 // do not track any other networks
1567 timeout = 0;
1568 }
1569
Robert Greenwalt7b816022014-04-18 15:25:25 -07001570 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001571 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001572 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001573 } catch (Exception e) {
1574 // You shall not crash!
1575 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001576 }
1577 }
1578 }
1579
1580 /**
1581 * Remove data activity tracking when network disconnects.
1582 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001583 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1584 final String iface = networkAgent.linkProperties.getInterfaceName();
1585 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001586
Robert Greenwalt7b816022014-04-18 15:25:25 -07001587 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1588 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001589 try {
1590 // the call fails silently if no idletimer setup for this interface
1591 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001592 } catch (Exception e) {
1593 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001594 }
1595 }
1596 }
1597
1598 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001599 * Reads the network specific MTU size from reources.
1600 * and set it on it's iface.
1601 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001602 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1603 final String iface = newLp.getInterfaceName();
1604 final int mtu = newLp.getMtu();
1605 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1606 if (VDBG) log("identical MTU - not setting");
1607 return;
1608 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001609
Robert Greenwalt43074032014-08-15 17:53:05 -07001610 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001611 loge("Unexpected mtu value: " + mtu + ", " + iface);
1612 return;
1613 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001614
w1997615afd812014-08-05 15:18:11 -07001615 // Cannot set MTU without interface name
1616 if (TextUtils.isEmpty(iface)) {
1617 loge("Setting MTU size with null iface.");
1618 return;
1619 }
1620
Robert Greenwalt7b816022014-04-18 15:25:25 -07001621 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001622 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001623 mNetd.setMtu(iface, mtu);
1624 } catch (Exception e) {
1625 Slog.e(TAG, "exception in setMtu()" + e);
1626 }
1627 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001628
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001629 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001630 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1631
1632 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001633 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001634 protected int getDefaultTcpRwnd() {
1635 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1636 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001637
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001638 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1639 if (isDefaultNetwork(nai) == false) {
1640 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001641 }
1642
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001643 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1644 String[] values = null;
1645 if (tcpBufferSizes != null) {
1646 values = tcpBufferSizes.split(",");
1647 }
1648
1649 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001650 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001651 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1652 values = tcpBufferSizes.split(",");
1653 }
1654
1655 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1656
1657 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001658 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001659
1660 final String prefix = "/sys/kernel/ipv4/tcp_";
1661 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1662 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1663 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1664 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1665 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1666 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1667 mCurrentTcpBufferSizes = tcpBufferSizes;
1668 } catch (IOException e) {
1669 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001670 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001671
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001672 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001673 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001674 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1675 if (rwndValue != 0) {
1676 SystemProperties.set(sysctlKey, rwndValue.toString());
1677 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001678 }
1679
Mattias Falk8b47b362011-08-23 14:15:13 +02001680 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001681 /*
1682 * Tell the VMs to toss their DNS caches
1683 */
1684 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1685 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001686 /*
1687 * Connectivity events can happen before boot has completed ...
1688 */
1689 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001690 final long ident = Binder.clearCallingIdentity();
1691 try {
1692 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1693 } finally {
1694 Binder.restoreCallingIdentity(ident);
1695 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001696 }
1697
Robert Greenwalt562cc542014-05-15 18:07:26 -07001698 @Override
1699 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001700 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1701 NETWORK_RESTORE_DELAY_PROP_NAME);
1702 if(restoreDefaultNetworkDelayStr != null &&
1703 restoreDefaultNetworkDelayStr.length() != 0) {
1704 try {
1705 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1706 } catch (NumberFormatException e) {
1707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001709 // if the system property isn't set, use the value for the apn type
1710 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1711
1712 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1713 (mNetConfigs[networkType] != null)) {
1714 ret = mNetConfigs[networkType].restoreTime;
1715 }
1716 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 }
1718
Erik Kline379747a2015-06-05 17:47:34 +09001719 private boolean shouldPerformDiagnostics(String[] args) {
1720 for (String arg : args) {
1721 if (arg.equals("--diag")) {
1722 return true;
1723 }
1724 }
1725 return false;
1726 }
1727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001729 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1730 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001731 if (mContext.checkCallingOrSelfPermission(
1732 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001734 pw.println("Permission Denial: can't dump ConnectivityService " +
1735 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1736 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 return;
1738 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001739
Erik Kline379747a2015-06-05 17:47:34 +09001740 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1741 if (shouldPerformDiagnostics(args)) {
1742 final long DIAG_TIME_MS = 5000;
1743 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1744 // Start gathering diagnostic information.
1745 netDiags.add(new NetworkDiagnostics(
1746 nai.network,
1747 new LinkProperties(nai.linkProperties),
1748 DIAG_TIME_MS));
1749 }
1750
1751 for (NetworkDiagnostics netDiag : netDiags) {
1752 pw.println();
1753 netDiag.waitForMeasurements();
1754 netDiag.dump(pw);
1755 }
1756
1757 return;
1758 }
1759
Lorenzo Colittie3805462015-06-03 11:18:24 +09001760 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001761 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001762 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001763 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001764 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001765 pw.println();
1766
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001767 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1768 pw.print("Active default network: ");
1769 if (defaultNai == null) {
1770 pw.println("none");
1771 } else {
1772 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001774 pw.println();
1775
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001776 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001777 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001778 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1779 pw.println(nai.toString());
1780 pw.increaseIndent();
1781 pw.println("Requests:");
1782 pw.increaseIndent();
1783 for (int i = 0; i < nai.networkRequests.size(); i++) {
1784 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001785 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001786 pw.decreaseIndent();
1787 pw.println("Lingered:");
1788 pw.increaseIndent();
1789 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1790 pw.decreaseIndent();
1791 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001792 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001793 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001794 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001795
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001796 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001797 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001798 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1799 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001800 }
1801 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001802 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001803
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001804 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001805
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001806 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001807 pw.print("mNetTransitionWakeLock: currently " +
1808 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1809 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1810 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1811 } else {
1812 pw.println(", last requested never");
1813 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001814 }
1815 pw.println();
1816
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001817 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001818
Lorenzo Colittie3805462015-06-03 11:18:24 +09001819 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001820 pw.println();
1821 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001822 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001823 for(int i = 0; i < mInetLog.size(); i++) {
1824 pw.println(mInetLog.get(i));
1825 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001826 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
1829
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001830 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001831 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001832 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001833 if (officialNai != null && officialNai.equals(nai)) return true;
1834 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001835 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001836 " - " + nai);
1837 }
1838 return false;
1839 }
1840
Paul Jensenc8b9a742014-09-30 15:37:41 -04001841 private boolean isRequest(NetworkRequest request) {
1842 return mNetworkRequests.get(request).isRequest;
1843 }
1844
Robert Greenwalt42acef32009-08-12 16:08:25 -07001845 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001846 private class NetworkStateTrackerHandler extends Handler {
1847 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001848 super(looper);
1849 }
1850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 @Override
1852 public void handleMessage(Message msg) {
1853 NetworkInfo info;
1854 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001855 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001856 handleAsyncChannelHalfConnect(msg);
1857 break;
1858 }
1859 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1860 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1861 if (nai != null) nai.asyncChannel.disconnect();
1862 break;
1863 }
1864 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1865 handleAsyncChannelDisconnected(msg);
1866 break;
1867 }
1868 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1869 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1870 if (nai == null) {
1871 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1872 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001873 final NetworkCapabilities networkCapabilities =
1874 (NetworkCapabilities)msg.obj;
1875 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1876 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1877 Slog.wtf(TAG, "BUG: " + nai + " has stateful capability.");
1878 }
1879 updateCapabilities(nai, networkCapabilities,
1880 NascentState.NOT_JUST_VALIDATED);
Robert Greenwalte049c232014-04-11 15:53:27 -07001881 }
1882 break;
1883 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001884 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1885 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1886 if (nai == null) {
1887 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1888 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001889 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001890 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001891 "; created=" + nai.created);
1892 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001893 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001894 synchronized (nai) {
1895 nai.linkProperties = (LinkProperties)msg.obj;
1896 }
Paul Jenseneec75412014-08-04 12:21:19 -04001897 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001898 }
1899 break;
1900 }
1901 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1902 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1903 if (nai == null) {
1904 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1905 break;
1906 }
1907 info = (NetworkInfo) msg.obj;
1908 updateNetworkInfo(nai, info);
1909 break;
1910 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001911 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1912 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1913 if (nai == null) {
1914 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1915 break;
1916 }
1917 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001918 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001919 break;
1920 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001921 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1922 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1923 if (nai == null) {
1924 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1925 break;
1926 }
1927 try {
1928 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001929 } catch (Exception e) {
1930 // Never crash!
1931 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001932 }
1933 break;
1934 }
1935 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1936 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1937 if (nai == null) {
1938 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1939 break;
1940 }
1941 try {
1942 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001943 } catch (Exception e) {
1944 // Never crash!
1945 loge("Exception in removeVpnUidRanges: " + e);
1946 }
1947 break;
1948 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001949 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1950 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1951 if (nai == null) {
1952 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1953 break;
1954 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001955 if (nai.created && !nai.networkMisc.explicitlySelected) {
1956 loge("ERROR: created network explicitly selected.");
1957 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001958 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001959 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001960 break;
1961 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001962 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001963 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001964 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1965 final boolean valid =
1966 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04001967 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
1968 if (valid != nai.lastValidated) {
1969 final int oldScore = nai.getCurrentScore();
1970 final NascentState nascent = (valid && !nai.everValidated) ?
1971 NascentState.JUST_VALIDATED : NascentState.NOT_JUST_VALIDATED;
1972 nai.lastValidated = valid;
1973 nai.everValidated |= valid;
1974 updateCapabilities(nai, nai.networkCapabilities, nascent);
1975 // If score has changed, rebroadcast to NetworkFactories. b/17726566
1976 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04001977 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001978 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001979 // Let the NetworkAgent know the state of its network
1980 nai.asyncChannel.sendMessage(
1981 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1982 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1983 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001984 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001985 break;
1986 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001987 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001988 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001989 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1990 handleLingerComplete(nai);
1991 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001992 break;
1993 }
Paul Jensen869868be2014-05-15 10:33:05 -04001994 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09001995 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04001996 final boolean visible = (msg.arg1 != 0);
1997 final NetworkAgentInfo nai;
1998 synchronized (mNetworkForNetId) {
1999 nai = mNetworkForNetId.get(netId);
2000 }
2001 // If captive portal status has changed, update capabilities.
2002 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2003 nai.lastCaptivePortalDetected = visible;
2004 nai.everCaptivePortalDetected |= visible;
Paul Jensen1c7ba022015-06-16 14:27:36 -04002005 updateCapabilities(nai, nai.networkCapabilities,
2006 NascentState.NOT_JUST_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002007 }
2008 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002009 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002010 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002011 if (nai == null) {
2012 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2013 break;
2014 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002015 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002016 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2017 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002018 }
Paul Jensen869868be2014-05-15 10:33:05 -04002019 break;
2020 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002021 }
2022 }
2023 }
2024
Paul Jensen0cc17322014-11-25 15:26:53 -05002025 // Cancel any lingering so the linger timeout doesn't teardown a network.
2026 // This should be called when a network begins satisfying a NetworkRequest.
2027 // Note: depending on what state the NetworkMonitor is in (e.g.,
2028 // if it's awaiting captive portal login, or if validation failed), this
2029 // may trigger a re-evaluation of the network.
2030 private void unlinger(NetworkAgentInfo nai) {
2031 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002032 // If network has never been validated, it cannot have been lingered, so don't bother
2033 // needlessly triggering a re-evaluation.
2034 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002035 nai.networkLingered.clear();
2036 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2037 }
2038
Robert Greenwalt7b816022014-04-18 15:25:25 -07002039 private void handleAsyncChannelHalfConnect(Message msg) {
2040 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002041 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002042 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2043 if (VDBG) log("NetworkFactory connected");
2044 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002045 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002046 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002047 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002048 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002049 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002050 }
2051 } else {
2052 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002053 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002054 }
2055 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2056 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2057 if (VDBG) log("NetworkAgent connected");
2058 // A network agent has requested a connection. Establish the connection.
2059 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2060 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2061 } else {
2062 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002063 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002064 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002065 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002066 synchronized (mNetworkForNetId) {
2067 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002068 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002069 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002070 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002071 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002072 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002073 }
2074 }
2075 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002076
Robert Greenwalt7b816022014-04-18 15:25:25 -07002077 private void handleAsyncChannelDisconnected(Message msg) {
2078 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2079 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002080 if (DBG) {
2081 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2082 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002083 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002084 // TODO - if we move the logic to the network agent (have them disconnect
2085 // because they lost all their requests or because their score isn't good)
2086 // then they would disconnect organically, report their new state and then
2087 // disconnect the channel.
2088 if (nai.networkInfo.isConnected()) {
2089 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2090 null, null);
2091 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002092 final boolean wasDefault = isDefaultNetwork(nai);
2093 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002094 mDefaultInetConditionPublished = 0;
2095 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002096 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002097 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002098 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002099 mNetworkAgentInfos.remove(msg.replyTo);
2100 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002101 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002102 // Remove the NetworkAgent, but don't mark the netId as
2103 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002104 mNetworkForNetId.remove(nai.network.netId);
2105 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002106 // Since we've lost the network, go through all the requests that
2107 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002108 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002109 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002110 for (int i = 0; i < nai.networkRequests.size(); i++) {
2111 NetworkRequest request = nai.networkRequests.valueAt(i);
2112 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2113 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002114 if (DBG) {
2115 log("Checking for replacement network to handle request " + request );
2116 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002117 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002118 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002119 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002120 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2121 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002122 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002123 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002124 alternative = existing;
2125 }
2126 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002127 if (alternative != null) {
2128 if (DBG) log(" found replacement in " + alternative.name());
2129 if (!toActivate.contains(alternative)) {
2130 toActivate.add(alternative);
2131 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002132 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 }
2134 }
2135 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2136 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002137 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002138 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002140 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002141 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002142 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002143 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2144 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002145 }
Paul Jensen62d30802015-06-17 14:42:30 -04002146 if (nai.created) {
2147 // Tell netd to clean up the configuration for this network
2148 // (routing rules, DNS, etc).
2149 // This may be slow as it requires a lot of netd shelling out to ip and
2150 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2151 // after we've rematched networks with requests which should make a potential
2152 // fallback network the default or requested a new network from the
2153 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2154 // long time.
2155 try {
2156 mNetd.removeNetwork(nai.network.netId);
2157 } catch (Exception e) {
2158 loge("Exception removing network: " + e);
2159 }
2160 }
2161 synchronized (mNetworkForNetId) {
2162 mNetIdInUse.delete(nai.network.netId);
2163 }
2164 } else {
2165 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2166 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002167 }
2168 }
2169
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002170 // If this method proves to be too slow then we can maintain a separate
2171 // pendingIntent => NetworkRequestInfo map.
2172 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2173 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2174 Intent intent = pendingIntent.getIntent();
2175 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2176 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2177 if (existingPendingIntent != null &&
2178 existingPendingIntent.getIntent().filterEquals(intent)) {
2179 return entry.getValue();
2180 }
2181 }
2182 return null;
2183 }
2184
2185 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2186 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2187
2188 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2189 if (existingRequest != null) { // remove the existing request.
2190 if (DBG) log("Replacing " + existingRequest.request + " with "
2191 + nri.request + " because their intents matched.");
2192 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2193 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002194 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002195 }
2196
Erik Klineda4bfa82015-04-30 12:58:40 +09002197 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002198 mNetworkRequests.put(nri.request, nri);
2199
Paul Jensen0cc17322014-11-25 15:26:53 -05002200 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2201
Robert Greenwalt9258c642014-03-26 16:47:06 -07002202 // Check for the best currently alive network that satisfies this request
2203 NetworkAgentInfo bestNetwork = null;
2204 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002205 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002206 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002207 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002208 if (!nri.isRequest) {
2209 // Not setting bestNetwork here as a listening NetworkRequest may be
2210 // satisfied by multiple Networks. Instead the request is added to
2211 // each satisfying Network and notified about each.
Paul Jensen3d911462015-06-12 06:40:24 -04002212 if (!network.addRequest(nri.request)) {
2213 Slog.wtf(TAG, "BUG: " + network.name() + " already has " + nri.request);
2214 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002215 notifyNetworkCallback(network, nri);
2216 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002217 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002218 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002219 }
2220 }
2221 }
2222 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002223 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002224 unlinger(bestNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04002225 if (!bestNetwork.addRequest(nri.request)) {
2226 Slog.wtf(TAG, "BUG: " + bestNetwork.name() + " already has " + nri.request);
2227 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07002228 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002229 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002230 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002231 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2232 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002233 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002234
Lorenzo Colittia793a672014-07-31 23:20:17 +09002235 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002236 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002237 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002238 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002239 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002240 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002241 }
2242 }
2243 }
2244
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002245 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2246 int callingUid) {
2247 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2248 if (nri != null) {
2249 handleReleaseNetworkRequest(nri.request, callingUid);
2250 }
2251 }
2252
Paul Jensen99364842014-12-09 11:43:45 -05002253 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2254 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2255 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2256 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2257 private boolean unneeded(NetworkAgentInfo nai) {
2258 if (!nai.created || nai.isVPN()) return false;
2259 boolean unneeded = true;
2260 if (nai.everValidated) {
2261 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2262 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2263 try {
2264 if (isRequest(nr)) unneeded = false;
2265 } catch (Exception e) {
2266 loge("Request " + nr + " not found in mNetworkRequests.");
2267 loge(" it came from request list of " + nai.name());
2268 }
2269 }
2270 } else {
2271 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2272 // If this Network is already the highest scoring Network for a request, or if
2273 // there is hope for it to become one if it validated, then it is needed.
2274 if (nri.isRequest && nai.satisfies(nri.request) &&
2275 (nai.networkRequests.get(nri.request.requestId) != null ||
2276 // Note that this catches two important cases:
2277 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2278 // is currently satisfying the request. This is desirable when
2279 // cellular ends up validating but WiFi does not.
2280 // 2. Unvalidated WiFi will not be reaped when validated cellular
2281 // is currently satsifying the request. This is desirable when
2282 // WiFi ends up validating and out scoring cellular.
2283 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2284 nai.getCurrentScoreAsValidated())) {
2285 unneeded = false;
2286 break;
2287 }
2288 }
2289 }
2290 return unneeded;
2291 }
2292
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002293 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2294 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002295 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002296 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002297 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2298 return;
2299 }
2300 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002301 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002302 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002303 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002304 // Find all networks that are satisfying this request and remove the request
2305 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002306 // TODO - it's my understanding that for a request there is only a single
2307 // network satisfying it, so this loop is wasteful
2308 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002309 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2310 if (nai.networkRequests.get(nri.request.requestId) != null) {
2311 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002312 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002313 log(" Removing from current network " + nai.name() +
2314 ", leaving " + nai.networkRequests.size() +
2315 " requests.");
2316 }
Paul Jensen99364842014-12-09 11:43:45 -05002317 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002318 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002319 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002320 } else {
2321 // suspect there should only be one pass through here
2322 // but if any were kept do the check below
2323 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002324 }
2325 }
2326 }
2327
Robert Greenwalt51481852015-01-08 14:43:31 -08002328 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2329 if (nai != null) {
2330 mNetworkForRequestId.remove(nri.request.requestId);
2331 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002332 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002333 // that a network connected to serve it, even though the network was already
2334 // connected. Now that this request has gone away, we might have to pretend
2335 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002336 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002337 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2338 boolean doRemove = true;
2339 if (wasKept) {
2340 // check if any of the remaining requests for this network are for the
2341 // same legacy type - if so, don't remove the nai
2342 for (int i = 0; i < nai.networkRequests.size(); i++) {
2343 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2344 if (otherRequest.legacyType == nri.request.legacyType &&
2345 isRequest(otherRequest)) {
2346 if (DBG) log(" still have other legacy request - leaving");
2347 doRemove = false;
2348 }
2349 }
2350 }
2351
2352 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002353 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002354 }
2355 }
2356
Robert Greenwalta67be032014-05-16 15:49:14 -07002357 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002358 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2359 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002360 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002361 } else {
2362 // listens don't have a singular affectedNetwork. Check all networks to see
2363 // if this listen request applies and remove it.
2364 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2365 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002366 }
2367 }
2368 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2369 }
2370 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002371
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002372 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2373 enforceConnectivityInternalPermission();
2374 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2375 accept ? 1 : 0, always ? 1: 0, network));
2376 }
2377
2378 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2379 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2380 " accept=" + accept + " always=" + always);
2381
2382 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2383 if (nai == null) {
2384 // Nothing to do.
2385 return;
2386 }
2387
2388 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002389 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002390 return;
2391 }
2392
2393 if (!nai.networkMisc.explicitlySelected) {
2394 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2395 }
2396
2397 if (accept != nai.networkMisc.acceptUnvalidated) {
2398 int oldScore = nai.getCurrentScore();
2399 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen1c7ba022015-06-16 14:27:36 -04002400 rematchAllNetworksAndRequests(nai, oldScore, NascentState.NOT_JUST_VALIDATED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002401 sendUpdatedScoreToFactories(nai);
2402 }
2403
2404 if (always) {
2405 nai.asyncChannel.sendMessage(
2406 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2407 }
2408
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002409 if (!accept) {
2410 // Tell the NetworkAgent that the network does not have Internet access (because that's
2411 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2412 // the future. We do this now because NetworkMonitor might not yet have finished
2413 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2414 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2415 NetworkAgent.INVALID_NETWORK, 0, null);
2416 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2417 // to reconnect to it immediately. http://b/20739299
2418 }
2419
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002420 }
2421
2422 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002423 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002424 mHandler.sendMessageDelayed(
2425 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2426 PROMPT_UNVALIDATED_DELAY_MS);
2427 }
2428
2429 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002430 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002431 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2432
2433 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2434 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002435 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002436 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002437 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2438 return;
2439 }
2440
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002441 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002442 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002443 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2444 intent.setClassName("com.android.settings",
2445 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002446
2447 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2448 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2449 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002450 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002451 }
2452
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002453 private class InternalHandler extends Handler {
2454 public InternalHandler(Looper looper) {
2455 super(looper);
2456 }
2457
2458 @Override
2459 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002460 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002461 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002462 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002463 String causedBy = null;
2464 synchronized (ConnectivityService.this) {
2465 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2466 mNetTransitionWakeLock.isHeld()) {
2467 mNetTransitionWakeLock.release();
2468 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002469 } else {
2470 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002471 }
2472 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002473 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2474 log("Failed to find a new network - expiring NetTransition Wakelock");
2475 } else {
2476 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2477 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002478 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002479 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002480 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002481 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002482 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002483 break;
2484 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002485 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002486 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002487 sendStickyBroadcast(intent);
2488 break;
2489 }
Jason Monkdecd2952013-10-10 14:02:51 -04002490 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002491 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002492 break;
2493 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002494 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002495 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2496 break;
2497 }
2498 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2499 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002500 break;
2501 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002502 case EVENT_REGISTER_NETWORK_AGENT: {
2503 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2504 break;
2505 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002506 case EVENT_REGISTER_NETWORK_REQUEST:
2507 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002508 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002509 break;
2510 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002511 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2512 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002513 handleRegisterNetworkRequestWithIntent(msg);
2514 break;
2515 }
2516 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2517 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2518 break;
2519 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002520 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002521 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002522 break;
2523 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002524 case EVENT_SET_ACCEPT_UNVALIDATED: {
2525 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2526 break;
2527 }
2528 case EVENT_PROMPT_UNVALIDATED: {
2529 handlePromptUnvalidated((Network) msg.obj);
2530 break;
2531 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002532 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2533 handleMobileDataAlwaysOn();
2534 break;
2535 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002536 case EVENT_SYSTEM_READY: {
2537 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2538 nai.networkMonitor.systemReady = true;
2539 }
2540 break;
2541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 }
2543 }
2544 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002545
2546 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002547 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002548 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002549 if (isTetheringSupported()) {
2550 return mTethering.tether(iface);
2551 } else {
2552 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2553 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002554 }
2555
2556 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002557 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002558 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002559
2560 if (isTetheringSupported()) {
2561 return mTethering.untether(iface);
2562 } else {
2563 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2564 }
2565 }
2566
2567 // javadoc from interface
2568 public int getLastTetherError(String iface) {
2569 enforceTetherAccessPermission();
2570
2571 if (isTetheringSupported()) {
2572 return mTethering.getLastTetherError(iface);
2573 } else {
2574 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2575 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002576 }
2577
2578 // TODO - proper iface API for selection by property, inspection, etc
2579 public String[] getTetherableUsbRegexs() {
2580 enforceTetherAccessPermission();
2581 if (isTetheringSupported()) {
2582 return mTethering.getTetherableUsbRegexs();
2583 } else {
2584 return new String[0];
2585 }
2586 }
2587
2588 public String[] getTetherableWifiRegexs() {
2589 enforceTetherAccessPermission();
2590 if (isTetheringSupported()) {
2591 return mTethering.getTetherableWifiRegexs();
2592 } else {
2593 return new String[0];
2594 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002595 }
2596
Danica Chang6fdd0c62010-08-11 14:54:43 -07002597 public String[] getTetherableBluetoothRegexs() {
2598 enforceTetherAccessPermission();
2599 if (isTetheringSupported()) {
2600 return mTethering.getTetherableBluetoothRegexs();
2601 } else {
2602 return new String[0];
2603 }
2604 }
2605
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002606 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002607 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002608 if (isTetheringSupported()) {
2609 return mTethering.setUsbTethering(enable);
2610 } else {
2611 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2612 }
2613 }
2614
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002615 // TODO - move iface listing, queries, etc to new module
2616 // javadoc from interface
2617 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002618 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002619 return mTethering.getTetherableIfaces();
2620 }
2621
2622 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002623 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002624 return mTethering.getTetheredIfaces();
2625 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002626
Robert Greenwalt5a735062010-03-02 17:25:02 -08002627 public String[] getTetheringErroredIfaces() {
2628 enforceTetherAccessPermission();
2629 return mTethering.getErroredIfaces();
2630 }
2631
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002632 public String[] getTetheredDhcpRanges() {
2633 enforceConnectivityInternalPermission();
2634 return mTethering.getTetheredDhcpRanges();
2635 }
2636
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002637 // if ro.tether.denied = true we default to no tethering
2638 // gservices could set the secure setting to 1 though to enable it on a build where it
2639 // had previously been turned off.
2640 public boolean isTetheringSupported() {
2641 enforceTetherAccessPermission();
2642 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002643 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002644 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2645 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002646 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2647 mTethering.getTetherableWifiRegexs().length != 0 ||
2648 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2649 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002650 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002651
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002652 // Called when we lose the default network and have no replacement yet.
2653 // This will automatically be cleared after X seconds or a new default network
2654 // becomes CONNECTED, whichever happens first. The timer is started by the
2655 // first caller and not restarted by subsequent callers.
2656 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002657 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002658 synchronized (this) {
2659 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002660 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002661 mNetTransitionWakeLock.acquire();
2662 mNetTransitionWakeLockCausedBy = forWhom;
2663 }
2664 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002665 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002666 mNetTransitionWakeLockTimeout);
2667 return;
2668 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002669
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002670 // 100 percent is full good, 0 is full bad.
2671 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002672 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002673 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002674 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002675 }
2676
Paul Jensenbfd17b72015-04-07 12:43:13 -04002677 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002678 enforceAccessPermission();
2679 enforceInternetPermission();
2680
Paul Jensenbfd17b72015-04-07 12:43:13 -04002681 NetworkAgentInfo nai;
2682 if (network == null) {
2683 nai = getDefaultNetwork();
2684 } else {
2685 nai = getNetworkAgentInfoForNetwork(network);
2686 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002687 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002688 // Revalidate if the app report does not match our current validated state.
2689 if (hasConnectivity == nai.lastValidated) return;
2690 final int uid = Binder.getCallingUid();
2691 if (DBG) {
2692 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2693 ") by " + uid);
2694 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002695 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002696 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2697 // which isn't meant to work on uncreated networks.
2698 if (!nai.created) return;
2699
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002700 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002701
2702 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2703 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002704 }
2705
Paul Jensen25a217c2015-02-27 22:55:47 -05002706 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2707 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2708 enforceConnectivityInternalPermission();
2709 }
2710 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2711 if (nai == null) return;
2712 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2713 actionToken);
2714 }
2715
Paul Jensencee9b512015-05-06 07:32:40 -04002716 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002717 // this information is already available as a world read/writable jvm property
2718 // so this API change wouldn't have a benifit. It also breaks the passing
2719 // of proxy info to all the JVMs.
2720 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002721 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002722 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002723 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2724 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002725 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002726 }
2727
Paul Jensencee9b512015-05-06 07:32:40 -04002728 public ProxyInfo getProxyForNetwork(Network network) {
2729 if (network == null) return getDefaultProxy();
2730 final ProxyInfo globalProxy = getGlobalProxy();
2731 if (globalProxy != null) return globalProxy;
2732 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2733 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2734 // caller may not have.
2735 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2736 if (nai == null) return null;
2737 synchronized (nai) {
2738 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2739 if (proxyInfo == null) return null;
2740 return new ProxyInfo(proxyInfo);
2741 }
2742 }
2743
Paul Jensene0bef712014-12-10 15:12:18 -05002744 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2745 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2746 // proxy is null then there is no proxy in place).
2747 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2748 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2749 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2750 proxy = null;
2751 }
2752 return proxy;
2753 }
2754
2755 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2756 // better for determining if a new proxy broadcast is necessary:
2757 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2758 // avoid unnecessary broadcasts.
2759 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2760 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2761 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2762 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2763 // all set.
2764 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2765 a = canonicalizeProxyInfo(a);
2766 b = canonicalizeProxyInfo(b);
2767 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2768 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2769 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2770 }
2771
Jason Monk207900c2014-04-25 15:00:09 -04002772 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002773 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002774
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002775 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002776 if (proxyProperties == mGlobalProxy) return;
2777 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2778 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2779
2780 String host = "";
2781 int port = 0;
2782 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002783 String pacFileUrl = "";
2784 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002785 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002786 if (!proxyProperties.isValid()) {
2787 if (DBG)
2788 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2789 return;
2790 }
Jason Monk207900c2014-04-25 15:00:09 -04002791 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002792 host = mGlobalProxy.getHost();
2793 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002794 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002795 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002796 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002797 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002798 } else {
2799 mGlobalProxy = null;
2800 }
2801 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002802 final long token = Binder.clearCallingIdentity();
2803 try {
2804 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2805 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2806 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2807 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002808 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002809 } finally {
2810 Binder.restoreCallingIdentity(token);
2811 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002812
Jason Monkcf0f97a2014-10-02 15:39:38 -04002813 if (mGlobalProxy == null) {
2814 proxyProperties = mDefaultProxy;
2815 }
2816 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002817 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002818 }
2819
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002820 private void loadGlobalProxy() {
2821 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002822 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2823 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2824 String exclList = Settings.Global.getString(res,
2825 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002826 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2827 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002828 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002829 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002830 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002831 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002832 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002833 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002834 if (!proxyProperties.isValid()) {
2835 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2836 return;
2837 }
2838
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002839 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002840 mGlobalProxy = proxyProperties;
2841 }
2842 }
2843 }
2844
Jason Monk207900c2014-04-25 15:00:09 -04002845 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002846 // this information is already available as a world read/writable jvm property
2847 // so this API change wouldn't have a benifit. It also breaks the passing
2848 // of proxy info to all the JVMs.
2849 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002850 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002851 return mGlobalProxy;
2852 }
2853 }
2854
Jason Monk207900c2014-04-25 15:00:09 -04002855 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002856 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002857 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002858 proxy = null;
2859 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002860 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002861 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002862 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002863 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002864 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2865 return;
2866 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002867
2868 // This call could be coming from the PacManager, containing the port of the local
2869 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2870 // global (to get the correct local port), and send a broadcast.
2871 // TODO: Switch PacManager to have its own message to send back rather than
2872 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002873 if ((mGlobalProxy != null) && (proxy != null)
2874 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002875 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2876 mGlobalProxy = proxy;
2877 sendProxyBroadcast(mGlobalProxy);
2878 return;
2879 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002880 mDefaultProxy = proxy;
2881
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002882 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002883 if (!mDefaultProxyDisabled) {
2884 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002885 }
2886 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002887 }
2888
Paul Jensene0bef712014-12-10 15:12:18 -05002889 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2890 // This method gets called when any network changes proxy, but the broadcast only ever contains
2891 // the default proxy (even if it hasn't changed).
2892 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2893 // world where an app might be bound to a non-default network.
2894 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2895 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2896 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2897
2898 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2899 sendProxyBroadcast(getDefaultProxy());
2900 }
2901 }
2902
Robert Greenwalt434203a2010-10-11 16:00:27 -07002903 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002904 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2905 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002906 if (!TextUtils.isEmpty(proxy)) {
2907 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002908 if (data.length == 0) {
2909 return;
2910 }
2911
Robert Greenwalt434203a2010-10-11 16:00:27 -07002912 String proxyHost = data[0];
2913 int proxyPort = 8080;
2914 if (data.length > 1) {
2915 try {
2916 proxyPort = Integer.parseInt(data[1]);
2917 } catch (NumberFormatException e) {
2918 return;
2919 }
2920 }
Jason Monk207900c2014-04-25 15:00:09 -04002921 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002922 setGlobalProxy(p);
2923 }
2924 }
2925
Jason Monk207900c2014-04-25 15:00:09 -04002926 private void sendProxyBroadcast(ProxyInfo proxy) {
2927 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002928 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002929 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002930 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002931 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2932 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002933 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002934 final long ident = Binder.clearCallingIdentity();
2935 try {
2936 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2937 } finally {
2938 Binder.restoreCallingIdentity(ident);
2939 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002940 }
2941
2942 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002943 final private HashMap<Uri, Integer> mUriEventMap;
2944 final private Context mContext;
2945 final private Handler mHandler;
2946
2947 SettingsObserver(Context context, Handler handler) {
2948 super(null);
2949 mUriEventMap = new HashMap<Uri, Integer>();
2950 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002951 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002952 }
2953
Erik Klineda4bfa82015-04-30 12:58:40 +09002954 void observe(Uri uri, int what) {
2955 mUriEventMap.put(uri, what);
2956 final ContentResolver resolver = mContext.getContentResolver();
2957 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002958 }
2959
2960 @Override
2961 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002962 Slog.wtf(TAG, "Should never be reached.");
2963 }
2964
2965 @Override
2966 public void onChange(boolean selfChange, Uri uri) {
2967 final Integer what = mUriEventMap.get(uri);
2968 if (what != null) {
2969 mHandler.obtainMessage(what.intValue()).sendToTarget();
2970 } else {
2971 loge("No matching event to send for URI=" + uri);
2972 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002973 }
2974 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002975
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002976 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002977 Slog.d(TAG, s);
2978 }
2979
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002980 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002981 Slog.e(TAG, s);
2982 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002983
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002984 private static <T> T checkNotNull(T value, String message) {
2985 if (value == null) {
2986 throw new NullPointerException(message);
2987 }
2988 return value;
2989 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002990
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002991 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002992 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002993 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2994 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2995 *
2996 * @param oldPackage Package name of the application which currently controls VPN, which will
2997 * be replaced. If there is no such application, this should should either be
2998 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2999 * @param newPackage Package name of the application which should gain control of VPN, or
3000 * {@code null} to disable.
3001 * @param userId User for whom to prepare the new VPN.
3002 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003003 * @hide
3004 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003005 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003006 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3007 int userId) {
3008 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003009 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003010
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003011 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003012 Vpn vpn = mVpns.get(userId);
3013 if (vpn != null) {
3014 return vpn.prepare(oldPackage, newPackage);
3015 } else {
3016 return false;
3017 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003018 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003019 }
3020
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003021 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003022 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3023 * This method is used by system-privileged apps.
3024 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3025 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3026 *
3027 * @param packageName The package for which authorization state should change.
3028 * @param userId User for whom {@code packageName} is installed.
3029 * @param authorized {@code true} if this app should be able to start a VPN connection without
3030 * explicit user approval, {@code false} if not.
3031 *
Jeff Davidson05542602014-08-11 14:07:27 -07003032 * @hide
3033 */
3034 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003035 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3036 enforceCrossUserPermission(userId);
3037
Jeff Davidson05542602014-08-11 14:07:27 -07003038 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003039 Vpn vpn = mVpns.get(userId);
3040 if (vpn != null) {
3041 vpn.setPackageAuthorization(packageName, authorized);
3042 }
Jeff Davidson05542602014-08-11 14:07:27 -07003043 }
3044 }
3045
3046 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003047 * Configure a TUN interface and return its file descriptor. Parameters
3048 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003049 * and not available in ConnectivityManager. Permissions are checked in
3050 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003051 * @hide
3052 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003053 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003054 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003055 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003056 int user = UserHandle.getUserId(Binder.getCallingUid());
3057 synchronized(mVpns) {
3058 return mVpns.get(user).establish(config);
3059 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003060 }
3061
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003062 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003063 * Start legacy VPN, controlling native daemons as needed. Creates a
3064 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003065 */
3066 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003067 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003068 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003069 final LinkProperties egress = getActiveLinkProperties();
3070 if (egress == null) {
3071 throw new IllegalStateException("Missing active network connection");
3072 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003073 int user = UserHandle.getUserId(Binder.getCallingUid());
3074 synchronized(mVpns) {
3075 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3076 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003077 }
3078
3079 /**
3080 * Return the information of the ongoing legacy VPN. This method is used
3081 * by VpnSettings and not available in ConnectivityManager. Permissions
3082 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003083 */
3084 @Override
3085 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003086 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003087 int user = UserHandle.getUserId(Binder.getCallingUid());
3088 synchronized(mVpns) {
3089 return mVpns.get(user).getLegacyVpnInfo();
3090 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003091 }
3092
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003093 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003094 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3095 * and not available in ConnectivityManager.
3096 */
3097 @Override
3098 public VpnInfo[] getAllVpnInfo() {
3099 enforceConnectivityInternalPermission();
3100 if (mLockdownEnabled) {
3101 return new VpnInfo[0];
3102 }
3103
3104 synchronized(mVpns) {
3105 List<VpnInfo> infoList = new ArrayList<>();
3106 for (int i = 0; i < mVpns.size(); i++) {
3107 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3108 if (info != null) {
3109 infoList.add(info);
3110 }
3111 }
3112 return infoList.toArray(new VpnInfo[infoList.size()]);
3113 }
3114 }
3115
3116 /**
3117 * @return VPN information for accounting, or null if we can't retrieve all required
3118 * information, e.g primary underlying iface.
3119 */
3120 @Nullable
3121 private VpnInfo createVpnInfo(Vpn vpn) {
3122 VpnInfo info = vpn.getVpnInfo();
3123 if (info == null) {
3124 return null;
3125 }
3126 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3127 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3128 // the underlyingNetworks list.
3129 if (underlyingNetworks == null) {
3130 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3131 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3132 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3133 }
3134 } else if (underlyingNetworks.length > 0) {
3135 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3136 if (linkProperties != null) {
3137 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3138 }
3139 }
3140 return info.primaryUnderlyingIface == null ? null : info;
3141 }
3142
3143 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003144 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3145 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003146 * Permissions are checked in Vpn class.
3147 * @hide
3148 */
3149 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003150 public VpnConfig getVpnConfig(int userId) {
3151 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003152 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003153 Vpn vpn = mVpns.get(userId);
3154 if (vpn != null) {
3155 return vpn.getVpnConfig();
3156 } else {
3157 return null;
3158 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003159 }
3160 }
3161
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003162 @Override
3163 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003164 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3165 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3166 return false;
3167 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003168
3169 // Tear down existing lockdown if profile was removed
3170 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3171 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003172 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003173 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3174 return false;
3175 }
3176
3177 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3178 final VpnProfile profile = VpnProfile.decode(
3179 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003180 int user = UserHandle.getUserId(Binder.getCallingUid());
3181 synchronized(mVpns) {
3182 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3183 profile));
3184 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003185 } else {
3186 setLockdownTracker(null);
3187 }
3188
3189 return true;
3190 }
3191
3192 /**
3193 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3194 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3195 */
3196 private void setLockdownTracker(LockdownVpnTracker tracker) {
3197 // Shutdown any existing tracker
3198 final LockdownVpnTracker existing = mLockdownTracker;
3199 mLockdownTracker = null;
3200 if (existing != null) {
3201 existing.shutdown();
3202 }
3203
3204 try {
3205 if (tracker != null) {
3206 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003207 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003208 mLockdownTracker = tracker;
3209 mLockdownTracker.init();
3210 } else {
3211 mNetd.setFirewallEnabled(false);
3212 }
3213 } catch (RemoteException e) {
3214 // ignored; NMS lives inside system_server
3215 }
3216 }
3217
3218 private void throwIfLockdownEnabled() {
3219 if (mLockdownEnabled) {
3220 throw new IllegalStateException("Unavailable in lockdown mode");
3221 }
3222 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003223
Wink Savilleab9321d2013-06-29 21:10:57 -07003224 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003225 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003226 // TODO: Remove? Any reason to trigger a provisioning check?
3227 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003228 }
3229
3230 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003231 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003232
Paul Jensen89e0f092014-09-15 15:59:36 -04003233 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003234 if (DBG) {
3235 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003236 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003237 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003238 Intent intent = new Intent(action);
3239 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003240 // Concatenate the range of types onto the range of NetIDs.
3241 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003242 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003243 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003244 }
3245
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003246 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003247 * Show or hide network provisioning notifications.
3248 *
3249 * We use notifications for two purposes: to notify that a network requires sign in
3250 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3251 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3252 * particular network we can display the notification type that was most recently requested.
3253 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3254 * might first display NO_INTERNET, and then when the captive portal check completes, display
3255 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003256 *
3257 * @param id an identifier that uniquely identifies this notification. This must match
3258 * between show and hide calls. We use the NetID value but for legacy callers
3259 * we concatenate the range of types with the range of NetIDs.
3260 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003261 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003262 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3263 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003264 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003265 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3266 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003267 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003268 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003269
3270 Resources r = Resources.getSystem();
3271 NotificationManager notificationManager = (NotificationManager) mContext
3272 .getSystemService(Context.NOTIFICATION_SERVICE);
3273
3274 if (visible) {
3275 CharSequence title;
3276 CharSequence details;
3277 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003278 if (notifyType == NotificationType.NO_INTERNET &&
3279 networkType == ConnectivityManager.TYPE_WIFI) {
3280 title = r.getString(R.string.wifi_no_internet, 0);
3281 details = r.getString(R.string.wifi_no_internet_detailed);
3282 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3283 } else if (notifyType == NotificationType.SIGN_IN) {
3284 switch (networkType) {
3285 case ConnectivityManager.TYPE_WIFI:
3286 title = r.getString(R.string.wifi_available_sign_in, 0);
3287 details = r.getString(R.string.network_available_sign_in_detailed,
3288 extraInfo);
3289 icon = R.drawable.stat_notify_wifi_in_range;
3290 break;
3291 case ConnectivityManager.TYPE_MOBILE:
3292 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3293 title = r.getString(R.string.network_available_sign_in, 0);
3294 // TODO: Change this to pull from NetworkInfo once a printable
3295 // name has been added to it
3296 details = mTelephonyManager.getNetworkOperatorName();
3297 icon = R.drawable.stat_notify_rssi_in_range;
3298 break;
3299 default:
3300 title = r.getString(R.string.network_available_sign_in, 0);
3301 details = r.getString(R.string.network_available_sign_in_detailed,
3302 extraInfo);
3303 icon = R.drawable.stat_notify_rssi_in_range;
3304 break;
3305 }
3306 } else {
3307 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3308 + getNetworkTypeName(networkType));
3309 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003310 }
3311
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003312 Notification notification = new Notification.Builder(mContext)
3313 .setWhen(0)
3314 .setSmallIcon(icon)
3315 .setAutoCancel(true)
3316 .setTicker(title)
3317 .setColor(mContext.getColor(
3318 com.android.internal.R.color.system_notification_accent_color))
3319 .setContentTitle(title)
3320 .setContentText(details)
3321 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003322 .setLocalOnly(true)
3323 .setPriority(highPriority ?
3324 Notification.PRIORITY_HIGH :
3325 Notification.PRIORITY_DEFAULT)
3326 .setDefaults(Notification.DEFAULT_ALL)
3327 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003328 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003329
Wink Saville948282b2013-08-29 08:55:16 -07003330 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003331 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003332 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003333 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003334 npe.printStackTrace();
3335 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003336 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003337 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003338 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003339 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003340 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003341 npe.printStackTrace();
3342 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003343 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003344 }
3345
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003346 /** Location to an updatable file listing carrier provisioning urls.
3347 * An example:
3348 *
3349 * <?xml version="1.0" encoding="utf-8"?>
3350 * <provisioningUrls>
3351 * <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 -07003352 * </provisioningUrls>
3353 */
3354 private static final String PROVISIONING_URL_PATH =
3355 "/data/misc/radio/provisioning_urls.xml";
3356 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003357
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003358 /** XML tag for root element. */
3359 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3360 /** XML tag for individual url */
3361 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003362 /** XML attribute for mcc */
3363 private static final String ATTR_MCC = "mcc";
3364 /** XML attribute for mnc */
3365 private static final String ATTR_MNC = "mnc";
3366
Paul Jensen434dde82015-06-11 09:43:30 -04003367 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003368 FileReader fileReader = null;
3369 XmlPullParser parser = null;
3370 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003371
3372 try {
3373 fileReader = new FileReader(mProvisioningUrlFile);
3374 parser = Xml.newPullParser();
3375 parser.setInput(fileReader);
3376 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3377
3378 while (true) {
3379 XmlUtils.nextElement(parser);
3380
3381 String element = parser.getName();
3382 if (element == null) break;
3383
Paul Jensen434dde82015-06-11 09:43:30 -04003384 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003385 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3386 try {
3387 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3388 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3389 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3390 parser.next();
3391 if (parser.getEventType() == XmlPullParser.TEXT) {
3392 return parser.getText();
3393 }
3394 }
3395 }
3396 } catch (NumberFormatException e) {
3397 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3398 }
3399 }
3400 }
3401 return null;
3402 } catch (FileNotFoundException e) {
3403 loge("Carrier Provisioning Urls file not found");
3404 } catch (XmlPullParserException e) {
3405 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3406 } catch (IOException e) {
3407 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3408 } finally {
3409 if (fileReader != null) {
3410 try {
3411 fileReader.close();
3412 } catch (IOException e) {}
3413 }
3414 }
3415 return null;
3416 }
3417
Wink Saville42d4f082013-07-20 20:31:59 -07003418 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003419 public String getMobileProvisioningUrl() {
3420 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003421 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003422 if (TextUtils.isEmpty(url)) {
3423 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003424 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003425 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003426 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003427 }
Wink Saville8cf35602013-07-10 23:00:07 -07003428 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003429 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003430 String phoneNumber = mTelephonyManager.getLine1Number();
3431 if (TextUtils.isEmpty(phoneNumber)) {
3432 phoneNumber = "0000000000";
3433 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003434 url = String.format(url,
3435 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3436 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003437 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003438 }
3439
Wink Savilleab9321d2013-06-29 21:10:57 -07003440 return url;
3441 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003442
Wink Saville948282b2013-08-29 08:55:16 -07003443 @Override
3444 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003445 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003446 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003447 final long ident = Binder.clearCallingIdentity();
3448 try {
3449 setProvNotificationVisible(visible, networkType, action);
3450 } finally {
3451 Binder.restoreCallingIdentity(ident);
3452 }
Wink Saville948282b2013-08-29 08:55:16 -07003453 }
Wink Saville7788c612013-08-29 14:57:08 -07003454
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003455 @Override
3456 public void setAirplaneMode(boolean enable) {
3457 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003458 final long ident = Binder.clearCallingIdentity();
3459 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003460 final ContentResolver cr = mContext.getContentResolver();
3461 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3462 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3463 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003464 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003465 } finally {
3466 Binder.restoreCallingIdentity(ident);
3467 }
3468 }
3469
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003470 private void onUserStart(int userId) {
3471 synchronized(mVpns) {
3472 Vpn userVpn = mVpns.get(userId);
3473 if (userVpn != null) {
3474 loge("Starting user already has a VPN");
3475 return;
3476 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003477 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003478 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003479 }
3480 }
3481
3482 private void onUserStop(int userId) {
3483 synchronized(mVpns) {
3484 Vpn userVpn = mVpns.get(userId);
3485 if (userVpn == null) {
3486 loge("Stopping user has no VPN");
3487 return;
3488 }
3489 mVpns.delete(userId);
3490 }
3491 }
3492
3493 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3494 @Override
3495 public void onReceive(Context context, Intent intent) {
3496 final String action = intent.getAction();
3497 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3498 if (userId == UserHandle.USER_NULL) return;
3499
3500 if (Intent.ACTION_USER_STARTING.equals(action)) {
3501 onUserStart(userId);
3502 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3503 onUserStop(userId);
3504 }
3505 }
3506 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003507
Robert Greenwalta67be032014-05-16 15:49:14 -07003508 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3509 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003510 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3511 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003512
Robert Greenwalta67be032014-05-16 15:49:14 -07003513 private static class NetworkFactoryInfo {
3514 public final String name;
3515 public final Messenger messenger;
3516 public final AsyncChannel asyncChannel;
3517
3518 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3519 this.name = name;
3520 this.messenger = messenger;
3521 this.asyncChannel = asyncChannel;
3522 }
3523 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003524
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003525 /**
3526 * Tracks info about the requester.
3527 * Also used to notice when the calling process dies so we can self-expire
3528 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003529 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3530 static final boolean REQUEST = true;
3531 static final boolean LISTEN = false;
3532
3533 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003534 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003535 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003536 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003537 final int mPid;
3538 final int mUid;
3539 final Messenger messenger;
3540 final boolean isRequest;
3541
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003542 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3543 request = r;
3544 mPendingIntent = pi;
3545 messenger = null;
3546 mBinder = null;
3547 mPid = getCallingPid();
3548 mUid = getCallingUid();
3549 this.isRequest = isRequest;
3550 }
3551
Robert Greenwalt9258c642014-03-26 16:47:06 -07003552 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3553 super();
3554 messenger = m;
3555 request = r;
3556 mBinder = binder;
3557 mPid = getCallingPid();
3558 mUid = getCallingUid();
3559 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003560 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003561
3562 try {
3563 mBinder.linkToDeath(this, 0);
3564 } catch (RemoteException e) {
3565 binderDied();
3566 }
3567 }
3568
3569 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003570 if (mBinder != null) {
3571 mBinder.unlinkToDeath(this, 0);
3572 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003573 }
3574
3575 public void binderDied() {
3576 log("ConnectivityService NetworkRequestInfo binderDied(" +
3577 request + ", " + mBinder + ")");
3578 releaseNetworkRequest(request);
3579 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003580
3581 public String toString() {
3582 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003583 mPid + " for " + request +
3584 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003585 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003586 }
3587
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003588 private void ensureImmutableCapabilities(NetworkCapabilities networkCapabilities) {
3589 if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
3590 throw new IllegalArgumentException(
3591 "Cannot request network with NET_CAPABILITY_VALIDATED");
3592 }
3593 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
3594 throw new IllegalArgumentException(
3595 "Cannot request network with NET_CAPABILITY_CAPTIVE_PORTAL");
3596 }
3597 }
3598
Robert Greenwalt9258c642014-03-26 16:47:06 -07003599 @Override
3600 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003601 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003602 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003603 enforceNetworkRequestPermissions(networkCapabilities);
3604 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003605 ensureImmutableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003606
Robert Greenwalt6078b502014-06-11 16:05:07 -07003607 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003608 throw new IllegalArgumentException("Bad timeout specified");
3609 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003610
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003611 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3612 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003613 if (DBG) log("requestNetwork for " + networkRequest);
3614 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3615 NetworkRequestInfo.REQUEST);
3616
3617 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003618 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003619 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003620 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003621 }
3622 return networkRequest;
3623 }
3624
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003625 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003626 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003627 enforceConnectivityInternalPermission();
3628 } else {
3629 enforceChangePermission();
3630 }
3631 }
3632
fenglub15e72b2015-03-20 11:29:56 -07003633 @Override
fengludb571472015-04-21 17:12:05 -07003634 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003635 enforceAccessPermission();
3636 NetworkAgentInfo nai = null;
3637 if (network == null) {
3638 return false;
3639 }
3640 synchronized (mNetworkForNetId) {
3641 nai = mNetworkForNetId.get(network.netId);
3642 }
3643 if (nai != null) {
3644 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3645 return true;
3646 }
3647 return false;
3648 }
3649
3650
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003651 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3652 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003653 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003654 final int uidRules;
3655 final int uid = Binder.getCallingUid();
3656 synchronized(mRulesLock) {
3657 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3658 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003659 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003660 // we could silently fail or we can filter the available nets to only give
3661 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003662 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003663 }
3664 }
3665 }
3666
Robert Greenwalt9258c642014-03-26 16:47:06 -07003667 @Override
3668 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3669 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003670 checkNotNull(operation, "PendingIntent cannot be null.");
3671 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3672 enforceNetworkRequestPermissions(networkCapabilities);
3673 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003674 ensureImmutableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003675
3676 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3677 nextNetworkRequestId());
3678 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3679 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3680 NetworkRequestInfo.REQUEST);
3681 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3682 nri));
3683 return networkRequest;
3684 }
3685
Jeremy Joslin79294842014-12-03 17:15:28 -08003686 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3687 mHandler.sendMessageDelayed(
3688 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3689 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3690 }
3691
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003692 @Override
3693 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003694 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003695 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3696 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003697 }
3698
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003699 // In order to implement the compatibility measure for pre-M apps that call
3700 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3701 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3702 // This ensures it has permission to do so.
3703 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3704 if (nc == null) {
3705 return false;
3706 }
3707 int[] transportTypes = nc.getTransportTypes();
3708 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3709 return false;
3710 }
3711 try {
3712 mContext.enforceCallingOrSelfPermission(
3713 android.Manifest.permission.ACCESS_WIFI_STATE,
3714 "ConnectivityService");
3715 } catch (SecurityException e) {
3716 return false;
3717 }
3718 return true;
3719 }
3720
Robert Greenwalt9258c642014-03-26 16:47:06 -07003721 @Override
3722 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3723 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003724 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3725 enforceAccessPermission();
3726 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003727
3728 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003729 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003730 if (DBG) log("listenForNetwork for " + networkRequest);
3731 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3732 NetworkRequestInfo.LISTEN);
3733
3734 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3735 return networkRequest;
3736 }
3737
3738 @Override
3739 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3740 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003741 checkNotNull(operation, "PendingIntent cannot be null.");
3742 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3743 enforceAccessPermission();
3744 }
3745
3746 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3747 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3748 if (DBG) log("pendingListenForNetwork for " + networkRequest + " to trigger " + operation);
3749 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3750 NetworkRequestInfo.LISTEN);
3751
3752 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003753 }
3754
3755 @Override
3756 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003757 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3758 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003759 }
3760
3761 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003762 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003763 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003764 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3765 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003766 }
3767
Robert Greenwalta67be032014-05-16 15:49:14 -07003768 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003769 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003770 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3771 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3772 }
3773
3774 @Override
3775 public void unregisterNetworkFactory(Messenger messenger) {
3776 enforceConnectivityInternalPermission();
3777 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3778 }
3779
3780 private void handleUnregisterNetworkFactory(Messenger messenger) {
3781 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3782 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003783 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003784 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003785 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003786 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003787 }
3788
Robert Greenwalt7b816022014-04-18 15:25:25 -07003789 /**
3790 * NetworkAgentInfo supporting a request by requestId.
3791 * These have already been vetted (their Capabilities satisfy the request)
3792 * and the are the highest scored network available.
3793 * the are keyed off the Requests requestId.
3794 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003795 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003796 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3797 new SparseArray<NetworkAgentInfo>();
3798
Paul Jensen31a94f42015-02-13 14:18:39 -05003799 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3800 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003801 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3802 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003803 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3804 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3805 // there may not be a strict 1:1 correlation between the two.
3806 @GuardedBy("mNetworkForNetId")
3807 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003808
Robert Greenwalt7b816022014-04-18 15:25:25 -07003809 // NetworkAgentInfo keyed off its connecting messenger
3810 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003811 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003812 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3813 new HashMap<Messenger, NetworkAgentInfo>();
3814
Paul Jensen2c311d62014-11-17 12:34:51 -05003815 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003816 private final NetworkRequest mDefaultRequest;
3817
Erik Klineda4bfa82015-04-30 12:58:40 +09003818 // Request used to optionally keep mobile data active even when higher
3819 // priority networks like Wi-Fi are active.
3820 private final NetworkRequest mDefaultMobileDataRequest;
3821
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003822 private NetworkAgentInfo getDefaultNetwork() {
3823 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3824 }
3825
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003826 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003827 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003828 }
3829
Paul Jensen31a94f42015-02-13 14:18:39 -05003830 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003831 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003832 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003833 enforceConnectivityInternalPermission();
3834
Paul Jensen2c311d62014-11-17 12:34:51 -05003835 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3836 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003837 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003838 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3839 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3840 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003841 synchronized (this) {
3842 nai.networkMonitor.systemReady = mSystemReady;
3843 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003844 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003845 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003846 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003847 }
3848
3849 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3850 if (VDBG) log("Got NetworkAgent Messenger");
3851 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003852 synchronized (mNetworkForNetId) {
3853 mNetworkForNetId.put(na.network.netId, na);
3854 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003855 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3856 NetworkInfo networkInfo = na.networkInfo;
3857 na.networkInfo = null;
3858 updateNetworkInfo(na, networkInfo);
3859 }
3860
3861 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3862 LinkProperties newLp = networkAgent.linkProperties;
3863 int netId = networkAgent.network.netId;
3864
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003865 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3866 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003867 if (networkAgent.clatd != null) {
3868 networkAgent.clatd.fixupLinkProperties(oldLp);
3869 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003870
Paul Jensen992f2522014-04-28 10:33:11 -04003871 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003872 updateMtu(newLp, oldLp);
3873 // TODO - figure out what to do for clat
3874// for (LinkProperties lp : newLp.getStackedLinks()) {
3875// updateMtu(lp, null);
3876// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003877 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003878
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003879 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3880 // In L, we used it only when the network had Internet access but provided no DNS servers.
3881 // For now, just disable it, and if disabling it doesn't break things, remove it.
3882 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3883 // NET_CAPABILITY_INTERNET);
3884 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003885 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003886 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3887
Paul Jensen3b759822014-05-13 11:44:01 -04003888 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003889 if (isDefaultNetwork(networkAgent)) {
3890 handleApplyDefaultProxy(newLp.getHttpProxy());
3891 } else {
3892 updateProxy(newLp, oldLp, networkAgent);
3893 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003894 // TODO - move this check to cover the whole function
3895 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003896 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003897 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3898 }
Paul Jensen3b759822014-05-13 11:44:01 -04003899 }
3900
Lorenzo Colitti95439462014-10-09 13:44:48 +09003901 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3902 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3903 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003904
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003905 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003906 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3907 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003908 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003909 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003910 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003911 }
Paul Jensen992f2522014-04-28 10:33:11 -04003912
3913 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3914 CompareResult<String> interfaceDiff = new CompareResult<String>();
3915 if (oldLp != null) {
3916 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3917 } else if (newLp != null) {
3918 interfaceDiff.added = newLp.getAllInterfaceNames();
3919 }
3920 for (String iface : interfaceDiff.added) {
3921 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003922 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003923 mNetd.addInterfaceToNetwork(iface, netId);
3924 } catch (Exception e) {
3925 loge("Exception adding interface: " + e);
3926 }
3927 }
3928 for (String iface : interfaceDiff.removed) {
3929 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003930 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003931 mNetd.removeInterfaceFromNetwork(iface, netId);
3932 } catch (Exception e) {
3933 loge("Exception removing interface: " + e);
3934 }
3935 }
3936 }
3937
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003938 /**
3939 * Have netd update routes from oldLp to newLp.
3940 * @return true if routes changed between oldLp and newLp
3941 */
3942 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003943 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3944 if (oldLp != null) {
3945 routeDiff = oldLp.compareAllRoutes(newLp);
3946 } else if (newLp != null) {
3947 routeDiff.added = newLp.getAllRoutes();
3948 }
3949
3950 // add routes before removing old in case it helps with continuous connectivity
3951
3952 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3953 for (RouteInfo route : routeDiff.added) {
3954 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003955 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003956 try {
3957 mNetd.addRoute(netId, route);
3958 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003959 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3960 loge("Exception in addRoute for non-gateway: " + e);
3961 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003962 }
3963 }
3964 for (RouteInfo route : routeDiff.added) {
3965 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003966 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003967 try {
3968 mNetd.addRoute(netId, route);
3969 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003970 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3971 loge("Exception in addRoute for gateway: " + e);
3972 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003973 }
3974 }
3975
3976 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003977 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003978 try {
3979 mNetd.removeRoute(netId, route);
3980 } catch (Exception e) {
3981 loge("Exception in removeRoute: " + e);
3982 }
3983 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003984 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003985 }
Erik Kline41368502015-06-17 13:19:54 +09003986
3987 // TODO: investigate moving this into LinkProperties, if only to make more accurate
3988 // the isProvisioned() checks.
3989 private static Collection<InetAddress> getLikelyReachableDnsServers(LinkProperties lp) {
3990 final ArrayList<InetAddress> dnsServers = new ArrayList<InetAddress>();
3991 final List<RouteInfo> allRoutes = lp.getAllRoutes();
3992 for (InetAddress nameserver : lp.getDnsServers()) {
3993 // If the LinkProperties doesn't include a route to the nameserver, ignore it.
3994 final RouteInfo bestRoute = RouteInfo.selectBestRoute(allRoutes, nameserver);
3995 if (bestRoute == null) {
3996 continue;
3997 }
3998
3999 // TODO: better source address evaluation for destination addresses.
4000 if (nameserver instanceof Inet4Address) {
4001 if (!lp.hasIPv4Address()) {
4002 continue;
4003 }
4004 } else if (nameserver instanceof Inet6Address) {
4005 if (nameserver.isLinkLocalAddress()) {
4006 if (((Inet6Address)nameserver).getScopeId() == 0) {
4007 // For now, just make sure link-local DNS servers have
4008 // scopedIds set, since DNS lookups will fail otherwise.
4009 // TODO: verify the scopeId matches that of lp's interface.
4010 continue;
4011 }
4012 } else {
4013 if (bestRoute.isIPv6Default() && !lp.hasGlobalIPv6Address()) {
4014 // TODO: reconsider all corner cases (disconnected ULA networks, ...).
4015 continue;
4016 }
4017 }
4018 }
4019
4020 dnsServers.add(nameserver);
4021 }
4022 return Collections.unmodifiableList(dnsServers);
4023 }
4024
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004025 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4026 boolean flush, boolean useDefaultDns) {
Erik Kline41368502015-06-17 13:19:54 +09004027 // TODO: consider comparing the getLikelyReachableDnsServers() lists, in case the
4028 // route to a DNS server has been removed (only really applicable in special cases
4029 // where there is no default route).
Robert Greenwalt7b816022014-04-18 15:25:25 -07004030 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Kline41368502015-06-17 13:19:54 +09004031 Collection<InetAddress> dnses = getLikelyReachableDnsServers(newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004032 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004033 dnses = new ArrayList();
4034 dnses.add(mDefaultDns);
4035 if (DBG) {
4036 loge("no dns provided for netId " + netId + ", so using defaults");
4037 }
4038 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004039 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004040 try {
4041 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4042 newLp.getDomains());
4043 } catch (Exception e) {
4044 loge("Exception in setDnsServersForNetwork: " + e);
4045 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004046 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
4047 if (defaultNai != null && defaultNai.network.netId == netId) {
4048 setDefaultDnsSystemProperties(dnses);
4049 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004050 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004051 } else if (flush) {
4052 try {
4053 mNetd.flushNetworkDnsCache(netId);
4054 } catch (Exception e) {
4055 loge("Exception in flushNetworkDnsCache: " + e);
4056 }
4057 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004058 }
4059 }
4060
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004061 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4062 int last = 0;
4063 for (InetAddress dns : dnses) {
4064 ++last;
4065 String key = "net.dns" + last;
4066 String value = dns.getHostAddress();
4067 SystemProperties.set(key, value);
4068 }
4069 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4070 String key = "net.dns" + i;
4071 SystemProperties.set(key, "");
4072 }
4073 mNumDnsEntries = last;
4074 }
4075
Paul Jensen3d194ea2015-06-16 14:27:36 -04004076 /**
4077 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4078 * augmented with any stateful capabilities implied from {@code networkAgent}
4079 * (e.g., validated status and captive portal status).
4080 *
4081 * @param networkAgent the network having its capabilities updated.
4082 * @param networkCapabilities the new network capabilities.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004083 * @param nascent indicates whether {@code networkAgent} was validated
4084 * (i.e. had everValidated set for the first time) immediately prior to this call.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004085 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07004086 private void updateCapabilities(NetworkAgentInfo networkAgent,
Paul Jensen1c7ba022015-06-16 14:27:36 -04004087 NetworkCapabilities networkCapabilities, NascentState nascent) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004088 // Don't modify caller's NetworkCapabilities.
4089 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4090 if (networkAgent.lastValidated) {
4091 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4092 } else {
4093 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4094 }
4095 if (networkAgent.lastCaptivePortalDetected) {
4096 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4097 } else {
4098 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4099 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004100 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
4101 synchronized (networkAgent) {
4102 networkAgent.networkCapabilities = networkCapabilities;
4103 }
Paul Jensen1c7ba022015-06-16 14:27:36 -04004104 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore(), nascent);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004105 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004106 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004107 }
4108
Paul Jensenc8b9a742014-09-30 15:37:41 -04004109 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4110 for (int i = 0; i < nai.networkRequests.size(); i++) {
4111 NetworkRequest nr = nai.networkRequests.valueAt(i);
4112 // Don't send listening requests to factories. b/17393458
4113 if (!isRequest(nr)) continue;
4114 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4115 }
4116 }
4117
Robert Greenwalt7b816022014-04-18 15:25:25 -07004118 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4119 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004120 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004121 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4122 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004123 }
4124 }
4125
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004126 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4127 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004128 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004129 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004130 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4131 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004132 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004133 sendIntent(nri.mPendingIntent, intent);
4134 }
4135 // else not handled
4136 }
4137
4138 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4139 mPendingIntentWakeLock.acquire();
4140 try {
4141 if (DBG) log("Sending " + pendingIntent);
4142 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4143 } catch (PendingIntent.CanceledException e) {
4144 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4145 mPendingIntentWakeLock.release();
4146 releasePendingNetworkRequest(pendingIntent);
4147 }
4148 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4149 }
4150
4151 @Override
4152 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4153 String resultData, Bundle resultExtras) {
4154 if (DBG) log("Finished sending " + pendingIntent);
4155 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004156 // Release with a delay so the receiving client has an opportunity to put in its
4157 // own request.
4158 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004159 }
4160
Robert Greenwalt9258c642014-03-26 16:47:06 -07004161 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004162 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004163 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004164 Bundle bundle = new Bundle();
4165 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4166 new NetworkRequest(nri.request));
4167 Message msg = Message.obtain();
4168 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4169 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4170 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4171 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004172 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004173 case ConnectivityManager.CALLBACK_LOSING: {
4174 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4175 break;
4176 }
4177 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4178 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4179 new NetworkCapabilities(networkAgent.networkCapabilities));
4180 break;
4181 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004182 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004183 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4184 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004185 break;
4186 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004187 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004188 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004189 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004190 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004191 if (VDBG) {
4192 log("sending notification " + notifyTypeToName(notificationType) +
4193 " for " + nri.request);
4194 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004195 nri.messenger.send(msg);
4196 } catch (RemoteException e) {
4197 // may occur naturally in the race of binder death.
4198 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4199 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004200 }
4201
Paul Jensenc8b9a742014-09-30 15:37:41 -04004202 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4203 for (int i = 0; i < nai.networkRequests.size(); i++) {
4204 NetworkRequest nr = nai.networkRequests.valueAt(i);
4205 // Ignore listening requests.
4206 if (!isRequest(nr)) continue;
4207 loge("Dead network still had at least " + nr);
4208 break;
4209 }
4210 nai.asyncChannel.disconnect();
4211 }
4212
Robert Greenwalt7b816022014-04-18 15:25:25 -07004213 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4214 if (oldNetwork == null) {
4215 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4216 return;
4217 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004218 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4219 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004220 }
4221
Paul Jensen27b02b72014-07-14 12:03:33 -04004222 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004223 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004224 setupDataActivityTracking(newNetwork);
4225 try {
4226 mNetd.setDefaultNetId(newNetwork.network.netId);
4227 } catch (Exception e) {
4228 loge("Exception setting default network :" + e);
4229 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004230 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004231 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004232 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004233 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004234 }
4235
Paul Jensen2161a8e2014-09-11 11:00:39 -04004236 // Handles a network appearing or improving its score.
4237 //
4238 // - Evaluates all current NetworkRequests that can be
4239 // satisfied by newNetwork, and reassigns to newNetwork
4240 // any such requests for which newNetwork is the best.
4241 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004242 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004243 // needed. A network is needed if it is the best network for
4244 // one or more NetworkRequests, or if it is a VPN.
4245 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004246 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004247 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4248 //
4249 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4250 // networks that have no chance (i.e. even if validated)
4251 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004252 //
4253 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4254 // it does not remove NetworkRequests that other Networks could better satisfy.
4255 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4256 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4257 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004258 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004259 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004260 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004261 // torn down if unneeded.
4262 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4263 // performed to tear down unvalidated networks that have no chance (i.e. even if
4264 // validated) of becoming the highest scoring network.
4265 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4266 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004267 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004268 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004269 loge("ERROR: nascent network not validated.");
4270 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004271 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004272 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004273 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004274 if (DBG) log("rematching " + newNetwork.name());
4275 // Find and migrate to this Network any NetworkRequests for
4276 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004277 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004278 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004279 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004280 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004281 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4282 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004283 if (DBG) {
4284 log("Network " + newNetwork.name() + " was already satisfying" +
4285 " request " + nri.request.requestId + ". No change.");
4286 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004287 keep = true;
4288 continue;
4289 }
4290
4291 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004292 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004293 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004294 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004295 // This is not a request, it's a callback listener.
4296 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004297 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004298 continue;
4299 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004300
Robert Greenwalt7b816022014-04-18 15:25:25 -07004301 // next check if it's better than any current network we're using for
4302 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004303 if (VDBG) {
4304 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004305 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4306 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004307 }
4308 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004309 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004310 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004311 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004312 currentNetwork.networkRequests.remove(nri.request.requestId);
4313 currentNetwork.networkLingered.add(nri.request);
4314 affectedNetworks.add(currentNetwork);
4315 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004316 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004317 }
Paul Jensen573a0352015-01-08 10:49:34 -05004318 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004319 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004320 if (!newNetwork.addRequest(nri.request)) {
4321 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4322 }
4323 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004324 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004325 // Tell NetworkFactories about the new score, so they can stop
4326 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004327 // TODO - this could get expensive if we have alot of requests for this
4328 // network. Think about if there is a way to reduce this. Push
4329 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004330 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004331 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004332 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004333 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004334 }
4335 }
4336 }
4337 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004338 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004339 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004340 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004341 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4342 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4343 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004344 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004345 }
4346 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004347 if (keep) {
4348 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004349 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004350 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004351 synchronized (ConnectivityService.this) {
4352 // have a new default network, release the transition wakelock in
4353 // a second if it's held. The second pause is to allow apps
4354 // to reconnect over the new network
4355 if (mNetTransitionWakeLock.isHeld()) {
4356 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4357 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4358 mNetTransitionWakeLockSerialNumber, 0),
4359 1000);
4360 }
4361 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004362 }
4363
4364 // do this after the default net is switched, but
4365 // before LegacyTypeTracker sends legacy broadcasts
Paul Jensen3d911462015-06-12 06:40:24 -04004366 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
Robert Greenwalt152ed372014-12-17 17:19:53 -08004367
4368 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004369 // Maintain the illusion: since the legacy API only
4370 // understands one network at a time, we must pretend
4371 // that the current default network disconnected before
4372 // the new one connected.
4373 if (oldDefaultNetwork != null) {
4374 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004375 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004376 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004377 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004378 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4379 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004380 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004381
4382 // Notify battery stats service about this network, both the normal
4383 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004384 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004385 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004386 final IBatteryStats bs = BatteryStatsService.getService();
4387 final int type = newNetwork.networkInfo.getType();
4388
4389 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4390 bs.noteNetworkInterfaceType(baseIface, type);
4391 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4392 final String stackedIface = stacked.getInterfaceName();
4393 bs.noteNetworkInterfaceType(stackedIface, type);
4394 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4395 }
4396 } catch (RemoteException ignored) {
4397 }
4398
Robert Greenwalt152ed372014-12-17 17:19:53 -08004399 // This has to happen after the notifyNetworkCallbacks as that tickles each
4400 // ConnectivityManager instance so that legacy requests correctly bind dns
4401 // requests to this network. The legacy users are listening for this bcast
4402 // and will generally do a dns request so they can ensureRouteToHost and if
4403 // they do that before the callbacks happen they'll use the default network.
4404 //
4405 // TODO: Is there still a race here? We send the broadcast
4406 // after sending the callback, but if the app can receive the
4407 // broadcast before the callback, it might still break.
4408 //
4409 // This *does* introduce a race where if the user uses the new api
4410 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4411 // they may get old info. Reverse this after the old startUsing api is removed.
4412 // This is on top of the multiple intent sequencing referenced in the todo above.
4413 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4414 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4415 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4416 // legacy type tracker filters out repeat adds
4417 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4418 }
4419 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004420
4421 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4422 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4423 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4424 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4425 if (newNetwork.isVPN()) {
4426 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4427 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004428 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004429 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004430 // validated (and get evaluated against peers, one losing here), or get reaped (see
4431 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4432 // network. Networks that have been up for a while and are validated should be torn
4433 // down via the lingering process so communication on that network is given time to
4434 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004435 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004436 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004437 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004438 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4439 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004440 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004441 if (DBG) log("Reaping " + nai.name());
4442 teardownUnneededNetwork(nai);
4443 }
4444 }
4445 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004446 }
4447
Paul Jensen1c7ba022015-06-16 14:27:36 -04004448 /**
4449 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4450 * being disconnected.
4451 * @param changed If only one Network's score or capabilities have been modified since the last
4452 * time this function was called, pass this Network in this argument, otherwise pass
4453 * null.
4454 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4455 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4456 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4457 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4458 * network's score.
4459 * @param nascent indicates if {@code changed} has just been validated.
4460 */
4461 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore,
4462 NascentState nascent) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004463 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4464 // to avoid the slowness. It is not simply enough to process just "changed", for
4465 // example in the case where "changed"'s score decreases and another network should begin
4466 // satifying a NetworkRequest that "changed" currently satisfies.
4467
4468 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4469 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4470 // rematchNetworkAndRequests() handles.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004471 if (changed != null &&
4472 (oldScore < changed.getCurrentScore() || nascent == NascentState.JUST_VALIDATED)) {
4473 rematchNetworkAndRequests(changed, nascent, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004474 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004475 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4476 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4477 NascentState.NOT_JUST_VALIDATED,
4478 // Only reap the last time through the loop. Reaping before all rematching
4479 // is complete could incorrectly teardown a network that hasn't yet been
4480 // rematched.
4481 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4482 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004483 }
4484 }
4485 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004486
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004487 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004488 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004489 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004490 // For now only update icons for default connection.
4491 // TODO: Update WiFi and cellular icons separately. b/17237507
4492 if (!isDefaultNetwork(nai)) return;
4493
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004494 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004495 // Don't repeat publish.
4496 if (newInetCondition == mDefaultInetConditionPublished) return;
4497
4498 mDefaultInetConditionPublished = newInetCondition;
4499 sendInetConditionBroadcast(nai.networkInfo);
4500 }
4501
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004502 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4503 if (mLockdownTracker != null) {
4504 if (nai != null && nai.isVPN()) {
4505 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4506 } else {
4507 mLockdownTracker.onNetworkInfoChanged();
4508 }
4509 }
4510 }
4511
Robert Greenwalt7b816022014-04-18 15:25:25 -07004512 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4513 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004514 NetworkInfo oldInfo = null;
4515 synchronized (networkAgent) {
4516 oldInfo = networkAgent.networkInfo;
4517 networkAgent.networkInfo = newInfo;
4518 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004519 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004520
4521 if (oldInfo != null && oldInfo.getState() == state) {
4522 if (VDBG) log("ignoring duplicate network state non-change");
4523 return;
4524 }
4525 if (DBG) {
4526 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4527 (oldInfo == null ? "null" : oldInfo.getState()) +
4528 " to " + state);
4529 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004530
Paul Jenseneec75412014-08-04 12:21:19 -04004531 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004533 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004534 if (networkAgent.isVPN()) {
4535 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004536 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4537 (networkAgent.networkMisc == null ||
4538 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004539 } else {
4540 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4541 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004542 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004543 loge("Error creating network " + networkAgent.network.netId + ": "
4544 + e.getMessage());
4545 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004546 }
Paul Jenseneec75412014-08-04 12:21:19 -04004547 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004548 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004549 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004550
Paul Jensenca8f16a2014-05-09 12:47:55 -04004551 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004552 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004553
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004554 if (networkAgent.isVPN()) {
4555 // Temporarily disable the default proxy (not global).
4556 synchronized (mProxyLock) {
4557 if (!mDefaultProxyDisabled) {
4558 mDefaultProxyDisabled = true;
4559 if (mGlobalProxy == null && mDefaultProxy != null) {
4560 sendProxyBroadcast(null);
4561 }
4562 }
4563 }
4564 // TODO: support proxy per network.
4565 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004566
Paul Jensen2161a8e2014-09-11 11:00:39 -04004567 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004568 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4569 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004570
4571 // This has to happen after matching the requests, because callbacks are just requests.
4572 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004573 } else if (state == NetworkInfo.State.DISCONNECTED ||
4574 state == NetworkInfo.State.SUSPENDED) {
4575 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004576 if (networkAgent.isVPN()) {
4577 synchronized (mProxyLock) {
4578 if (mDefaultProxyDisabled) {
4579 mDefaultProxyDisabled = false;
4580 if (mGlobalProxy == null && mDefaultProxy != null) {
4581 sendProxyBroadcast(mDefaultProxy);
4582 }
4583 }
4584 }
4585 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004586 }
4587 }
4588
Robert Greenwaltac96c522014-06-03 16:43:57 -07004589 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4590 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004591 if (score < 0) {
4592 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4593 "). Bumping score to min of 0");
4594 score = 0;
4595 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004596
Paul Jensen2161a8e2014-09-11 11:00:39 -04004597 final int oldScore = nai.getCurrentScore();
4598 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004599
Paul Jensen1c7ba022015-06-16 14:27:36 -04004600 rematchAllNetworksAndRequests(nai, oldScore, NascentState.NOT_JUST_VALIDATED);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004601
Paul Jensenc8b9a742014-09-30 15:37:41 -04004602 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004603 }
4604
Robert Greenwalt9258c642014-03-26 16:47:06 -07004605 // notify only this one new request of the current state
4606 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4607 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4608 // TODO - read state from monitor to decide what to send.
4609// if (nai.networkMonitor.isLingering()) {
4610// notifyType = NetworkCallbacks.LOSING;
4611// } else if (nai.networkMonitor.isEvaluating()) {
4612// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4613// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004614 if (nri.mPendingIntent == null) {
4615 callCallbackForRequest(nri, nai, notifyType);
4616 } else {
4617 sendPendingIntentForRequest(nri, nai, notifyType);
4618 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004619 }
4620
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004621 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004622 // The NetworkInfo we actually send out has no bearing on the real
4623 // state of affairs. For example, if the default connection is mobile,
4624 // and a request for HIPRI has just gone away, we need to pretend that
4625 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4626 // the state to DISCONNECTED, even though the network is of type MOBILE
4627 // and is still connected.
4628 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4629 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004630 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004631 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004632 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004633 } else {
Feixiong Zhang376133f2015-06-01 18:07:58 -07004634 info.setDetailedState(DetailedState.DISCONNECTED, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004635 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4636 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4637 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4638 if (info.isFailover()) {
4639 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4640 nai.networkInfo.setFailover(false);
4641 }
4642 if (info.getReason() != null) {
4643 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4644 }
4645 if (info.getExtraInfo() != null) {
4646 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4647 }
4648 NetworkAgentInfo newDefaultAgent = null;
4649 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4650 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4651 if (newDefaultAgent != null) {
4652 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4653 newDefaultAgent.networkInfo);
4654 } else {
4655 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4656 }
4657 }
4658 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4659 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004660 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004661 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004662 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004663 }
4664 }
4665 }
4666
Robert Greenwalt7b816022014-04-18 15:25:25 -07004667 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004668 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004669 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004670 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4671 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4672 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004673 if (nri.mPendingIntent == null) {
4674 callCallbackForRequest(nri, networkAgent, notifyType);
4675 } else {
4676 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4677 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004678 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004679 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004680
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004681 private String notifyTypeToName(int notifyType) {
4682 switch (notifyType) {
4683 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4684 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4685 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4686 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4687 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4688 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4689 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4690 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4691 }
4692 return "UNKNOWN";
4693 }
4694
Jeff Sharkey69736342014-12-08 14:50:12 -08004695 /**
4696 * Notify other system services that set of active ifaces has changed.
4697 */
4698 private void notifyIfacesChanged() {
4699 try {
4700 mStatsService.forceUpdateIfaces();
4701 } catch (Exception ignored) {
4702 }
4703 }
4704
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004705 @Override
4706 public boolean addVpnAddress(String address, int prefixLength) {
4707 throwIfLockdownEnabled();
4708 int user = UserHandle.getUserId(Binder.getCallingUid());
4709 synchronized (mVpns) {
4710 return mVpns.get(user).addAddress(address, prefixLength);
4711 }
4712 }
4713
4714 @Override
4715 public boolean removeVpnAddress(String address, int prefixLength) {
4716 throwIfLockdownEnabled();
4717 int user = UserHandle.getUserId(Binder.getCallingUid());
4718 synchronized (mVpns) {
4719 return mVpns.get(user).removeAddress(address, prefixLength);
4720 }
4721 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004722
4723 @Override
4724 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4725 throwIfLockdownEnabled();
4726 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004727 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004728 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004729 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004730 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004731 if (success) {
4732 notifyIfacesChanged();
4733 }
4734 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004735 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004736
4737 @Override
4738 public void factoryReset() {
4739 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004740
4741 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4742 return;
4743 }
4744
Robin Lee3b3dd942015-05-12 18:14:58 +01004745 final int userId = UserHandle.getCallingUserId();
4746
Stuart Scottf1fb3972015-04-02 18:00:02 -07004747 // Turn airplane mode off
4748 setAirplaneMode(false);
4749
Stuart Scotte3e314d2015-04-20 14:07:45 -07004750 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4751 // Untether
4752 for (String tether : getTetheredIfaces()) {
4753 untether(tether);
4754 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004755 }
4756
Stuart Scotte3e314d2015-04-20 14:07:45 -07004757 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4758 // Turn VPN off
4759 VpnConfig vpnConfig = getVpnConfig(userId);
4760 if (vpnConfig != null) {
4761 if (vpnConfig.legacy) {
4762 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4763 } else {
4764 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4765 // in the future without user intervention.
4766 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004767
Stuart Scotte3e314d2015-04-20 14:07:45 -07004768 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4769 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004770 }
4771 }
4772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004773}