blob: 8ca075f97d66c5974b88198e6ccdd927ece357b2 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070036import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
43import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070046import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090047import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
50import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070051import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070052import android.net.INetworkPolicyListener;
53import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070054import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080055import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070056import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070057import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070058import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070059import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070060import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070062import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070063import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070064import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070065import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070066import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070067import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070068import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040069import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070070import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040071import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040072import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070074import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040075import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070077import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070078import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070079import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Looper;
81import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070082import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070083import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070084import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070085import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070086import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070087import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070089import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040090import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070092import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070093import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070094import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070095import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070096import android.util.LocalLog;
97import android.util.LocalLog.ReadOnlyLocalLog;
98import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080099import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700100import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500101import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700102import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700103import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400106import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400107import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700108import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700109import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700110import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700111import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800112import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700113import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700114import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700115import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700116import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700117import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700118import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400119import com.android.server.connectivity.DataConnectionStats;
Erik Kline379747a2015-06-05 17:47:34 +0900120import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900121import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700122import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400123import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400124import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700125import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800126import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700127import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700128import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700129import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700130import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700131import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700132
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700133import org.xmlpull.v1.XmlPullParser;
134import org.xmlpull.v1.XmlPullParserException;
135
136import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700138import java.io.FileNotFoundException;
139import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700140import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700142import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700143import java.net.InetAddress;
144import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700145import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700146import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700147import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700148import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700149import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700150import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500151import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700152import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700153import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700154import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700155import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
157/**
158 * @hide
159 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800160public class ConnectivityService extends IConnectivityManager.Stub
161 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700162 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700164 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700165 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Jake Hamby786e71a2014-02-06 14:43:50 -0800167 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700168
Jeff Sharkey899223b2012-08-04 15:24:58 -0700169 // TODO: create better separation between radio types and network types
170
Robert Greenwalt42acef32009-08-12 16:08:25 -0700171 // how long to wait before switching back to a radio's default network
172 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
173 // system property that can override the above value
174 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
175 "android.telephony.apn-restore";
176
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900177 // How long to wait before putting up a "This network doesn't have an Internet connection,
178 // connect anyway?" dialog after the user selects a network that doesn't validate.
179 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
180
Jeremy Joslin79294842014-12-03 17:15:28 -0800181 // How long to delay to removal of a pending intent based request.
182 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
183 private final int mReleasePendingIntentDelayMs;
184
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800185 private Tethering mTethering;
186
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700187 private final PermissionMonitor mPermissionMonitor;
188
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700189 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700190
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700191 @GuardedBy("mVpns")
192 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700193
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700194 private boolean mLockdownEnabled;
195 private LockdownVpnTracker mLockdownTracker;
196
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700197 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
198 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700199 /** Currently active network rules by UID. */
200 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700201 /** Set of ifaces that are costly. */
202 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700203
Erik Klineda4bfa82015-04-30 12:58:40 +0900204 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700206 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700207 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800209 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
211 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700212 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700214 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800215 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700216 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700217
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700218 private String mCurrentTcpBufferSizes;
219
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700220 private static final int ENABLED = 1;
221 private static final int DISABLED = 0;
222
Paul Jensenb10e37f2014-11-25 12:33:08 -0500223 // Arguments to rematchNetworkAndRequests()
224 private enum NascentState {
225 // Indicates a network was just validated for the first time. If the network is found to
226 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
227 JUST_VALIDATED,
228 // Indicates a network was not validated for the first time immediately prior to this call.
229 NOT_JUST_VALIDATED
230 };
231 private enum ReapUnvalidatedNetworks {
232 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
233 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
234 // known that there may be unvalidated networks that could potentially be reaped, and when
235 // all networks have been rematched against all NetworkRequests.
236 REAP,
237 // Don't reap unvalidated networks. This should be passed when it's known that there are
238 // no unvalidated networks that could potentially be reaped, and when some networks have
239 // not yet been rematched against all NetworkRequests.
240 DONT_REAP
241 };
242
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700243 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700244 * used internally to change our mobile data enabled flag
245 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700246 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700247
248 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700249 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700250 * from one net to another. Clear happens when we get a new
251 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
252 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700253 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700254 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700255
Robert Greenwalt434203a2010-10-11 16:00:27 -0700256 /**
257 * used internally to reload global proxy settings
258 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700259 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700260
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700261 /**
Wink Saville628b0852011-08-04 15:01:58 -0700262 * used internally to send a sticky broadcast delayed.
263 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700264 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700265
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700266 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400267 * PAC manager has received new port.
268 */
269 private static final int EVENT_PROXY_HAS_CHANGED = 16;
270
Robert Greenwalte049c232014-04-11 15:53:27 -0700271 /**
272 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700273 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700274 */
275 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
276
Robert Greenwalt7b816022014-04-18 15:25:25 -0700277 /**
278 * used internally when registering NetworkAgents
279 * obj = Messenger
280 */
281 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
282
Robert Greenwalt9258c642014-03-26 16:47:06 -0700283 /**
284 * used to add a network request
285 * includes a NetworkRequestInfo
286 */
287 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
288
289 /**
290 * indicates a timeout period is over - check if we had a network yet or not
291 * and if not, call the timeout calback (but leave the request live until they
292 * cancel it.
293 * includes a NetworkRequestInfo
294 */
295 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
296
297 /**
298 * used to add a network listener - no request
299 * includes a NetworkRequestInfo
300 */
301 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
302
303 /**
304 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400305 * arg1 = UID of caller
306 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700307 */
308 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
309
Robert Greenwalta67be032014-05-16 15:49:14 -0700310 /**
311 * used internally when registering NetworkFactories
312 * obj = Messenger
313 */
314 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
315
Robert Greenwalt27711812014-06-25 16:45:57 -0700316 /**
317 * used internally to expire a wakelock when transitioning
318 * from one net to another. Expire happens when we fail to find
319 * a new network (typically after 1 minute) -
320 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
321 * a replacement network.
322 */
323 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
324
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700325 /**
326 * Used internally to indicate the system is ready.
327 */
328 private static final int EVENT_SYSTEM_READY = 25;
329
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800330 /**
331 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400332 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800333 */
334 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
335
336 /**
337 * used to remove a pending intent and its associated network request.
338 * arg1 = UID of caller
339 * obj = PendingIntent
340 */
341 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
342
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900343 /**
344 * used to specify whether a network should be used even if unvalidated.
345 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
346 * arg2 = whether to remember this choice in the future (1 or 0)
347 * obj = network
348 */
349 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
350
351 /**
352 * used to ask the user to confirm a connection to an unvalidated network.
353 * obj = network
354 */
355 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700356
Erik Klineda4bfa82015-04-30 12:58:40 +0900357 /**
358 * used internally to (re)configure mobile data always-on settings.
359 */
360 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
361
Paul Jensen694f2b82015-06-17 14:15:39 -0400362 /**
363 * used to add a network listener with a pending intent
364 * obj = NetworkRequestInfo
365 */
366 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
367
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700368 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700369 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700370 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700371 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700372
Mike Lockwood0f79b542009-08-14 14:18:49 -0400373 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800374 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400375
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700376 private PowerManager.WakeLock mNetTransitionWakeLock;
377 private String mNetTransitionWakeLockCausedBy = "";
378 private int mNetTransitionWakeLockSerialNumber;
379 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800380 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700381
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700382 private InetAddress mDefaultDns;
383
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700384 // used in DBG mode to track inet condition reports
385 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
386 private ArrayList mInetLog;
387
Robert Greenwalt434203a2010-10-11 16:00:27 -0700388 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400389 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700390 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700391 private boolean mDefaultProxyDisabled = false;
392
Robert Greenwalt434203a2010-10-11 16:00:27 -0700393 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400394 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700395
Jason Monk602b2322013-07-03 17:04:33 -0400396 private PacManager mPacManager = null;
397
Erik Klineda4bfa82015-04-30 12:58:40 +0900398 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700399
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400400 private UserManager mUserManager;
401
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700402 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700403 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700404
Robert Greenwalt50393202011-06-21 17:26:14 -0700405 // the set of network types that can only be enabled by system/sig apps
406 List mProtectedNetworks;
407
John Spurlockbf991a82013-06-24 14:20:23 -0400408 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700409
Wink Savilleab9321d2013-06-29 21:10:57 -0700410 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400411
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700412 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
413 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700414 private final static int MAX_NET_ID = 65535;
415 private int mNextNetId = MIN_NET_ID;
416
Robert Greenwalt34524f02014-05-18 16:22:10 -0700417 // sequence number of NetworkRequests
418 private int mNextNetworkRequestId = 1;
419
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700420 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
421 private static final int MAX_VALIDATION_LOGS = 10;
422 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
423 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
424
425 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
426 synchronized(mValidationLogs) {
427 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
428 mValidationLogs.removeLast();
429 }
430 mValidationLogs.addFirst(new Pair(network, log));
431 }
432 }
433
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700434 /**
435 * Implements support for the legacy "one network per network type" model.
436 *
437 * We used to have a static array of NetworkStateTrackers, one for each
438 * network type, but that doesn't work any more now that we can have,
439 * for example, more that one wifi network. This class stores all the
440 * NetworkAgentInfo objects that support a given type, but the legacy
441 * API will only see the first one.
442 *
443 * It serves two main purposes:
444 *
445 * 1. Provide information about "the network for a given type" (since this
446 * API only supports one).
447 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
448 * the first network for a given type changes, or if the default network
449 * changes.
450 */
451 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900452
453 private static final boolean DBG = true;
454 private static final boolean VDBG = false;
455 private static final String TAG = "CSLegacyTypeTracker";
456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 /**
458 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
459 * Each list holds references to all NetworkAgentInfos that are used to
460 * satisfy requests for that network type.
461 *
462 * This array is built out at startup such that an unsupported network
463 * doesn't get an ArrayList instance, making this a tristate:
464 * unsupported, supported but not active and active.
465 *
466 * The actual lists are populated when we scan the network types that
467 * are supported on this device.
468 */
469 private ArrayList<NetworkAgentInfo> mTypeLists[];
470
471 public LegacyTypeTracker() {
472 mTypeLists = (ArrayList<NetworkAgentInfo>[])
473 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
474 }
475
476 public void addSupportedType(int type) {
477 if (mTypeLists[type] != null) {
478 throw new IllegalStateException(
479 "legacy list for type " + type + "already initialized");
480 }
481 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
482 }
483
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700484 public boolean isTypeSupported(int type) {
485 return isNetworkTypeValid(type) && mTypeLists[type] != null;
486 }
487
488 public NetworkAgentInfo getNetworkForType(int type) {
489 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
490 return mTypeLists[type].get(0);
491 } else {
492 return null;
493 }
494 }
495
Robert Greenwalt8d482522015-06-24 13:23:42 -0700496 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900497 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700499 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900500 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900501 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900502 }
503 }
504
505 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700506 public void add(int type, NetworkAgentInfo nai) {
507 if (!isTypeSupported(type)) {
508 return; // Invalid network type.
509 }
510 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
511
512 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
513 if (list.contains(nai)) {
514 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
515 return;
516 }
517
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900518 list.add(nai);
519
520 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900521 final boolean isDefaultNetwork = isDefaultNetwork(nai);
522 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700523 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
524 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700525 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700526 }
527
Lorenzo Colittia793a672014-07-31 23:20:17 +0900528 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900529 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900530 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
531 if (list == null || list.isEmpty()) {
532 return;
533 }
534
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900535 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900536
537 if (!list.remove(nai)) {
538 return;
539 }
540
Robert Greenwalt8d482522015-06-24 13:23:42 -0700541 final DetailedState state = DetailedState.DISCONNECTED;
542
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900543 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700544 maybeLogBroadcast(nai, state, type, wasDefault);
545 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900546 }
547
548 if (!list.isEmpty() && wasFirstNetwork) {
549 if (DBG) log("Other network available for type " + type +
550 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900551 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700552 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
553 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900554 }
555 }
556
557 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900558 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
559 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900561 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700562 }
563 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700564
Robert Greenwalt8d482522015-06-24 13:23:42 -0700565 // send out another legacy broadcast - currently only used for suspend/unsuspend
566 // toggle
567 public void update(NetworkAgentInfo nai) {
568 final boolean isDefault = isDefaultNetwork(nai);
569 final DetailedState state = nai.networkInfo.getDetailedState();
570 for (int type = 0; type < mTypeLists.length; type++) {
571 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
572 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
573 if (isFirst || isDefault) {
574 maybeLogBroadcast(nai, state, type, isDefault);
575 sendLegacyNetworkBroadcast(nai, state, type);
576 }
577 }
578 }
579
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 private String naiToString(NetworkAgentInfo nai) {
581 String name = (nai != null) ? nai.name() : "null";
582 String state = (nai.networkInfo != null) ?
583 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
584 "???/???";
585 return name + " " + state;
586 }
587
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700588 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900589 pw.println("mLegacyTypeTracker:");
590 pw.increaseIndent();
591 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700592 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900593 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700594 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900595 pw.println();
596 pw.println("Current state:");
597 pw.increaseIndent();
598 for (int type = 0; type < mTypeLists.length; type++) {
599 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
600 for (NetworkAgentInfo nai : mTypeLists[type]) {
601 pw.println(type + " " + naiToString(nai));
602 }
603 }
604 pw.decreaseIndent();
605 pw.decreaseIndent();
606 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700607 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608
609 // This class needs its own log method because it has a different TAG.
610 private void log(String s) {
611 Slog.d(TAG, s);
612 }
613
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700614 }
615 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
616
Jeff Sharkey899223b2012-08-04 15:24:58 -0700617 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700618 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800619 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800620
Erik Klineda4bfa82015-04-30 12:58:40 +0900621 mDefaultRequest = createInternetRequestForTransport(-1);
622 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
623 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
624
625 mDefaultMobileDataRequest = createInternetRequestForTransport(
626 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700627
Wink Savillebb08caf2010-09-02 19:23:52 -0700628 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
629 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700630 mHandler = new InternalHandler(handlerThread.getLooper());
631 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700632
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800633 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800634 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
635 String id = Settings.Secure.getString(context.getContentResolver(),
636 Settings.Secure.ANDROID_ID);
637 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700638 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800639 SystemProperties.set("net.hostname", name);
640 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800641 }
642
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700643 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700644 String dns = Settings.Global.getString(context.getContentResolver(),
645 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700646 if (dns == null || dns.length() == 0) {
647 dns = context.getResources().getString(
648 com.android.internal.R.string.config_default_dns_server);
649 }
650 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800651 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
652 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800653 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700654 }
655
Jeremy Joslin79294842014-12-03 17:15:28 -0800656 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
657 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
658
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700659 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700660 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800661 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700662 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700663 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700664 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700665
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700666 try {
667 mPolicyManager.registerListener(mPolicyListener);
668 } catch (RemoteException e) {
669 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700670 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700671 }
672
673 final PowerManager powerManager = (PowerManager) context.getSystemService(
674 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700675 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
676 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
677 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800678 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700679
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700680 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700681
Wink Saville51f456f2013-04-23 14:26:51 -0700682 // TODO: What is the "correct" way to do determine if this is a wifi only device?
683 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
684 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700685 String[] naStrings = context.getResources().getStringArray(
686 com.android.internal.R.array.networkAttributes);
687 for (String naString : naStrings) {
688 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700689 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700690 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700691 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800692 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700693 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700694 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700695 }
Wink Saville51f456f2013-04-23 14:26:51 -0700696 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
697 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
698 n.type);
699 continue;
700 }
Wink Saville975c8482011-04-07 14:23:45 -0700701 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800702 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700703 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700704 continue;
705 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700706 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700707
Wink Saville975c8482011-04-07 14:23:45 -0700708 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700709 mNetworksDefined++;
710 } catch(Exception e) {
711 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700712 }
713 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700714
715 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
716 if (mNetConfigs[TYPE_VPN] == null) {
717 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
718 // don't need to add TYPE_VPN to mNetConfigs.
719 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
720 mNetworksDefined++; // used only in the log() statement below.
721 }
722
Wink Saville5e56bc52013-07-29 15:00:57 -0700723 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700724
Robert Greenwalt50393202011-06-21 17:26:14 -0700725 mProtectedNetworks = new ArrayList<Integer>();
726 int[] protectedNetworks = context.getResources().getIntArray(
727 com.android.internal.R.array.config_protectedNetworks);
728 for (int p : protectedNetworks) {
729 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
730 mProtectedNetworks.add(p);
731 } else {
732 if (DBG) loge("Ignoring protectedNetwork " + p);
733 }
734 }
735
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700736 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
737 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700738
Robert Greenwaltfab501672014-07-23 11:44:01 -0700739 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800740
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700741 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
742
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700743 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700744 IntentFilter intentFilter = new IntentFilter();
745 intentFilter.addAction(Intent.ACTION_USER_STARTING);
746 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
747 mContext.registerReceiverAsUser(
748 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900749
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700750 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700751 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700752 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700753 } catch (RemoteException e) {
754 loge("Error registering observer :" + e);
755 }
756
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700757 if (DBG) {
758 mInetLog = new ArrayList();
759 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700760
Erik Klineda4bfa82015-04-30 12:58:40 +0900761 mSettingsObserver = new SettingsObserver(mContext, mHandler);
762 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800763
John Spurlockbf991a82013-06-24 14:20:23 -0400764 mDataConnectionStats = new DataConnectionStats(mContext);
765 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400766
Jason Monkdecd2952013-10-10 14:02:51 -0400767 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700768
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400769 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700771
Erik Klineda4bfa82015-04-30 12:58:40 +0900772 private NetworkRequest createInternetRequestForTransport(int transportType) {
773 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900774 netCap.addCapability(NET_CAPABILITY_INTERNET);
775 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900776 if (transportType > -1) {
777 netCap.addTransportType(transportType);
778 }
779 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
780 }
781
782 private void handleMobileDataAlwaysOn() {
783 final boolean enable = (Settings.Global.getInt(
784 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
785 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
786 if (enable == isEnabled) {
787 return; // Nothing to do.
788 }
789
790 if (enable) {
791 handleRegisterNetworkRequest(new NetworkRequestInfo(
792 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
793 } else {
794 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
795 }
796 }
797
798 private void registerSettingsCallbacks() {
799 // Watch for global HTTP proxy changes.
800 mSettingsObserver.observe(
801 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
802 EVENT_APPLY_GLOBAL_HTTP_PROXY);
803
804 // Watch for whether or not to keep mobile data always on.
805 mSettingsObserver.observe(
806 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
807 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
808 }
809
Robert Greenwalt34524f02014-05-18 16:22:10 -0700810 private synchronized int nextNetworkRequestId() {
811 return mNextNetworkRequestId++;
812 }
813
Paul Jensen67b0b072015-06-10 11:22:17 -0400814 @VisibleForTesting
815 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400816 synchronized (mNetworkForNetId) {
817 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
818 int netId = mNextNetId;
819 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
820 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500821 if (!mNetIdInUse.get(netId)) {
822 mNetIdInUse.put(netId, true);
823 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400824 }
825 }
826 }
827 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700828 }
829
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800830 private NetworkState getFilteredNetworkState(int networkType, int uid) {
831 NetworkInfo info = null;
832 LinkProperties lp = null;
833 NetworkCapabilities nc = null;
834 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800835 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800836
837 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
838 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
839 if (nai != null) {
840 synchronized (nai) {
841 info = new NetworkInfo(nai.networkInfo);
842 lp = new LinkProperties(nai.linkProperties);
843 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400844 // Network objects are outwardly immutable so there is no point to duplicating.
845 // Duplicating also precludes sharing socket factories and connection pools.
846 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800847 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800848 }
849 info.setType(networkType);
850 } else {
851 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
852 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
853 info.setIsAvailable(true);
854 lp = new LinkProperties();
855 nc = new NetworkCapabilities();
856 network = null;
857 }
858 info = getFilteredNetworkInfo(info, lp, uid);
859 }
860
Jeff Sharkey32566012014-12-02 18:30:14 -0800861 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400862 }
863
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800864 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
865 if (network == null) {
866 return null;
867 }
868 synchronized (mNetworkForNetId) {
869 return mNetworkForNetId.get(network.netId);
870 }
871 };
872
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900873 private Network[] getVpnUnderlyingNetworks(int uid) {
874 if (!mLockdownEnabled) {
875 int user = UserHandle.getUserId(uid);
876 synchronized (mVpns) {
877 Vpn vpn = mVpns.get(user);
878 if (vpn != null && vpn.appliesToUid(uid)) {
879 return vpn.getUnderlyingNetworks();
880 }
881 }
882 }
883 return null;
884 }
885
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800886 private NetworkState getUnfilteredActiveNetworkState(int uid) {
887 NetworkInfo info = null;
888 LinkProperties lp = null;
889 NetworkCapabilities nc = null;
890 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800891 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800892
893 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800894
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900895 final Network[] networks = getVpnUnderlyingNetworks(uid);
896 if (networks != null) {
897 // getUnderlyingNetworks() returns:
898 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
899 // empty array => the VPN explicitly said "no default network".
900 // non-empty array => the VPN specified one or more default networks; we use the
901 // first one.
902 if (networks.length > 0) {
903 nai = getNetworkAgentInfoForNetwork(networks[0]);
904 } else {
905 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800906 }
907 }
908
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800909 if (nai != null) {
910 synchronized (nai) {
911 info = new NetworkInfo(nai.networkInfo);
912 lp = new LinkProperties(nai.linkProperties);
913 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400914 // Network objects are outwardly immutable so there is no point to duplicating.
915 // Duplicating also precludes sharing socket factories and connection pools.
916 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800917 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800918 }
919 }
920
Jeff Sharkey32566012014-12-02 18:30:14 -0800921 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400922 }
923
924 /**
925 * Check if UID should be blocked from using the network with the given LinkProperties.
926 */
927 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700928 final boolean networkCostly;
929 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700930
Robert Greenwalt12e67352014-05-13 21:41:06 -0700931 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700932 synchronized (mRulesLock) {
933 networkCostly = mMeteredIfaces.contains(iface);
934 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700935 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700936
Amith Yamasani15e472352015-04-24 19:06:07 -0700937 if ((uidRules & RULE_REJECT_ALL) != 0
938 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700939 return true;
940 }
941
942 // no restrictive rules; network is visible
943 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700944 }
945
946 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700947 * Return a filtered {@link NetworkInfo}, potentially marked
948 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800949 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700950 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800951 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
952 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400953 // network is blocked; clone and override state
954 info = new NetworkInfo(info);
955 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900956 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900957 log("returning Blocked NetworkInfo for ifname=" +
958 lp.getInterfaceName() + ", uid=" + uid);
959 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700960 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800961 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700962 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900963 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700964 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700965 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700966 }
967
968 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 * Return NetworkInfo for the active (i.e., connected) network interface.
970 * It is assumed that at most one network is active at a time. If more
971 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700972 * @return the info for the active network, or {@code null} if none is
973 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700975 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700977 enforceAccessPermission();
978 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800979 NetworkState state = getUnfilteredActiveNetworkState(uid);
980 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 }
982
Paul Jensen31a94f42015-02-13 14:18:39 -0500983 @Override
984 public Network getActiveNetwork() {
985 enforceAccessPermission();
986 final int uid = Binder.getCallingUid();
987 final int user = UserHandle.getUserId(uid);
988 int vpnNetId = NETID_UNSET;
989 synchronized (mVpns) {
990 final Vpn vpn = mVpns.get(user);
991 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
992 }
993 NetworkAgentInfo nai;
994 if (vpnNetId != NETID_UNSET) {
995 synchronized (mNetworkForNetId) {
996 nai = mNetworkForNetId.get(vpnNetId);
997 }
998 if (nai != null) return nai.network;
999 }
1000 nai = getDefaultNetwork();
1001 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1002 return nai != null ? nai.network : null;
1003 }
1004
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001005 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1006 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001007 final int uid = Binder.getCallingUid();
1008 NetworkState state = getUnfilteredActiveNetworkState(uid);
1009 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001010 }
1011
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001012 @Override
1013 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1014 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001015 NetworkState state = getUnfilteredActiveNetworkState(uid);
1016 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001017 }
1018
1019 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 public NetworkInfo getNetworkInfo(int networkType) {
1021 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001022 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001023 if (getVpnUnderlyingNetworks(uid) != null) {
1024 // A VPN is active, so we may need to return one of its underlying networks. This
1025 // information is not available in LegacyTypeTracker, so we have to get it from
1026 // getUnfilteredActiveNetworkState.
1027 NetworkState state = getUnfilteredActiveNetworkState(uid);
1028 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1029 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1030 }
1031 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001032 NetworkState state = getFilteredNetworkState(networkType, uid);
1033 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 }
1035
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001036 @Override
1037 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1038 enforceAccessPermission();
1039 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001040 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001041 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1042 if (nai != null) {
1043 synchronized (nai) {
1044 info = new NetworkInfo(nai.networkInfo);
1045 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001046 }
1047 }
1048 return info;
1049 }
1050
1051 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 public NetworkInfo[] getAllNetworkInfo() {
1053 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001054 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001055 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1056 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001057 NetworkInfo info = getNetworkInfo(networkType);
1058 if (info != null) {
1059 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001062 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 }
1064
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001065 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001066 public Network getNetworkForType(int networkType) {
1067 enforceAccessPermission();
1068 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001069 NetworkState state = getFilteredNetworkState(networkType, uid);
1070 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1071 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001072 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001073 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001074 }
1075
1076 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001077 public Network[] getAllNetworks() {
1078 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001079 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001080 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001081 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001082 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001083 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001084 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001085 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001086 }
1087
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001088 @Override
1089 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1090 // The basic principle is: if an app's traffic could possibly go over a
1091 // network, without the app doing anything multinetwork-specific,
1092 // (hence, by "default"), then include that network's capabilities in
1093 // the array.
1094 //
1095 // In the normal case, app traffic only goes over the system's default
1096 // network connection, so that's the only network returned.
1097 //
1098 // With a VPN in force, some app traffic may go into the VPN, and thus
1099 // over whatever underlying networks the VPN specifies, while other app
1100 // traffic may go over the system default network (e.g.: a split-tunnel
1101 // VPN, or an app disallowed by the VPN), so the set of networks
1102 // returned includes the VPN's underlying networks and the system
1103 // default.
1104 enforceAccessPermission();
1105
1106 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1107
1108 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001109 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001110 if (nc != null) {
1111 result.put(nai.network, nc);
1112 }
1113
1114 if (!mLockdownEnabled) {
1115 synchronized (mVpns) {
1116 Vpn vpn = mVpns.get(userId);
1117 if (vpn != null) {
1118 Network[] networks = vpn.getUnderlyingNetworks();
1119 if (networks != null) {
1120 for (Network network : networks) {
1121 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001122 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001123 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001124 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001125 }
1126 }
1127 }
1128 }
1129 }
1130 }
1131
1132 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1133 out = result.values().toArray(out);
1134 return out;
1135 }
1136
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001137 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001138 public boolean isNetworkSupported(int networkType) {
1139 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001140 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001141 }
1142
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001143 /**
1144 * Return LinkProperties for the active (i.e., connected) default
1145 * network interface. It is assumed that at most one default network
1146 * is active at a time. If more than one is active, it is indeterminate
1147 * which will be returned.
1148 * @return the ip properties for the active network, or {@code null} if
1149 * none is active
1150 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001151 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001152 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001153 enforceAccessPermission();
1154 final int uid = Binder.getCallingUid();
1155 NetworkState state = getUnfilteredActiveNetworkState(uid);
1156 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001157 }
1158
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001160 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001161 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001162 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1163 if (nai != null) {
1164 synchronized (nai) {
1165 return new LinkProperties(nai.linkProperties);
1166 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001167 }
1168 return null;
1169 }
1170
Robert Greenwalt12e67352014-05-13 21:41:06 -07001171 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001172 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001173 public LinkProperties getLinkProperties(Network network) {
1174 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001176 if (nai != null) {
1177 synchronized (nai) {
1178 return new LinkProperties(nai.linkProperties);
1179 }
1180 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001181 return null;
1182 }
1183
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001184 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001185 if (nai != null) {
1186 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001187 if (nai.networkCapabilities != null) {
1188 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001189 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001190 }
1191 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001192 return null;
1193 }
1194
1195 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001196 public NetworkCapabilities getNetworkCapabilities(Network network) {
1197 enforceAccessPermission();
1198 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1199 }
1200
1201 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001202 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001203 // Require internal since we're handing out IMSI details
1204 enforceConnectivityInternalPermission();
1205
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001206 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001207 for (Network network : getAllNetworks()) {
1208 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1209 if (nai != null) {
1210 synchronized (nai) {
1211 final String subscriberId = (nai.networkMisc != null)
1212 ? nai.networkMisc.subscriberId : null;
1213 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1214 nai.networkCapabilities, network, subscriberId, null));
1215 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001216 }
1217 }
1218 return result.toArray(new NetworkState[result.size()]);
1219 }
1220
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001221 @Override
1222 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1223 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001224 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001225 final long token = Binder.clearCallingIdentity();
1226 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001227 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1228 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001229 try {
1230 return mPolicyManager.getNetworkQuotaInfo(state);
1231 } catch (RemoteException e) {
1232 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001233 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001234 return null;
1235 } finally {
1236 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001237 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001238 }
1239
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001240 @Override
1241 public boolean isActiveNetworkMetered() {
1242 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001244 final long token = Binder.clearCallingIdentity();
1245 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001246 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001247 } finally {
1248 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001249 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001250 }
1251
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001252 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1253 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1254 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001255 try {
1256 return mPolicyManager.isNetworkMetered(state);
1257 } catch (RemoteException e) {
1258 }
1259 }
1260 return false;
1261 }
1262
Jeff Sharkey216c1812012-08-05 14:29:23 -07001263 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1264 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001265 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001266 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001267 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001268 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001269 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001270
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001271 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 * Ensure that a network route exists to deliver traffic to the specified
1273 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001274 * @param networkType the type of the network over which traffic to the
1275 * specified host is to be routed
1276 * @param hostAddress the IP address of the host to which the route is
1277 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 * @return {@code true} on success, {@code false} on failure
1279 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001280 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001282 if (mProtectedNetworks.contains(networkType)) {
1283 enforceConnectivityInternalPermission();
1284 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001285
Chad Brubakerc0234532014-02-14 13:24:29 -08001286 InetAddress addr;
1287 try {
1288 addr = InetAddress.getByAddress(hostAddress);
1289 } catch (UnknownHostException e) {
1290 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1291 return false;
1292 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001295 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 return false;
1297 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001298
1299 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1300 if (nai == null) {
1301 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1302 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1303 } else {
1304 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1305 }
1306 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001307 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001308
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001309 DetailedState netState;
1310 synchronized (nai) {
1311 netState = nai.networkInfo.getDetailedState();
1312 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001313
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001314 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001315 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001316 log("requestRouteToHostAddress on down network "
1317 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001318 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001319 }
1320 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001322
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001323 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001324 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001325 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001326 LinkProperties lp;
1327 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001328 synchronized (nai) {
1329 lp = nai.linkProperties;
1330 netId = nai.network.netId;
1331 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001332 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001333 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1334 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001335 } finally {
1336 Binder.restoreCallingIdentity(token);
1337 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001338 }
1339
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001340 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001341 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001342 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001343 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001344 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001345 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001346 if (bestRoute.getGateway().equals(addr)) {
1347 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001348 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001349 } else {
1350 // if we will connect to this through another route, add a direct route
1351 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001352 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001353 }
1354 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001355 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001356 try {
1357 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1358 } catch (Exception e) {
1359 // never crash - catch them all
1360 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001361 return false;
1362 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001363 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
1365
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001366 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1367 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001368 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001369 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001370 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001371 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001372 }
1373
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001374 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001375 // skip update when we've already applied rules
1376 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1377 if (oldRules == uidRules) return;
1378
1379 mUidRules.put(uid, uidRules);
1380 }
1381
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001382 // TODO: notify UID when it has requested targeted updates
1383 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001384
1385 @Override
1386 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001387 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001388 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001389 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001390 }
1391
1392 synchronized (mRulesLock) {
1393 mMeteredIfaces.clear();
1394 for (String iface : meteredIfaces) {
1395 mMeteredIfaces.add(iface);
1396 }
1397 }
1398 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001399
1400 @Override
1401 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1402 // caller is NPMS, since we only register with them
1403 if (LOGD_RULES) {
1404 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1405 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001406 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001407 };
1408
Robin Lee3b3dd942015-05-12 18:14:58 +01001409 /**
1410 * Require that the caller is either in the same user or has appropriate permission to interact
1411 * across users.
1412 *
1413 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1414 */
1415 private void enforceCrossUserPermission(int userId) {
1416 if (userId == UserHandle.getCallingUserId()) {
1417 // Not a cross-user call.
1418 return;
1419 }
1420 mContext.enforceCallingOrSelfPermission(
1421 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1422 "ConnectivityService");
1423 }
1424
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001425 private void enforceInternetPermission() {
1426 mContext.enforceCallingOrSelfPermission(
1427 android.Manifest.permission.INTERNET,
1428 "ConnectivityService");
1429 }
1430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001432 mContext.enforceCallingOrSelfPermission(
1433 android.Manifest.permission.ACCESS_NETWORK_STATE,
1434 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436
1437 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001438 mContext.enforceCallingOrSelfPermission(
1439 android.Manifest.permission.CHANGE_NETWORK_STATE,
1440 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
1442
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001443 private void enforceTetherAccessPermission() {
1444 mContext.enforceCallingOrSelfPermission(
1445 android.Manifest.permission.ACCESS_NETWORK_STATE,
1446 "ConnectivityService");
1447 }
1448
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001449 private void enforceConnectivityInternalPermission() {
1450 mContext.enforceCallingOrSelfPermission(
1451 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1452 "ConnectivityService");
1453 }
1454
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001455 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001456 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001457 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001458 }
1459
1460 private void sendInetConditionBroadcast(NetworkInfo info) {
1461 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1462 }
1463
Wink Saville628b0852011-08-04 15:01:58 -07001464 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001465 if (mLockdownTracker != null) {
1466 info = mLockdownTracker.augmentNetworkInfo(info);
1467 }
1468
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001469 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001470 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001471 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 if (info.isFailover()) {
1473 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1474 info.setFailover(false);
1475 }
1476 if (info.getReason() != null) {
1477 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1478 }
1479 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001480 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1481 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001483 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001484 return intent;
1485 }
1486
1487 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1488 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1489 }
1490
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001491 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001492 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1493 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1494 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001495 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001496 final long ident = Binder.clearCallingIdentity();
1497 try {
1498 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1499 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1500 } finally {
1501 Binder.restoreCallingIdentity(ident);
1502 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001503 }
1504
Mike Lockwood0f79b542009-08-14 14:18:49 -04001505 private void sendStickyBroadcast(Intent intent) {
1506 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001507 if (!mSystemReady) {
1508 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001509 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001510 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001511 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001512 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001513 }
1514
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001515 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001516 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1517 final IBatteryStats bs = BatteryStatsService.getService();
1518 try {
1519 NetworkInfo ni = intent.getParcelableExtra(
1520 ConnectivityManager.EXTRA_NETWORK_INFO);
1521 bs.noteConnectivityChanged(intent.getIntExtra(
1522 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1523 ni != null ? ni.getState().toString() : "?");
1524 } catch (RemoteException e) {
1525 }
1526 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001527 try {
1528 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1529 } finally {
1530 Binder.restoreCallingIdentity(ident);
1531 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001532 }
1533 }
1534
1535 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001536 loadGlobalProxy();
1537
Mike Lockwood0f79b542009-08-14 14:18:49 -04001538 synchronized(this) {
1539 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001540 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001541 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001542 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001543 }
1544 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001545 // load the global proxy at startup
1546 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001547
1548 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1549 // for user to unlock device.
1550 if (!updateLockdownVpn()) {
1551 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1552 mContext.registerReceiver(mUserPresentReceiver, filter);
1553 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001554
Erik Klineda4bfa82015-04-30 12:58:40 +09001555 // Configure whether mobile data is always on.
1556 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1557
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001558 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001559
1560 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 }
1562
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001563 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1564 @Override
1565 public void onReceive(Context context, Intent intent) {
1566 // Try creating lockdown tracker, since user present usually means
1567 // unlocked keystore.
1568 if (updateLockdownVpn()) {
1569 mContext.unregisterReceiver(this);
1570 }
1571 }
1572 };
1573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001575 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001576 *
1577 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001578 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001579 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001580 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1581 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001582
1583 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001584 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001585
Robert Greenwalt7b816022014-04-18 15:25:25 -07001586 if (networkAgent.networkCapabilities.hasTransport(
1587 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001588 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1589 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001590 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001591 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001592 } else if (networkAgent.networkCapabilities.hasTransport(
1593 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001594 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1595 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001596 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001597 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001598 } else {
1599 // do not track any other networks
1600 timeout = 0;
1601 }
1602
Robert Greenwalt7b816022014-04-18 15:25:25 -07001603 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001604 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001605 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001606 } catch (Exception e) {
1607 // You shall not crash!
1608 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001609 }
1610 }
1611 }
1612
1613 /**
1614 * Remove data activity tracking when network disconnects.
1615 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001616 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1617 final String iface = networkAgent.linkProperties.getInterfaceName();
1618 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001619
Robert Greenwalt7b816022014-04-18 15:25:25 -07001620 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1621 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001622 try {
1623 // the call fails silently if no idletimer setup for this interface
1624 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001625 } catch (Exception e) {
1626 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001627 }
1628 }
1629 }
1630
1631 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001632 * Reads the network specific MTU size from reources.
1633 * and set it on it's iface.
1634 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001635 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1636 final String iface = newLp.getInterfaceName();
1637 final int mtu = newLp.getMtu();
1638 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1639 if (VDBG) log("identical MTU - not setting");
1640 return;
1641 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001642
Robert Greenwalt43074032014-08-15 17:53:05 -07001643 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001644 loge("Unexpected mtu value: " + mtu + ", " + iface);
1645 return;
1646 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001647
w1997615afd812014-08-05 15:18:11 -07001648 // Cannot set MTU without interface name
1649 if (TextUtils.isEmpty(iface)) {
1650 loge("Setting MTU size with null iface.");
1651 return;
1652 }
1653
Robert Greenwalt7b816022014-04-18 15:25:25 -07001654 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001655 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001656 mNetd.setMtu(iface, mtu);
1657 } catch (Exception e) {
1658 Slog.e(TAG, "exception in setMtu()" + e);
1659 }
1660 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001661
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001662 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001663 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1664
1665 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001666 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001667 protected int getDefaultTcpRwnd() {
1668 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1669 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001670
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001671 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1672 if (isDefaultNetwork(nai) == false) {
1673 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001674 }
1675
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001676 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1677 String[] values = null;
1678 if (tcpBufferSizes != null) {
1679 values = tcpBufferSizes.split(",");
1680 }
1681
1682 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001683 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001684 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1685 values = tcpBufferSizes.split(",");
1686 }
1687
1688 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1689
1690 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001691 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001692
1693 final String prefix = "/sys/kernel/ipv4/tcp_";
1694 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1695 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1696 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1697 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1698 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1699 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1700 mCurrentTcpBufferSizes = tcpBufferSizes;
1701 } catch (IOException e) {
1702 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001703 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001704
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001705 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001706 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001707 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1708 if (rwndValue != 0) {
1709 SystemProperties.set(sysctlKey, rwndValue.toString());
1710 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001711 }
1712
Mattias Falk8b47b362011-08-23 14:15:13 +02001713 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001714 /*
1715 * Tell the VMs to toss their DNS caches
1716 */
1717 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1718 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001719 /*
1720 * Connectivity events can happen before boot has completed ...
1721 */
1722 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001723 final long ident = Binder.clearCallingIdentity();
1724 try {
1725 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1726 } finally {
1727 Binder.restoreCallingIdentity(ident);
1728 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001729 }
1730
Robert Greenwalt562cc542014-05-15 18:07:26 -07001731 @Override
1732 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001733 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1734 NETWORK_RESTORE_DELAY_PROP_NAME);
1735 if(restoreDefaultNetworkDelayStr != null &&
1736 restoreDefaultNetworkDelayStr.length() != 0) {
1737 try {
1738 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1739 } catch (NumberFormatException e) {
1740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001742 // if the system property isn't set, use the value for the apn type
1743 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1744
1745 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1746 (mNetConfigs[networkType] != null)) {
1747 ret = mNetConfigs[networkType].restoreTime;
1748 }
1749 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
1751
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001752 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001753 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001754 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001755 }
1756 return false;
1757 }
1758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001760 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1761 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001762 if (mContext.checkCallingOrSelfPermission(
1763 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001765 pw.println("Permission Denial: can't dump ConnectivityService " +
1766 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1767 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 return;
1769 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001770
Erik Kline379747a2015-06-05 17:47:34 +09001771 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001772 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001773 final long DIAG_TIME_MS = 5000;
1774 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1775 // Start gathering diagnostic information.
1776 netDiags.add(new NetworkDiagnostics(
1777 nai.network,
1778 new LinkProperties(nai.linkProperties),
1779 DIAG_TIME_MS));
1780 }
1781
1782 for (NetworkDiagnostics netDiag : netDiags) {
1783 pw.println();
1784 netDiag.waitForMeasurements();
1785 netDiag.dump(pw);
1786 }
1787
1788 return;
1789 }
1790
Lorenzo Colittie3805462015-06-03 11:18:24 +09001791 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001792 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001793 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001794 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001795 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001796 pw.println();
1797
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001798 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1799 pw.print("Active default network: ");
1800 if (defaultNai == null) {
1801 pw.println("none");
1802 } else {
1803 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001805 pw.println();
1806
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001807 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001808 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001809 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1810 pw.println(nai.toString());
1811 pw.increaseIndent();
1812 pw.println("Requests:");
1813 pw.increaseIndent();
1814 for (int i = 0; i < nai.networkRequests.size(); i++) {
1815 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001816 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001817 pw.decreaseIndent();
1818 pw.println("Lingered:");
1819 pw.increaseIndent();
1820 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1821 pw.decreaseIndent();
1822 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001823 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001824 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001825 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001826
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001827 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001828 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001829 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1830 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001831 }
1832 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001833 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001834
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001835 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001836
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001837 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001838 pw.print("mNetTransitionWakeLock: currently " +
1839 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1840 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1841 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1842 } else {
1843 pw.println(", last requested never");
1844 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001845 }
1846 pw.println();
1847
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001848 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001849
Lorenzo Colittie3805462015-06-03 11:18:24 +09001850 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001851 pw.println();
1852 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001853 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001854 for(int i = 0; i < mInetLog.size(); i++) {
1855 pw.println(mInetLog.get(i));
1856 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001857 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001858 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001859
1860 if (argsContain(args, "--short") == false) {
1861 pw.println();
1862 synchronized (mValidationLogs) {
1863 pw.println("mValidationLogs (most recent first):");
1864 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1865 pw.println(p.first);
1866 pw.increaseIndent();
1867 p.second.dump(fd, pw, args);
1868 pw.decreaseIndent();
1869 }
1870 }
1871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 }
1873
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001874 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001875 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001876 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001877 if (officialNai != null && officialNai.equals(nai)) return true;
1878 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001879 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001880 " - " + nai);
1881 }
1882 return false;
1883 }
1884
Paul Jensenc8b9a742014-09-30 15:37:41 -04001885 private boolean isRequest(NetworkRequest request) {
1886 return mNetworkRequests.get(request).isRequest;
1887 }
1888
Robert Greenwalt42acef32009-08-12 16:08:25 -07001889 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001890 private class NetworkStateTrackerHandler extends Handler {
1891 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001892 super(looper);
1893 }
1894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 @Override
1896 public void handleMessage(Message msg) {
1897 NetworkInfo info;
1898 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001899 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001900 handleAsyncChannelHalfConnect(msg);
1901 break;
1902 }
1903 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1904 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1905 if (nai != null) nai.asyncChannel.disconnect();
1906 break;
1907 }
1908 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1909 handleAsyncChannelDisconnected(msg);
1910 break;
1911 }
1912 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1913 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1914 if (nai == null) {
1915 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1916 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001917 final NetworkCapabilities networkCapabilities =
1918 (NetworkCapabilities)msg.obj;
1919 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1920 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1921 Slog.wtf(TAG, "BUG: " + nai + " has stateful capability.");
1922 }
1923 updateCapabilities(nai, networkCapabilities,
1924 NascentState.NOT_JUST_VALIDATED);
Robert Greenwalte049c232014-04-11 15:53:27 -07001925 }
1926 break;
1927 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001928 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1929 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1930 if (nai == null) {
1931 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1932 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001933 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001934 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001935 "; created=" + nai.created);
1936 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001937 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001938 synchronized (nai) {
1939 nai.linkProperties = (LinkProperties)msg.obj;
1940 }
Paul Jenseneec75412014-08-04 12:21:19 -04001941 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001942 }
1943 break;
1944 }
1945 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1946 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1947 if (nai == null) {
1948 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1949 break;
1950 }
1951 info = (NetworkInfo) msg.obj;
1952 updateNetworkInfo(nai, info);
1953 break;
1954 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001955 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1956 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1957 if (nai == null) {
1958 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1959 break;
1960 }
1961 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001962 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001963 break;
1964 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001965 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1966 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1967 if (nai == null) {
1968 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1969 break;
1970 }
1971 try {
1972 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001973 } catch (Exception e) {
1974 // Never crash!
1975 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001976 }
1977 break;
1978 }
1979 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1980 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1981 if (nai == null) {
1982 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1983 break;
1984 }
1985 try {
1986 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001987 } catch (Exception e) {
1988 // Never crash!
1989 loge("Exception in removeVpnUidRanges: " + e);
1990 }
1991 break;
1992 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001993 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1994 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1995 if (nai == null) {
1996 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1997 break;
1998 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001999 if (nai.created && !nai.networkMisc.explicitlySelected) {
2000 loge("ERROR: created network explicitly selected.");
2001 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002002 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002003 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002004 break;
2005 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002006 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002007 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002008 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2009 final boolean valid =
2010 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002011 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2012 if (valid != nai.lastValidated) {
2013 final int oldScore = nai.getCurrentScore();
2014 final NascentState nascent = (valid && !nai.everValidated) ?
2015 NascentState.JUST_VALIDATED : NascentState.NOT_JUST_VALIDATED;
2016 nai.lastValidated = valid;
2017 nai.everValidated |= valid;
2018 updateCapabilities(nai, nai.networkCapabilities, nascent);
2019 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2020 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002021 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002022 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002023 // Let the NetworkAgent know the state of its network
2024 nai.asyncChannel.sendMessage(
2025 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2026 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2027 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002028 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002029 break;
2030 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002031 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002032 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002033 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2034 handleLingerComplete(nai);
2035 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002036 break;
2037 }
Paul Jensen869868be2014-05-15 10:33:05 -04002038 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002039 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002040 final boolean visible = (msg.arg1 != 0);
2041 final NetworkAgentInfo nai;
2042 synchronized (mNetworkForNetId) {
2043 nai = mNetworkForNetId.get(netId);
2044 }
2045 // If captive portal status has changed, update capabilities.
2046 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2047 nai.lastCaptivePortalDetected = visible;
2048 nai.everCaptivePortalDetected |= visible;
Paul Jensen1c7ba022015-06-16 14:27:36 -04002049 updateCapabilities(nai, nai.networkCapabilities,
2050 NascentState.NOT_JUST_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002051 }
2052 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002053 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002054 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002055 if (nai == null) {
2056 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2057 break;
2058 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002059 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002060 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2061 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002062 }
Paul Jensen869868be2014-05-15 10:33:05 -04002063 break;
2064 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002065 }
2066 }
2067 }
2068
Paul Jensen0cc17322014-11-25 15:26:53 -05002069 // Cancel any lingering so the linger timeout doesn't teardown a network.
2070 // This should be called when a network begins satisfying a NetworkRequest.
2071 // Note: depending on what state the NetworkMonitor is in (e.g.,
2072 // if it's awaiting captive portal login, or if validation failed), this
2073 // may trigger a re-evaluation of the network.
2074 private void unlinger(NetworkAgentInfo nai) {
2075 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002076 // If network has never been validated, it cannot have been lingered, so don't bother
2077 // needlessly triggering a re-evaluation.
2078 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002079 nai.networkLingered.clear();
2080 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2081 }
2082
Robert Greenwalt7b816022014-04-18 15:25:25 -07002083 private void handleAsyncChannelHalfConnect(Message msg) {
2084 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002085 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002086 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2087 if (VDBG) log("NetworkFactory connected");
2088 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002089 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002090 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002091 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002092 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002093 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002094 }
2095 } else {
2096 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002097 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002098 }
2099 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2100 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2101 if (VDBG) log("NetworkAgent connected");
2102 // A network agent has requested a connection. Establish the connection.
2103 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2104 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2105 } else {
2106 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002107 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002108 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002109 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002110 synchronized (mNetworkForNetId) {
2111 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002112 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002113 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002114 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002115 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002116 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002117 }
2118 }
2119 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002120
Robert Greenwalt7b816022014-04-18 15:25:25 -07002121 private void handleAsyncChannelDisconnected(Message msg) {
2122 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2123 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002124 if (DBG) {
2125 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2126 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002127 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002128 // TODO - if we move the logic to the network agent (have them disconnect
2129 // because they lost all their requests or because their score isn't good)
2130 // then they would disconnect organically, report their new state and then
2131 // disconnect the channel.
2132 if (nai.networkInfo.isConnected()) {
2133 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2134 null, null);
2135 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002136 final boolean wasDefault = isDefaultNetwork(nai);
2137 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002138 mDefaultInetConditionPublished = 0;
2139 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002140 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002141 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002142 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002143 mNetworkAgentInfos.remove(msg.replyTo);
2144 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002145 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002146 // Remove the NetworkAgent, but don't mark the netId as
2147 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002148 mNetworkForNetId.remove(nai.network.netId);
2149 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 // Since we've lost the network, go through all the requests that
2151 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002152 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002153 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002154 for (int i = 0; i < nai.networkRequests.size(); i++) {
2155 NetworkRequest request = nai.networkRequests.valueAt(i);
2156 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2157 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002158 if (DBG) {
2159 log("Checking for replacement network to handle request " + request );
2160 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002161 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002162 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002163 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002164 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2165 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002166 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002167 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002168 alternative = existing;
2169 }
2170 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002171 if (alternative != null) {
2172 if (DBG) log(" found replacement in " + alternative.name());
2173 if (!toActivate.contains(alternative)) {
2174 toActivate.add(alternative);
2175 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002176 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002177 }
2178 }
2179 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2180 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002181 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002182 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002183 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002184 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002185 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002186 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002187 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2188 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002189 }
Paul Jensen62d30802015-06-17 14:42:30 -04002190 if (nai.created) {
2191 // Tell netd to clean up the configuration for this network
2192 // (routing rules, DNS, etc).
2193 // This may be slow as it requires a lot of netd shelling out to ip and
2194 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2195 // after we've rematched networks with requests which should make a potential
2196 // fallback network the default or requested a new network from the
2197 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2198 // long time.
2199 try {
2200 mNetd.removeNetwork(nai.network.netId);
2201 } catch (Exception e) {
2202 loge("Exception removing network: " + e);
2203 }
2204 }
2205 synchronized (mNetworkForNetId) {
2206 mNetIdInUse.delete(nai.network.netId);
2207 }
2208 } else {
2209 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2210 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002211 }
2212 }
2213
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002214 // If this method proves to be too slow then we can maintain a separate
2215 // pendingIntent => NetworkRequestInfo map.
2216 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2217 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2218 Intent intent = pendingIntent.getIntent();
2219 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2220 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2221 if (existingPendingIntent != null &&
2222 existingPendingIntent.getIntent().filterEquals(intent)) {
2223 return entry.getValue();
2224 }
2225 }
2226 return null;
2227 }
2228
2229 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2230 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2231
2232 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2233 if (existingRequest != null) { // remove the existing request.
2234 if (DBG) log("Replacing " + existingRequest.request + " with "
2235 + nri.request + " because their intents matched.");
2236 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2237 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002238 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002239 }
2240
Erik Klineda4bfa82015-04-30 12:58:40 +09002241 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002242 mNetworkRequests.put(nri.request, nri);
2243
Paul Jensen0cc17322014-11-25 15:26:53 -05002244 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2245
Robert Greenwalt9258c642014-03-26 16:47:06 -07002246 // Check for the best currently alive network that satisfies this request
2247 NetworkAgentInfo bestNetwork = null;
2248 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002249 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002250 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002251 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002252 if (!nri.isRequest) {
2253 // Not setting bestNetwork here as a listening NetworkRequest may be
2254 // satisfied by multiple Networks. Instead the request is added to
2255 // each satisfying Network and notified about each.
Paul Jensen3d911462015-06-12 06:40:24 -04002256 if (!network.addRequest(nri.request)) {
2257 Slog.wtf(TAG, "BUG: " + network.name() + " already has " + nri.request);
2258 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002259 notifyNetworkCallback(network, nri);
2260 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002261 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002262 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002263 }
2264 }
2265 }
2266 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002267 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002268 unlinger(bestNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04002269 if (!bestNetwork.addRequest(nri.request)) {
2270 Slog.wtf(TAG, "BUG: " + bestNetwork.name() + " already has " + nri.request);
2271 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07002272 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002273 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002274 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002275 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2276 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002277 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002278
Lorenzo Colittia793a672014-07-31 23:20:17 +09002279 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002280 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002281 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002282 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002283 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002284 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002285 }
2286 }
2287 }
2288
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002289 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2290 int callingUid) {
2291 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2292 if (nri != null) {
2293 handleReleaseNetworkRequest(nri.request, callingUid);
2294 }
2295 }
2296
Paul Jensen99364842014-12-09 11:43:45 -05002297 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2298 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2299 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2300 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2301 private boolean unneeded(NetworkAgentInfo nai) {
2302 if (!nai.created || nai.isVPN()) return false;
2303 boolean unneeded = true;
2304 if (nai.everValidated) {
2305 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2306 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2307 try {
2308 if (isRequest(nr)) unneeded = false;
2309 } catch (Exception e) {
2310 loge("Request " + nr + " not found in mNetworkRequests.");
2311 loge(" it came from request list of " + nai.name());
2312 }
2313 }
2314 } else {
2315 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2316 // If this Network is already the highest scoring Network for a request, or if
2317 // there is hope for it to become one if it validated, then it is needed.
2318 if (nri.isRequest && nai.satisfies(nri.request) &&
2319 (nai.networkRequests.get(nri.request.requestId) != null ||
2320 // Note that this catches two important cases:
2321 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2322 // is currently satisfying the request. This is desirable when
2323 // cellular ends up validating but WiFi does not.
2324 // 2. Unvalidated WiFi will not be reaped when validated cellular
2325 // is currently satsifying the request. This is desirable when
2326 // WiFi ends up validating and out scoring cellular.
2327 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2328 nai.getCurrentScoreAsValidated())) {
2329 unneeded = false;
2330 break;
2331 }
2332 }
2333 }
2334 return unneeded;
2335 }
2336
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002337 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2338 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002339 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002340 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002341 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2342 return;
2343 }
2344 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002345 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002346 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002347 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002348 // Find all networks that are satisfying this request and remove the request
2349 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002350 // TODO - it's my understanding that for a request there is only a single
2351 // network satisfying it, so this loop is wasteful
2352 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002353 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2354 if (nai.networkRequests.get(nri.request.requestId) != null) {
2355 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002356 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002357 log(" Removing from current network " + nai.name() +
2358 ", leaving " + nai.networkRequests.size() +
2359 " requests.");
2360 }
Paul Jensen99364842014-12-09 11:43:45 -05002361 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002362 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002363 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002364 } else {
2365 // suspect there should only be one pass through here
2366 // but if any were kept do the check below
2367 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002368 }
2369 }
2370 }
2371
Robert Greenwalt51481852015-01-08 14:43:31 -08002372 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2373 if (nai != null) {
2374 mNetworkForRequestId.remove(nri.request.requestId);
2375 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002376 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002377 // that a network connected to serve it, even though the network was already
2378 // connected. Now that this request has gone away, we might have to pretend
2379 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002380 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002381 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2382 boolean doRemove = true;
2383 if (wasKept) {
2384 // check if any of the remaining requests for this network are for the
2385 // same legacy type - if so, don't remove the nai
2386 for (int i = 0; i < nai.networkRequests.size(); i++) {
2387 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2388 if (otherRequest.legacyType == nri.request.legacyType &&
2389 isRequest(otherRequest)) {
2390 if (DBG) log(" still have other legacy request - leaving");
2391 doRemove = false;
2392 }
2393 }
2394 }
2395
2396 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002397 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002398 }
2399 }
2400
Robert Greenwalta67be032014-05-16 15:49:14 -07002401 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002402 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2403 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002404 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002405 } else {
2406 // listens don't have a singular affectedNetwork. Check all networks to see
2407 // if this listen request applies and remove it.
2408 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2409 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002410 }
2411 }
2412 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2413 }
2414 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002415
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002416 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2417 enforceConnectivityInternalPermission();
2418 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2419 accept ? 1 : 0, always ? 1: 0, network));
2420 }
2421
2422 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2423 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2424 " accept=" + accept + " always=" + always);
2425
2426 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2427 if (nai == null) {
2428 // Nothing to do.
2429 return;
2430 }
2431
2432 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002433 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002434 return;
2435 }
2436
2437 if (!nai.networkMisc.explicitlySelected) {
2438 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2439 }
2440
2441 if (accept != nai.networkMisc.acceptUnvalidated) {
2442 int oldScore = nai.getCurrentScore();
2443 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen1c7ba022015-06-16 14:27:36 -04002444 rematchAllNetworksAndRequests(nai, oldScore, NascentState.NOT_JUST_VALIDATED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002445 sendUpdatedScoreToFactories(nai);
2446 }
2447
2448 if (always) {
2449 nai.asyncChannel.sendMessage(
2450 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2451 }
2452
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002453 if (!accept) {
2454 // Tell the NetworkAgent that the network does not have Internet access (because that's
2455 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2456 // the future. We do this now because NetworkMonitor might not yet have finished
2457 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2458 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2459 NetworkAgent.INVALID_NETWORK, 0, null);
2460 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2461 // to reconnect to it immediately. http://b/20739299
2462 }
2463
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002464 }
2465
2466 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002467 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002468 mHandler.sendMessageDelayed(
2469 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2470 PROMPT_UNVALIDATED_DELAY_MS);
2471 }
2472
2473 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002474 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002475 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2476
2477 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2478 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002479 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002480 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002481 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2482 return;
2483 }
2484
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002485 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002486 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002487 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2488 intent.setClassName("com.android.settings",
2489 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002490
2491 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2492 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2493 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002494 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002495 }
2496
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002497 private class InternalHandler extends Handler {
2498 public InternalHandler(Looper looper) {
2499 super(looper);
2500 }
2501
2502 @Override
2503 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002504 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002505 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002506 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002507 String causedBy = null;
2508 synchronized (ConnectivityService.this) {
2509 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2510 mNetTransitionWakeLock.isHeld()) {
2511 mNetTransitionWakeLock.release();
2512 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002513 } else {
2514 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002515 }
2516 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002517 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2518 log("Failed to find a new network - expiring NetTransition Wakelock");
2519 } else {
2520 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2521 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002522 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002523 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002524 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002525 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002526 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002527 break;
2528 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002529 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002530 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002531 sendStickyBroadcast(intent);
2532 break;
2533 }
Jason Monkdecd2952013-10-10 14:02:51 -04002534 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002535 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002536 break;
2537 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002538 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002539 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2540 break;
2541 }
2542 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2543 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002544 break;
2545 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002546 case EVENT_REGISTER_NETWORK_AGENT: {
2547 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2548 break;
2549 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002550 case EVENT_REGISTER_NETWORK_REQUEST:
2551 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002552 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002553 break;
2554 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002555 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2556 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002557 handleRegisterNetworkRequestWithIntent(msg);
2558 break;
2559 }
2560 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2561 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2562 break;
2563 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002564 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002565 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002566 break;
2567 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002568 case EVENT_SET_ACCEPT_UNVALIDATED: {
2569 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2570 break;
2571 }
2572 case EVENT_PROMPT_UNVALIDATED: {
2573 handlePromptUnvalidated((Network) msg.obj);
2574 break;
2575 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002576 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2577 handleMobileDataAlwaysOn();
2578 break;
2579 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002580 case EVENT_SYSTEM_READY: {
2581 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2582 nai.networkMonitor.systemReady = true;
2583 }
2584 break;
2585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 }
2587 }
2588 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002589
2590 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002591 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002592 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002593 if (isTetheringSupported()) {
2594 return mTethering.tether(iface);
2595 } else {
2596 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2597 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002598 }
2599
2600 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002601 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002602 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002603
2604 if (isTetheringSupported()) {
2605 return mTethering.untether(iface);
2606 } else {
2607 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2608 }
2609 }
2610
2611 // javadoc from interface
2612 public int getLastTetherError(String iface) {
2613 enforceTetherAccessPermission();
2614
2615 if (isTetheringSupported()) {
2616 return mTethering.getLastTetherError(iface);
2617 } else {
2618 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2619 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002620 }
2621
2622 // TODO - proper iface API for selection by property, inspection, etc
2623 public String[] getTetherableUsbRegexs() {
2624 enforceTetherAccessPermission();
2625 if (isTetheringSupported()) {
2626 return mTethering.getTetherableUsbRegexs();
2627 } else {
2628 return new String[0];
2629 }
2630 }
2631
2632 public String[] getTetherableWifiRegexs() {
2633 enforceTetherAccessPermission();
2634 if (isTetheringSupported()) {
2635 return mTethering.getTetherableWifiRegexs();
2636 } else {
2637 return new String[0];
2638 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002639 }
2640
Danica Chang6fdd0c62010-08-11 14:54:43 -07002641 public String[] getTetherableBluetoothRegexs() {
2642 enforceTetherAccessPermission();
2643 if (isTetheringSupported()) {
2644 return mTethering.getTetherableBluetoothRegexs();
2645 } else {
2646 return new String[0];
2647 }
2648 }
2649
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002650 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002651 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002652 if (isTetheringSupported()) {
2653 return mTethering.setUsbTethering(enable);
2654 } else {
2655 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2656 }
2657 }
2658
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002659 // TODO - move iface listing, queries, etc to new module
2660 // javadoc from interface
2661 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002662 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002663 return mTethering.getTetherableIfaces();
2664 }
2665
2666 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002667 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002668 return mTethering.getTetheredIfaces();
2669 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002670
Robert Greenwalt5a735062010-03-02 17:25:02 -08002671 public String[] getTetheringErroredIfaces() {
2672 enforceTetherAccessPermission();
2673 return mTethering.getErroredIfaces();
2674 }
2675
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002676 public String[] getTetheredDhcpRanges() {
2677 enforceConnectivityInternalPermission();
2678 return mTethering.getTetheredDhcpRanges();
2679 }
2680
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002681 // if ro.tether.denied = true we default to no tethering
2682 // gservices could set the secure setting to 1 though to enable it on a build where it
2683 // had previously been turned off.
2684 public boolean isTetheringSupported() {
2685 enforceTetherAccessPermission();
2686 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002687 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002688 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2689 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002690 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2691 mTethering.getTetherableWifiRegexs().length != 0 ||
2692 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2693 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002694 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002695
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002696 // Called when we lose the default network and have no replacement yet.
2697 // This will automatically be cleared after X seconds or a new default network
2698 // becomes CONNECTED, whichever happens first. The timer is started by the
2699 // first caller and not restarted by subsequent callers.
2700 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002701 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002702 synchronized (this) {
2703 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002704 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002705 mNetTransitionWakeLock.acquire();
2706 mNetTransitionWakeLockCausedBy = forWhom;
2707 }
2708 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002709 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002710 mNetTransitionWakeLockTimeout);
2711 return;
2712 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002713
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002714 // 100 percent is full good, 0 is full bad.
2715 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002716 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002717 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002718 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002719 }
2720
Paul Jensenbfd17b72015-04-07 12:43:13 -04002721 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002722 enforceAccessPermission();
2723 enforceInternetPermission();
2724
Paul Jensenbfd17b72015-04-07 12:43:13 -04002725 NetworkAgentInfo nai;
2726 if (network == null) {
2727 nai = getDefaultNetwork();
2728 } else {
2729 nai = getNetworkAgentInfoForNetwork(network);
2730 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002731 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2732 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2733 return;
2734 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002735 // Revalidate if the app report does not match our current validated state.
2736 if (hasConnectivity == nai.lastValidated) return;
2737 final int uid = Binder.getCallingUid();
2738 if (DBG) {
2739 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2740 ") by " + uid);
2741 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002742 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002743 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2744 // which isn't meant to work on uncreated networks.
2745 if (!nai.created) return;
2746
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002747 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002748
2749 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2750 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002751 }
2752
Paul Jensen25a217c2015-02-27 22:55:47 -05002753 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2754 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2755 enforceConnectivityInternalPermission();
2756 }
2757 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2758 if (nai == null) return;
2759 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2760 actionToken);
2761 }
2762
Paul Jensencee9b512015-05-06 07:32:40 -04002763 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002764 // this information is already available as a world read/writable jvm property
2765 // so this API change wouldn't have a benifit. It also breaks the passing
2766 // of proxy info to all the JVMs.
2767 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002768 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002769 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002770 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2771 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002772 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002773 }
2774
Paul Jensencee9b512015-05-06 07:32:40 -04002775 public ProxyInfo getProxyForNetwork(Network network) {
2776 if (network == null) return getDefaultProxy();
2777 final ProxyInfo globalProxy = getGlobalProxy();
2778 if (globalProxy != null) return globalProxy;
2779 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2780 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2781 // caller may not have.
2782 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2783 if (nai == null) return null;
2784 synchronized (nai) {
2785 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2786 if (proxyInfo == null) return null;
2787 return new ProxyInfo(proxyInfo);
2788 }
2789 }
2790
Paul Jensene0bef712014-12-10 15:12:18 -05002791 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2792 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2793 // proxy is null then there is no proxy in place).
2794 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2795 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2796 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2797 proxy = null;
2798 }
2799 return proxy;
2800 }
2801
2802 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2803 // better for determining if a new proxy broadcast is necessary:
2804 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2805 // avoid unnecessary broadcasts.
2806 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2807 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2808 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2809 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2810 // all set.
2811 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2812 a = canonicalizeProxyInfo(a);
2813 b = canonicalizeProxyInfo(b);
2814 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2815 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2816 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2817 }
2818
Jason Monk207900c2014-04-25 15:00:09 -04002819 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002820 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002821
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002822 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002823 if (proxyProperties == mGlobalProxy) return;
2824 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2825 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2826
2827 String host = "";
2828 int port = 0;
2829 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002830 String pacFileUrl = "";
2831 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002832 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002833 if (!proxyProperties.isValid()) {
2834 if (DBG)
2835 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2836 return;
2837 }
Jason Monk207900c2014-04-25 15:00:09 -04002838 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002839 host = mGlobalProxy.getHost();
2840 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002841 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002842 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002843 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002844 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002845 } else {
2846 mGlobalProxy = null;
2847 }
2848 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002849 final long token = Binder.clearCallingIdentity();
2850 try {
2851 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2852 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2853 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2854 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002855 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002856 } finally {
2857 Binder.restoreCallingIdentity(token);
2858 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002859
Jason Monkcf0f97a2014-10-02 15:39:38 -04002860 if (mGlobalProxy == null) {
2861 proxyProperties = mDefaultProxy;
2862 }
2863 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002864 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002865 }
2866
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002867 private void loadGlobalProxy() {
2868 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002869 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2870 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2871 String exclList = Settings.Global.getString(res,
2872 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002873 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2874 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002875 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002876 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002877 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002878 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002879 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002880 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002881 if (!proxyProperties.isValid()) {
2882 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2883 return;
2884 }
2885
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002886 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002887 mGlobalProxy = proxyProperties;
2888 }
2889 }
2890 }
2891
Jason Monk207900c2014-04-25 15:00:09 -04002892 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002893 // this information is already available as a world read/writable jvm property
2894 // so this API change wouldn't have a benifit. It also breaks the passing
2895 // of proxy info to all the JVMs.
2896 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002897 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002898 return mGlobalProxy;
2899 }
2900 }
2901
Jason Monk207900c2014-04-25 15:00:09 -04002902 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002903 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002904 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002905 proxy = null;
2906 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002907 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002908 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002909 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002910 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002911 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2912 return;
2913 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002914
2915 // This call could be coming from the PacManager, containing the port of the local
2916 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2917 // global (to get the correct local port), and send a broadcast.
2918 // TODO: Switch PacManager to have its own message to send back rather than
2919 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002920 if ((mGlobalProxy != null) && (proxy != null)
2921 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002922 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2923 mGlobalProxy = proxy;
2924 sendProxyBroadcast(mGlobalProxy);
2925 return;
2926 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002927 mDefaultProxy = proxy;
2928
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002929 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002930 if (!mDefaultProxyDisabled) {
2931 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002932 }
2933 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002934 }
2935
Paul Jensene0bef712014-12-10 15:12:18 -05002936 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2937 // This method gets called when any network changes proxy, but the broadcast only ever contains
2938 // the default proxy (even if it hasn't changed).
2939 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2940 // world where an app might be bound to a non-default network.
2941 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2942 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2943 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2944
2945 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2946 sendProxyBroadcast(getDefaultProxy());
2947 }
2948 }
2949
Robert Greenwalt434203a2010-10-11 16:00:27 -07002950 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002951 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2952 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002953 if (!TextUtils.isEmpty(proxy)) {
2954 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002955 if (data.length == 0) {
2956 return;
2957 }
2958
Robert Greenwalt434203a2010-10-11 16:00:27 -07002959 String proxyHost = data[0];
2960 int proxyPort = 8080;
2961 if (data.length > 1) {
2962 try {
2963 proxyPort = Integer.parseInt(data[1]);
2964 } catch (NumberFormatException e) {
2965 return;
2966 }
2967 }
Jason Monk207900c2014-04-25 15:00:09 -04002968 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002969 setGlobalProxy(p);
2970 }
2971 }
2972
Jason Monk207900c2014-04-25 15:00:09 -04002973 private void sendProxyBroadcast(ProxyInfo proxy) {
2974 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002975 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002976 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002977 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002978 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2979 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002980 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002981 final long ident = Binder.clearCallingIdentity();
2982 try {
2983 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2984 } finally {
2985 Binder.restoreCallingIdentity(ident);
2986 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002987 }
2988
2989 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002990 final private HashMap<Uri, Integer> mUriEventMap;
2991 final private Context mContext;
2992 final private Handler mHandler;
2993
2994 SettingsObserver(Context context, Handler handler) {
2995 super(null);
2996 mUriEventMap = new HashMap<Uri, Integer>();
2997 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002998 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002999 }
3000
Erik Klineda4bfa82015-04-30 12:58:40 +09003001 void observe(Uri uri, int what) {
3002 mUriEventMap.put(uri, what);
3003 final ContentResolver resolver = mContext.getContentResolver();
3004 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003005 }
3006
3007 @Override
3008 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003009 Slog.wtf(TAG, "Should never be reached.");
3010 }
3011
3012 @Override
3013 public void onChange(boolean selfChange, Uri uri) {
3014 final Integer what = mUriEventMap.get(uri);
3015 if (what != null) {
3016 mHandler.obtainMessage(what.intValue()).sendToTarget();
3017 } else {
3018 loge("No matching event to send for URI=" + uri);
3019 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003020 }
3021 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003022
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003023 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003024 Slog.d(TAG, s);
3025 }
3026
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003027 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003028 Slog.e(TAG, s);
3029 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003030
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003031 private static <T> T checkNotNull(T value, String message) {
3032 if (value == null) {
3033 throw new NullPointerException(message);
3034 }
3035 return value;
3036 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003037
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003038 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003039 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003040 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3041 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3042 *
3043 * @param oldPackage Package name of the application which currently controls VPN, which will
3044 * be replaced. If there is no such application, this should should either be
3045 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3046 * @param newPackage Package name of the application which should gain control of VPN, or
3047 * {@code null} to disable.
3048 * @param userId User for whom to prepare the new VPN.
3049 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003050 * @hide
3051 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003052 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003053 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3054 int userId) {
3055 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003056 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003057
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003058 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003059 Vpn vpn = mVpns.get(userId);
3060 if (vpn != null) {
3061 return vpn.prepare(oldPackage, newPackage);
3062 } else {
3063 return false;
3064 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003065 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003066 }
3067
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003068 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003069 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3070 * This method is used by system-privileged apps.
3071 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3072 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3073 *
3074 * @param packageName The package for which authorization state should change.
3075 * @param userId User for whom {@code packageName} is installed.
3076 * @param authorized {@code true} if this app should be able to start a VPN connection without
3077 * explicit user approval, {@code false} if not.
3078 *
Jeff Davidson05542602014-08-11 14:07:27 -07003079 * @hide
3080 */
3081 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003082 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3083 enforceCrossUserPermission(userId);
3084
Jeff Davidson05542602014-08-11 14:07:27 -07003085 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003086 Vpn vpn = mVpns.get(userId);
3087 if (vpn != null) {
3088 vpn.setPackageAuthorization(packageName, authorized);
3089 }
Jeff Davidson05542602014-08-11 14:07:27 -07003090 }
3091 }
3092
3093 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003094 * Configure a TUN interface and return its file descriptor. Parameters
3095 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003096 * and not available in ConnectivityManager. Permissions are checked in
3097 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003098 * @hide
3099 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003100 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003101 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003102 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003103 int user = UserHandle.getUserId(Binder.getCallingUid());
3104 synchronized(mVpns) {
3105 return mVpns.get(user).establish(config);
3106 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003107 }
3108
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003109 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003110 * Start legacy VPN, controlling native daemons as needed. Creates a
3111 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003112 */
3113 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003114 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003115 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003116 final LinkProperties egress = getActiveLinkProperties();
3117 if (egress == null) {
3118 throw new IllegalStateException("Missing active network connection");
3119 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003120 int user = UserHandle.getUserId(Binder.getCallingUid());
3121 synchronized(mVpns) {
3122 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3123 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003124 }
3125
3126 /**
3127 * Return the information of the ongoing legacy VPN. This method is used
3128 * by VpnSettings and not available in ConnectivityManager. Permissions
3129 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003130 */
3131 @Override
3132 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003133 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003134 int user = UserHandle.getUserId(Binder.getCallingUid());
3135 synchronized(mVpns) {
3136 return mVpns.get(user).getLegacyVpnInfo();
3137 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003138 }
3139
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003140 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003141 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3142 * and not available in ConnectivityManager.
3143 */
3144 @Override
3145 public VpnInfo[] getAllVpnInfo() {
3146 enforceConnectivityInternalPermission();
3147 if (mLockdownEnabled) {
3148 return new VpnInfo[0];
3149 }
3150
3151 synchronized(mVpns) {
3152 List<VpnInfo> infoList = new ArrayList<>();
3153 for (int i = 0; i < mVpns.size(); i++) {
3154 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3155 if (info != null) {
3156 infoList.add(info);
3157 }
3158 }
3159 return infoList.toArray(new VpnInfo[infoList.size()]);
3160 }
3161 }
3162
3163 /**
3164 * @return VPN information for accounting, or null if we can't retrieve all required
3165 * information, e.g primary underlying iface.
3166 */
3167 @Nullable
3168 private VpnInfo createVpnInfo(Vpn vpn) {
3169 VpnInfo info = vpn.getVpnInfo();
3170 if (info == null) {
3171 return null;
3172 }
3173 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3174 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3175 // the underlyingNetworks list.
3176 if (underlyingNetworks == null) {
3177 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3178 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3179 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3180 }
3181 } else if (underlyingNetworks.length > 0) {
3182 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3183 if (linkProperties != null) {
3184 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3185 }
3186 }
3187 return info.primaryUnderlyingIface == null ? null : info;
3188 }
3189
3190 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003191 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3192 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003193 * Permissions are checked in Vpn class.
3194 * @hide
3195 */
3196 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003197 public VpnConfig getVpnConfig(int userId) {
3198 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003199 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003200 Vpn vpn = mVpns.get(userId);
3201 if (vpn != null) {
3202 return vpn.getVpnConfig();
3203 } else {
3204 return null;
3205 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003206 }
3207 }
3208
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003209 @Override
3210 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003211 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3212 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3213 return false;
3214 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003215
3216 // Tear down existing lockdown if profile was removed
3217 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3218 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003219 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003220 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3221 return false;
3222 }
3223
3224 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3225 final VpnProfile profile = VpnProfile.decode(
3226 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003227 int user = UserHandle.getUserId(Binder.getCallingUid());
3228 synchronized(mVpns) {
3229 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3230 profile));
3231 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003232 } else {
3233 setLockdownTracker(null);
3234 }
3235
3236 return true;
3237 }
3238
3239 /**
3240 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3241 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3242 */
3243 private void setLockdownTracker(LockdownVpnTracker tracker) {
3244 // Shutdown any existing tracker
3245 final LockdownVpnTracker existing = mLockdownTracker;
3246 mLockdownTracker = null;
3247 if (existing != null) {
3248 existing.shutdown();
3249 }
3250
3251 try {
3252 if (tracker != null) {
3253 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003254 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003255 mLockdownTracker = tracker;
3256 mLockdownTracker.init();
3257 } else {
3258 mNetd.setFirewallEnabled(false);
3259 }
3260 } catch (RemoteException e) {
3261 // ignored; NMS lives inside system_server
3262 }
3263 }
3264
3265 private void throwIfLockdownEnabled() {
3266 if (mLockdownEnabled) {
3267 throw new IllegalStateException("Unavailable in lockdown mode");
3268 }
3269 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003270
Wink Savilleab9321d2013-06-29 21:10:57 -07003271 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003272 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003273 // TODO: Remove? Any reason to trigger a provisioning check?
3274 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003275 }
3276
3277 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003278 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003279
Paul Jensen89e0f092014-09-15 15:59:36 -04003280 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003281 if (DBG) {
3282 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003283 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003284 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003285 Intent intent = new Intent(action);
3286 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003287 // Concatenate the range of types onto the range of NetIDs.
3288 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003289 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003290 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003291 }
3292
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003293 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003294 * Show or hide network provisioning notifications.
3295 *
3296 * We use notifications for two purposes: to notify that a network requires sign in
3297 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3298 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3299 * particular network we can display the notification type that was most recently requested.
3300 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3301 * might first display NO_INTERNET, and then when the captive portal check completes, display
3302 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003303 *
3304 * @param id an identifier that uniquely identifies this notification. This must match
3305 * between show and hide calls. We use the NetID value but for legacy callers
3306 * we concatenate the range of types with the range of NetIDs.
3307 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003308 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003309 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3310 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003311 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003312 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3313 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003314 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003315 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003316
3317 Resources r = Resources.getSystem();
3318 NotificationManager notificationManager = (NotificationManager) mContext
3319 .getSystemService(Context.NOTIFICATION_SERVICE);
3320
3321 if (visible) {
3322 CharSequence title;
3323 CharSequence details;
3324 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003325 if (notifyType == NotificationType.NO_INTERNET &&
3326 networkType == ConnectivityManager.TYPE_WIFI) {
3327 title = r.getString(R.string.wifi_no_internet, 0);
3328 details = r.getString(R.string.wifi_no_internet_detailed);
3329 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3330 } else if (notifyType == NotificationType.SIGN_IN) {
3331 switch (networkType) {
3332 case ConnectivityManager.TYPE_WIFI:
3333 title = r.getString(R.string.wifi_available_sign_in, 0);
3334 details = r.getString(R.string.network_available_sign_in_detailed,
3335 extraInfo);
3336 icon = R.drawable.stat_notify_wifi_in_range;
3337 break;
3338 case ConnectivityManager.TYPE_MOBILE:
3339 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3340 title = r.getString(R.string.network_available_sign_in, 0);
3341 // TODO: Change this to pull from NetworkInfo once a printable
3342 // name has been added to it
3343 details = mTelephonyManager.getNetworkOperatorName();
3344 icon = R.drawable.stat_notify_rssi_in_range;
3345 break;
3346 default:
3347 title = r.getString(R.string.network_available_sign_in, 0);
3348 details = r.getString(R.string.network_available_sign_in_detailed,
3349 extraInfo);
3350 icon = R.drawable.stat_notify_rssi_in_range;
3351 break;
3352 }
3353 } else {
3354 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3355 + getNetworkTypeName(networkType));
3356 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003357 }
3358
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003359 Notification notification = new Notification.Builder(mContext)
3360 .setWhen(0)
3361 .setSmallIcon(icon)
3362 .setAutoCancel(true)
3363 .setTicker(title)
3364 .setColor(mContext.getColor(
3365 com.android.internal.R.color.system_notification_accent_color))
3366 .setContentTitle(title)
3367 .setContentText(details)
3368 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003369 .setLocalOnly(true)
3370 .setPriority(highPriority ?
3371 Notification.PRIORITY_HIGH :
3372 Notification.PRIORITY_DEFAULT)
3373 .setDefaults(Notification.DEFAULT_ALL)
3374 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003375 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003376
Wink Saville948282b2013-08-29 08:55:16 -07003377 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003378 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003379 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003380 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003381 npe.printStackTrace();
3382 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003383 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003384 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003385 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003386 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003387 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003388 npe.printStackTrace();
3389 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003390 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003391 }
3392
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003393 /** Location to an updatable file listing carrier provisioning urls.
3394 * An example:
3395 *
3396 * <?xml version="1.0" encoding="utf-8"?>
3397 * <provisioningUrls>
3398 * <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 -07003399 * </provisioningUrls>
3400 */
3401 private static final String PROVISIONING_URL_PATH =
3402 "/data/misc/radio/provisioning_urls.xml";
3403 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003404
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003405 /** XML tag for root element. */
3406 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3407 /** XML tag for individual url */
3408 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003409 /** XML attribute for mcc */
3410 private static final String ATTR_MCC = "mcc";
3411 /** XML attribute for mnc */
3412 private static final String ATTR_MNC = "mnc";
3413
Paul Jensen434dde82015-06-11 09:43:30 -04003414 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003415 FileReader fileReader = null;
3416 XmlPullParser parser = null;
3417 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003418
3419 try {
3420 fileReader = new FileReader(mProvisioningUrlFile);
3421 parser = Xml.newPullParser();
3422 parser.setInput(fileReader);
3423 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3424
3425 while (true) {
3426 XmlUtils.nextElement(parser);
3427
3428 String element = parser.getName();
3429 if (element == null) break;
3430
Paul Jensen434dde82015-06-11 09:43:30 -04003431 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003432 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3433 try {
3434 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3435 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3436 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3437 parser.next();
3438 if (parser.getEventType() == XmlPullParser.TEXT) {
3439 return parser.getText();
3440 }
3441 }
3442 }
3443 } catch (NumberFormatException e) {
3444 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3445 }
3446 }
3447 }
3448 return null;
3449 } catch (FileNotFoundException e) {
3450 loge("Carrier Provisioning Urls file not found");
3451 } catch (XmlPullParserException e) {
3452 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3453 } catch (IOException e) {
3454 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3455 } finally {
3456 if (fileReader != null) {
3457 try {
3458 fileReader.close();
3459 } catch (IOException e) {}
3460 }
3461 }
3462 return null;
3463 }
3464
Wink Saville42d4f082013-07-20 20:31:59 -07003465 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003466 public String getMobileProvisioningUrl() {
3467 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003468 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003469 if (TextUtils.isEmpty(url)) {
3470 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003471 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003472 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003473 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003474 }
Wink Saville8cf35602013-07-10 23:00:07 -07003475 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003476 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003477 String phoneNumber = mTelephonyManager.getLine1Number();
3478 if (TextUtils.isEmpty(phoneNumber)) {
3479 phoneNumber = "0000000000";
3480 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003481 url = String.format(url,
3482 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3483 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003484 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003485 }
3486
Wink Savilleab9321d2013-06-29 21:10:57 -07003487 return url;
3488 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003489
Wink Saville948282b2013-08-29 08:55:16 -07003490 @Override
3491 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003492 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003493 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003494 final long ident = Binder.clearCallingIdentity();
3495 try {
3496 setProvNotificationVisible(visible, networkType, action);
3497 } finally {
3498 Binder.restoreCallingIdentity(ident);
3499 }
Wink Saville948282b2013-08-29 08:55:16 -07003500 }
Wink Saville7788c612013-08-29 14:57:08 -07003501
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003502 @Override
3503 public void setAirplaneMode(boolean enable) {
3504 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003505 final long ident = Binder.clearCallingIdentity();
3506 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003507 final ContentResolver cr = mContext.getContentResolver();
3508 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3509 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3510 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003511 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003512 } finally {
3513 Binder.restoreCallingIdentity(ident);
3514 }
3515 }
3516
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003517 private void onUserStart(int userId) {
3518 synchronized(mVpns) {
3519 Vpn userVpn = mVpns.get(userId);
3520 if (userVpn != null) {
3521 loge("Starting user already has a VPN");
3522 return;
3523 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003524 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003525 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003526 }
3527 }
3528
3529 private void onUserStop(int userId) {
3530 synchronized(mVpns) {
3531 Vpn userVpn = mVpns.get(userId);
3532 if (userVpn == null) {
3533 loge("Stopping user has no VPN");
3534 return;
3535 }
3536 mVpns.delete(userId);
3537 }
3538 }
3539
3540 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3541 @Override
3542 public void onReceive(Context context, Intent intent) {
3543 final String action = intent.getAction();
3544 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3545 if (userId == UserHandle.USER_NULL) return;
3546
3547 if (Intent.ACTION_USER_STARTING.equals(action)) {
3548 onUserStart(userId);
3549 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3550 onUserStop(userId);
3551 }
3552 }
3553 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003554
Robert Greenwalta67be032014-05-16 15:49:14 -07003555 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3556 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003557 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3558 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003559
Robert Greenwalta67be032014-05-16 15:49:14 -07003560 private static class NetworkFactoryInfo {
3561 public final String name;
3562 public final Messenger messenger;
3563 public final AsyncChannel asyncChannel;
3564
3565 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3566 this.name = name;
3567 this.messenger = messenger;
3568 this.asyncChannel = asyncChannel;
3569 }
3570 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003571
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003572 /**
3573 * Tracks info about the requester.
3574 * Also used to notice when the calling process dies so we can self-expire
3575 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003576 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3577 static final boolean REQUEST = true;
3578 static final boolean LISTEN = false;
3579
3580 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003581 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003582 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003583 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003584 final int mPid;
3585 final int mUid;
3586 final Messenger messenger;
3587 final boolean isRequest;
3588
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003589 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3590 request = r;
3591 mPendingIntent = pi;
3592 messenger = null;
3593 mBinder = null;
3594 mPid = getCallingPid();
3595 mUid = getCallingUid();
3596 this.isRequest = isRequest;
3597 }
3598
Robert Greenwalt9258c642014-03-26 16:47:06 -07003599 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3600 super();
3601 messenger = m;
3602 request = r;
3603 mBinder = binder;
3604 mPid = getCallingPid();
3605 mUid = getCallingUid();
3606 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003607 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003608
3609 try {
3610 mBinder.linkToDeath(this, 0);
3611 } catch (RemoteException e) {
3612 binderDied();
3613 }
3614 }
3615
3616 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003617 if (mBinder != null) {
3618 mBinder.unlinkToDeath(this, 0);
3619 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003620 }
3621
3622 public void binderDied() {
3623 log("ConnectivityService NetworkRequestInfo binderDied(" +
3624 request + ", " + mBinder + ")");
3625 releaseNetworkRequest(request);
3626 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003627
3628 public String toString() {
3629 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003630 mPid + " for " + request +
3631 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003632 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003633 }
3634
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003635 private void ensureImmutableCapabilities(NetworkCapabilities networkCapabilities) {
3636 if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
3637 throw new IllegalArgumentException(
3638 "Cannot request network with NET_CAPABILITY_VALIDATED");
3639 }
3640 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
3641 throw new IllegalArgumentException(
3642 "Cannot request network with NET_CAPABILITY_CAPTIVE_PORTAL");
3643 }
3644 }
3645
Robert Greenwalt9258c642014-03-26 16:47:06 -07003646 @Override
3647 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003648 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003649 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003650 enforceNetworkRequestPermissions(networkCapabilities);
3651 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003652 ensureImmutableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003653
Robert Greenwalt6078b502014-06-11 16:05:07 -07003654 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003655 throw new IllegalArgumentException("Bad timeout specified");
3656 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003657
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003658 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3659 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003660 if (DBG) log("requestNetwork for " + networkRequest);
3661 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3662 NetworkRequestInfo.REQUEST);
3663
3664 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003665 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003666 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003667 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003668 }
3669 return networkRequest;
3670 }
3671
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003672 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003673 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003674 enforceConnectivityInternalPermission();
3675 } else {
3676 enforceChangePermission();
3677 }
3678 }
3679
fenglub15e72b2015-03-20 11:29:56 -07003680 @Override
fengludb571472015-04-21 17:12:05 -07003681 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003682 enforceAccessPermission();
3683 NetworkAgentInfo nai = null;
3684 if (network == null) {
3685 return false;
3686 }
3687 synchronized (mNetworkForNetId) {
3688 nai = mNetworkForNetId.get(network.netId);
3689 }
3690 if (nai != null) {
3691 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3692 return true;
3693 }
3694 return false;
3695 }
3696
3697
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003698 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3699 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003700 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003701 final int uidRules;
3702 final int uid = Binder.getCallingUid();
3703 synchronized(mRulesLock) {
3704 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3705 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003706 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003707 // we could silently fail or we can filter the available nets to only give
3708 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003709 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003710 }
3711 }
3712 }
3713
Robert Greenwalt9258c642014-03-26 16:47:06 -07003714 @Override
3715 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3716 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003717 checkNotNull(operation, "PendingIntent cannot be null.");
3718 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3719 enforceNetworkRequestPermissions(networkCapabilities);
3720 enforceMeteredApnPolicy(networkCapabilities);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003721 ensureImmutableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003722
3723 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3724 nextNetworkRequestId());
3725 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3726 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3727 NetworkRequestInfo.REQUEST);
3728 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3729 nri));
3730 return networkRequest;
3731 }
3732
Jeremy Joslin79294842014-12-03 17:15:28 -08003733 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3734 mHandler.sendMessageDelayed(
3735 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3736 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3737 }
3738
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003739 @Override
3740 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003741 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003742 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3743 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003744 }
3745
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003746 // In order to implement the compatibility measure for pre-M apps that call
3747 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3748 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3749 // This ensures it has permission to do so.
3750 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3751 if (nc == null) {
3752 return false;
3753 }
3754 int[] transportTypes = nc.getTransportTypes();
3755 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3756 return false;
3757 }
3758 try {
3759 mContext.enforceCallingOrSelfPermission(
3760 android.Manifest.permission.ACCESS_WIFI_STATE,
3761 "ConnectivityService");
3762 } catch (SecurityException e) {
3763 return false;
3764 }
3765 return true;
3766 }
3767
Robert Greenwalt9258c642014-03-26 16:47:06 -07003768 @Override
3769 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3770 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003771 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3772 enforceAccessPermission();
3773 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003774
3775 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003776 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003777 if (DBG) log("listenForNetwork for " + networkRequest);
3778 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3779 NetworkRequestInfo.LISTEN);
3780
3781 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3782 return networkRequest;
3783 }
3784
3785 @Override
3786 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3787 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003788 checkNotNull(operation, "PendingIntent cannot be null.");
3789 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3790 enforceAccessPermission();
3791 }
3792
3793 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3794 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3795 if (DBG) log("pendingListenForNetwork for " + networkRequest + " to trigger " + operation);
3796 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3797 NetworkRequestInfo.LISTEN);
3798
3799 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003800 }
3801
3802 @Override
3803 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003804 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3805 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003806 }
3807
3808 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003809 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003810 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003811 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3812 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003813 }
3814
Robert Greenwalta67be032014-05-16 15:49:14 -07003815 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003816 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003817 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3818 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3819 }
3820
3821 @Override
3822 public void unregisterNetworkFactory(Messenger messenger) {
3823 enforceConnectivityInternalPermission();
3824 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3825 }
3826
3827 private void handleUnregisterNetworkFactory(Messenger messenger) {
3828 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3829 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003830 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003831 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003832 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003833 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003834 }
3835
Robert Greenwalt7b816022014-04-18 15:25:25 -07003836 /**
3837 * NetworkAgentInfo supporting a request by requestId.
3838 * These have already been vetted (their Capabilities satisfy the request)
3839 * and the are the highest scored network available.
3840 * the are keyed off the Requests requestId.
3841 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003842 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003843 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3844 new SparseArray<NetworkAgentInfo>();
3845
Paul Jensen31a94f42015-02-13 14:18:39 -05003846 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3847 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003848 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3849 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003850 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3851 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3852 // there may not be a strict 1:1 correlation between the two.
3853 @GuardedBy("mNetworkForNetId")
3854 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003855
Robert Greenwalt7b816022014-04-18 15:25:25 -07003856 // NetworkAgentInfo keyed off its connecting messenger
3857 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003858 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003859 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3860 new HashMap<Messenger, NetworkAgentInfo>();
3861
Paul Jensen2c311d62014-11-17 12:34:51 -05003862 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003863 private final NetworkRequest mDefaultRequest;
3864
Erik Klineda4bfa82015-04-30 12:58:40 +09003865 // Request used to optionally keep mobile data active even when higher
3866 // priority networks like Wi-Fi are active.
3867 private final NetworkRequest mDefaultMobileDataRequest;
3868
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003869 private NetworkAgentInfo getDefaultNetwork() {
3870 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3871 }
3872
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003873 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003874 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003875 }
3876
Paul Jensen31a94f42015-02-13 14:18:39 -05003877 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003878 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003879 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003880 enforceConnectivityInternalPermission();
3881
Paul Jensen2c311d62014-11-17 12:34:51 -05003882 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3883 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003884 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003885 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3886 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3887 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003888 synchronized (this) {
3889 nai.networkMonitor.systemReady = mSystemReady;
3890 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003891 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003892 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003893 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003894 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003895 }
3896
3897 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3898 if (VDBG) log("Got NetworkAgent Messenger");
3899 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003900 synchronized (mNetworkForNetId) {
3901 mNetworkForNetId.put(na.network.netId, na);
3902 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003903 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3904 NetworkInfo networkInfo = na.networkInfo;
3905 na.networkInfo = null;
3906 updateNetworkInfo(na, networkInfo);
3907 }
3908
3909 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3910 LinkProperties newLp = networkAgent.linkProperties;
3911 int netId = networkAgent.network.netId;
3912
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003913 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3914 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003915 if (networkAgent.clatd != null) {
3916 networkAgent.clatd.fixupLinkProperties(oldLp);
3917 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003918
Paul Jensen992f2522014-04-28 10:33:11 -04003919 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003920 updateMtu(newLp, oldLp);
3921 // TODO - figure out what to do for clat
3922// for (LinkProperties lp : newLp.getStackedLinks()) {
3923// updateMtu(lp, null);
3924// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003925 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003926
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003927 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3928 // In L, we used it only when the network had Internet access but provided no DNS servers.
3929 // For now, just disable it, and if disabling it doesn't break things, remove it.
3930 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3931 // NET_CAPABILITY_INTERNET);
3932 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003933 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003934 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3935
Paul Jensen3b759822014-05-13 11:44:01 -04003936 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003937 if (isDefaultNetwork(networkAgent)) {
3938 handleApplyDefaultProxy(newLp.getHttpProxy());
3939 } else {
3940 updateProxy(newLp, oldLp, networkAgent);
3941 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003942 // TODO - move this check to cover the whole function
3943 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003944 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003945 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3946 }
Paul Jensen3b759822014-05-13 11:44:01 -04003947 }
3948
Lorenzo Colitti95439462014-10-09 13:44:48 +09003949 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3950 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3951 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003952
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003953 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003954 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3955 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003956 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003957 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003958 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003959 }
Paul Jensen992f2522014-04-28 10:33:11 -04003960
3961 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3962 CompareResult<String> interfaceDiff = new CompareResult<String>();
3963 if (oldLp != null) {
3964 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3965 } else if (newLp != null) {
3966 interfaceDiff.added = newLp.getAllInterfaceNames();
3967 }
3968 for (String iface : interfaceDiff.added) {
3969 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003970 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003971 mNetd.addInterfaceToNetwork(iface, netId);
3972 } catch (Exception e) {
3973 loge("Exception adding interface: " + e);
3974 }
3975 }
3976 for (String iface : interfaceDiff.removed) {
3977 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003978 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003979 mNetd.removeInterfaceFromNetwork(iface, netId);
3980 } catch (Exception e) {
3981 loge("Exception removing interface: " + e);
3982 }
3983 }
3984 }
3985
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003986 /**
3987 * Have netd update routes from oldLp to newLp.
3988 * @return true if routes changed between oldLp and newLp
3989 */
3990 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003991 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3992 if (oldLp != null) {
3993 routeDiff = oldLp.compareAllRoutes(newLp);
3994 } else if (newLp != null) {
3995 routeDiff.added = newLp.getAllRoutes();
3996 }
3997
3998 // add routes before removing old in case it helps with continuous connectivity
3999
4000 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4001 for (RouteInfo route : routeDiff.added) {
4002 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004003 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004004 try {
4005 mNetd.addRoute(netId, route);
4006 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004007 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4008 loge("Exception in addRoute for non-gateway: " + e);
4009 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004010 }
4011 }
4012 for (RouteInfo route : routeDiff.added) {
4013 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004014 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004015 try {
4016 mNetd.addRoute(netId, route);
4017 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004018 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4019 loge("Exception in addRoute for gateway: " + e);
4020 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004021 }
4022 }
4023
4024 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004025 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004026 try {
4027 mNetd.removeRoute(netId, route);
4028 } catch (Exception e) {
4029 loge("Exception in removeRoute: " + e);
4030 }
4031 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004032 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004033 }
Erik Kline41368502015-06-17 13:19:54 +09004034
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004035 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4036 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004037 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09004038 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004039 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004040 dnses = new ArrayList();
4041 dnses.add(mDefaultDns);
4042 if (DBG) {
4043 loge("no dns provided for netId " + netId + ", so using defaults");
4044 }
4045 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004046 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004047 try {
4048 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4049 newLp.getDomains());
4050 } catch (Exception e) {
4051 loge("Exception in setDnsServersForNetwork: " + e);
4052 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004053 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
4054 if (defaultNai != null && defaultNai.network.netId == netId) {
4055 setDefaultDnsSystemProperties(dnses);
4056 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004057 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004058 } else if (flush) {
4059 try {
4060 mNetd.flushNetworkDnsCache(netId);
4061 } catch (Exception e) {
4062 loge("Exception in flushNetworkDnsCache: " + e);
4063 }
4064 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004065 }
4066 }
4067
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004068 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4069 int last = 0;
4070 for (InetAddress dns : dnses) {
4071 ++last;
4072 String key = "net.dns" + last;
4073 String value = dns.getHostAddress();
4074 SystemProperties.set(key, value);
4075 }
4076 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4077 String key = "net.dns" + i;
4078 SystemProperties.set(key, "");
4079 }
4080 mNumDnsEntries = last;
4081 }
4082
Paul Jensen3d194ea2015-06-16 14:27:36 -04004083 /**
4084 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4085 * augmented with any stateful capabilities implied from {@code networkAgent}
4086 * (e.g., validated status and captive portal status).
4087 *
4088 * @param networkAgent the network having its capabilities updated.
4089 * @param networkCapabilities the new network capabilities.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004090 * @param nascent indicates whether {@code networkAgent} was validated
4091 * (i.e. had everValidated set for the first time) immediately prior to this call.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004092 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07004093 private void updateCapabilities(NetworkAgentInfo networkAgent,
Paul Jensen1c7ba022015-06-16 14:27:36 -04004094 NetworkCapabilities networkCapabilities, NascentState nascent) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004095 // Don't modify caller's NetworkCapabilities.
4096 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4097 if (networkAgent.lastValidated) {
4098 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4099 } else {
4100 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4101 }
4102 if (networkAgent.lastCaptivePortalDetected) {
4103 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4104 } else {
4105 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4106 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004107 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
4108 synchronized (networkAgent) {
4109 networkAgent.networkCapabilities = networkCapabilities;
4110 }
Paul Jensen1c7ba022015-06-16 14:27:36 -04004111 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore(), nascent);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004112 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004113 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004114 }
4115
Paul Jensenc8b9a742014-09-30 15:37:41 -04004116 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4117 for (int i = 0; i < nai.networkRequests.size(); i++) {
4118 NetworkRequest nr = nai.networkRequests.valueAt(i);
4119 // Don't send listening requests to factories. b/17393458
4120 if (!isRequest(nr)) continue;
4121 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4122 }
4123 }
4124
Robert Greenwalt7b816022014-04-18 15:25:25 -07004125 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4126 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004127 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004128 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4129 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004130 }
4131 }
4132
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004133 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4134 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004135 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004136 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004137 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4138 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004139 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004140 sendIntent(nri.mPendingIntent, intent);
4141 }
4142 // else not handled
4143 }
4144
4145 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4146 mPendingIntentWakeLock.acquire();
4147 try {
4148 if (DBG) log("Sending " + pendingIntent);
4149 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4150 } catch (PendingIntent.CanceledException e) {
4151 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4152 mPendingIntentWakeLock.release();
4153 releasePendingNetworkRequest(pendingIntent);
4154 }
4155 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4156 }
4157
4158 @Override
4159 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4160 String resultData, Bundle resultExtras) {
4161 if (DBG) log("Finished sending " + pendingIntent);
4162 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004163 // Release with a delay so the receiving client has an opportunity to put in its
4164 // own request.
4165 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004166 }
4167
Robert Greenwalt9258c642014-03-26 16:47:06 -07004168 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004169 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004170 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004171 Bundle bundle = new Bundle();
4172 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4173 new NetworkRequest(nri.request));
4174 Message msg = Message.obtain();
4175 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4176 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4177 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4178 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004179 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004180 case ConnectivityManager.CALLBACK_LOSING: {
4181 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4182 break;
4183 }
4184 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4185 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4186 new NetworkCapabilities(networkAgent.networkCapabilities));
4187 break;
4188 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004189 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004190 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4191 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004192 break;
4193 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004195 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004196 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004197 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004198 if (VDBG) {
4199 log("sending notification " + notifyTypeToName(notificationType) +
4200 " for " + nri.request);
4201 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004202 nri.messenger.send(msg);
4203 } catch (RemoteException e) {
4204 // may occur naturally in the race of binder death.
4205 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4206 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004207 }
4208
Paul Jensenc8b9a742014-09-30 15:37:41 -04004209 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4210 for (int i = 0; i < nai.networkRequests.size(); i++) {
4211 NetworkRequest nr = nai.networkRequests.valueAt(i);
4212 // Ignore listening requests.
4213 if (!isRequest(nr)) continue;
4214 loge("Dead network still had at least " + nr);
4215 break;
4216 }
4217 nai.asyncChannel.disconnect();
4218 }
4219
Robert Greenwalt7b816022014-04-18 15:25:25 -07004220 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4221 if (oldNetwork == null) {
4222 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4223 return;
4224 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004225 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4226 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004227 }
4228
Paul Jensen27b02b72014-07-14 12:03:33 -04004229 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004230 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004231 setupDataActivityTracking(newNetwork);
4232 try {
4233 mNetd.setDefaultNetId(newNetwork.network.netId);
4234 } catch (Exception e) {
4235 loge("Exception setting default network :" + e);
4236 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004237 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004238 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004239 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004240 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004241 }
4242
Paul Jensen2161a8e2014-09-11 11:00:39 -04004243 // Handles a network appearing or improving its score.
4244 //
4245 // - Evaluates all current NetworkRequests that can be
4246 // satisfied by newNetwork, and reassigns to newNetwork
4247 // any such requests for which newNetwork is the best.
4248 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004249 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004250 // needed. A network is needed if it is the best network for
4251 // one or more NetworkRequests, or if it is a VPN.
4252 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004253 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004254 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4255 //
4256 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4257 // networks that have no chance (i.e. even if validated)
4258 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004259 //
4260 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4261 // it does not remove NetworkRequests that other Networks could better satisfy.
4262 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4263 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4264 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004265 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004266 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004267 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004268 // torn down if unneeded.
4269 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4270 // performed to tear down unvalidated networks that have no chance (i.e. even if
4271 // validated) of becoming the highest scoring network.
4272 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4273 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004274 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004275 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004276 loge("ERROR: nascent network not validated.");
4277 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004278 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004279 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004280 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004281 if (DBG) log("rematching " + newNetwork.name());
4282 // Find and migrate to this Network any NetworkRequests for
4283 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004284 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004285 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004286 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004287 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004288 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4289 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004290 if (DBG) {
4291 log("Network " + newNetwork.name() + " was already satisfying" +
4292 " request " + nri.request.requestId + ". No change.");
4293 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004294 keep = true;
4295 continue;
4296 }
4297
4298 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004299 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004300 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004301 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004302 // This is not a request, it's a callback listener.
4303 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004304 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004305 continue;
4306 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004307
Robert Greenwalt7b816022014-04-18 15:25:25 -07004308 // next check if it's better than any current network we're using for
4309 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004310 if (VDBG) {
4311 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004312 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4313 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004314 }
4315 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004316 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004317 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004318 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004319 currentNetwork.networkRequests.remove(nri.request.requestId);
4320 currentNetwork.networkLingered.add(nri.request);
4321 affectedNetworks.add(currentNetwork);
4322 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004323 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004324 }
Paul Jensen573a0352015-01-08 10:49:34 -05004325 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004326 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004327 if (!newNetwork.addRequest(nri.request)) {
4328 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4329 }
4330 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004331 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004332 // Tell NetworkFactories about the new score, so they can stop
4333 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004334 // TODO - this could get expensive if we have alot of requests for this
4335 // network. Think about if there is a way to reduce this. Push
4336 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004337 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004338 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004339 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004340 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004341 }
4342 }
4343 }
4344 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004345 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004346 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004347 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004348 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4349 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4350 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004351 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004352 }
4353 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004354 if (keep) {
4355 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004356 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004357 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004358 synchronized (ConnectivityService.this) {
4359 // have a new default network, release the transition wakelock in
4360 // a second if it's held. The second pause is to allow apps
4361 // to reconnect over the new network
4362 if (mNetTransitionWakeLock.isHeld()) {
4363 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4364 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4365 mNetTransitionWakeLockSerialNumber, 0),
4366 1000);
4367 }
4368 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004369 }
4370
4371 // do this after the default net is switched, but
4372 // before LegacyTypeTracker sends legacy broadcasts
Paul Jensen3d911462015-06-12 06:40:24 -04004373 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
Robert Greenwalt152ed372014-12-17 17:19:53 -08004374
4375 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004376 // Maintain the illusion: since the legacy API only
4377 // understands one network at a time, we must pretend
4378 // that the current default network disconnected before
4379 // the new one connected.
4380 if (oldDefaultNetwork != null) {
4381 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004382 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004383 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004384 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004385 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4386 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004387 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004388
4389 // Notify battery stats service about this network, both the normal
4390 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004391 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004392 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004393 final IBatteryStats bs = BatteryStatsService.getService();
4394 final int type = newNetwork.networkInfo.getType();
4395
4396 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4397 bs.noteNetworkInterfaceType(baseIface, type);
4398 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4399 final String stackedIface = stacked.getInterfaceName();
4400 bs.noteNetworkInterfaceType(stackedIface, type);
4401 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4402 }
4403 } catch (RemoteException ignored) {
4404 }
4405
Robert Greenwalt152ed372014-12-17 17:19:53 -08004406 // This has to happen after the notifyNetworkCallbacks as that tickles each
4407 // ConnectivityManager instance so that legacy requests correctly bind dns
4408 // requests to this network. The legacy users are listening for this bcast
4409 // and will generally do a dns request so they can ensureRouteToHost and if
4410 // they do that before the callbacks happen they'll use the default network.
4411 //
4412 // TODO: Is there still a race here? We send the broadcast
4413 // after sending the callback, but if the app can receive the
4414 // broadcast before the callback, it might still break.
4415 //
4416 // This *does* introduce a race where if the user uses the new api
4417 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4418 // they may get old info. Reverse this after the old startUsing api is removed.
4419 // This is on top of the multiple intent sequencing referenced in the todo above.
4420 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4421 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4422 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4423 // legacy type tracker filters out repeat adds
4424 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4425 }
4426 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004427
4428 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4429 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4430 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4431 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4432 if (newNetwork.isVPN()) {
4433 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4434 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004435 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004436 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004437 // validated (and get evaluated against peers, one losing here), or get reaped (see
4438 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4439 // network. Networks that have been up for a while and are validated should be torn
4440 // down via the lingering process so communication on that network is given time to
4441 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004442 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004443 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004444 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004445 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4446 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004447 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004448 if (DBG) log("Reaping " + nai.name());
4449 teardownUnneededNetwork(nai);
4450 }
4451 }
4452 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004453 }
4454
Paul Jensen1c7ba022015-06-16 14:27:36 -04004455 /**
4456 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4457 * being disconnected.
4458 * @param changed If only one Network's score or capabilities have been modified since the last
4459 * time this function was called, pass this Network in this argument, otherwise pass
4460 * null.
4461 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4462 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4463 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4464 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4465 * network's score.
4466 * @param nascent indicates if {@code changed} has just been validated.
4467 */
4468 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore,
4469 NascentState nascent) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004470 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4471 // to avoid the slowness. It is not simply enough to process just "changed", for
4472 // example in the case where "changed"'s score decreases and another network should begin
4473 // satifying a NetworkRequest that "changed" currently satisfies.
4474
4475 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4476 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4477 // rematchNetworkAndRequests() handles.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004478 if (changed != null &&
4479 (oldScore < changed.getCurrentScore() || nascent == NascentState.JUST_VALIDATED)) {
4480 rematchNetworkAndRequests(changed, nascent, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004481 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004482 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4483 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4484 NascentState.NOT_JUST_VALIDATED,
4485 // Only reap the last time through the loop. Reaping before all rematching
4486 // is complete could incorrectly teardown a network that hasn't yet been
4487 // rematched.
4488 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4489 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004490 }
4491 }
4492 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004493
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004494 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004495 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004496 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004497 // For now only update icons for default connection.
4498 // TODO: Update WiFi and cellular icons separately. b/17237507
4499 if (!isDefaultNetwork(nai)) return;
4500
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004501 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004502 // Don't repeat publish.
4503 if (newInetCondition == mDefaultInetConditionPublished) return;
4504
4505 mDefaultInetConditionPublished = newInetCondition;
4506 sendInetConditionBroadcast(nai.networkInfo);
4507 }
4508
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004509 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4510 if (mLockdownTracker != null) {
4511 if (nai != null && nai.isVPN()) {
4512 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4513 } else {
4514 mLockdownTracker.onNetworkInfoChanged();
4515 }
4516 }
4517 }
4518
Robert Greenwalt7b816022014-04-18 15:25:25 -07004519 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4520 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004521 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004522 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004523 synchronized (networkAgent) {
4524 oldInfo = networkAgent.networkInfo;
4525 networkAgent.networkInfo = newInfo;
4526 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004527 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004528
4529 if (oldInfo != null && oldInfo.getState() == state) {
4530 if (VDBG) log("ignoring duplicate network state non-change");
4531 return;
4532 }
4533 if (DBG) {
4534 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4535 (oldInfo == null ? "null" : oldInfo.getState()) +
4536 " to " + state);
4537 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004538
Paul Jenseneec75412014-08-04 12:21:19 -04004539 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004540 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004541 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004542 if (networkAgent.isVPN()) {
4543 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004544 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4545 (networkAgent.networkMisc == null ||
4546 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004547 } else {
4548 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4549 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004550 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004551 loge("Error creating network " + networkAgent.network.netId + ": "
4552 + e.getMessage());
4553 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004554 }
Paul Jenseneec75412014-08-04 12:21:19 -04004555 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004556 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004557 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004558
Paul Jensenca8f16a2014-05-09 12:47:55 -04004559 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004560 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004561
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004562 if (networkAgent.isVPN()) {
4563 // Temporarily disable the default proxy (not global).
4564 synchronized (mProxyLock) {
4565 if (!mDefaultProxyDisabled) {
4566 mDefaultProxyDisabled = true;
4567 if (mGlobalProxy == null && mDefaultProxy != null) {
4568 sendProxyBroadcast(null);
4569 }
4570 }
4571 }
4572 // TODO: support proxy per network.
4573 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004574
Paul Jensen2161a8e2014-09-11 11:00:39 -04004575 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004576 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4577 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004578
4579 // This has to happen after matching the requests, because callbacks are just requests.
4580 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004581 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004582 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004583 if (networkAgent.isVPN()) {
4584 synchronized (mProxyLock) {
4585 if (mDefaultProxyDisabled) {
4586 mDefaultProxyDisabled = false;
4587 if (mGlobalProxy == null && mDefaultProxy != null) {
4588 sendProxyBroadcast(mDefaultProxy);
4589 }
4590 }
4591 }
4592 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004593 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4594 state == NetworkInfo.State.SUSPENDED) {
4595 // going into or coming out of SUSPEND: rescore and notify
4596 if (networkAgent.getCurrentScore() != oldScore) {
4597 rematchAllNetworksAndRequests(networkAgent, oldScore,
4598 NascentState.NOT_JUST_VALIDATED);
4599 }
4600 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4601 ConnectivityManager.CALLBACK_SUSPENDED :
4602 ConnectivityManager.CALLBACK_RESUMED));
4603 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004604 }
4605 }
4606
Robert Greenwaltac96c522014-06-03 16:43:57 -07004607 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4608 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004609 if (score < 0) {
4610 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4611 "). Bumping score to min of 0");
4612 score = 0;
4613 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004614
Paul Jensen2161a8e2014-09-11 11:00:39 -04004615 final int oldScore = nai.getCurrentScore();
4616 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004617
Paul Jensen1c7ba022015-06-16 14:27:36 -04004618 rematchAllNetworksAndRequests(nai, oldScore, NascentState.NOT_JUST_VALIDATED);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004619
Paul Jensenc8b9a742014-09-30 15:37:41 -04004620 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004621 }
4622
Robert Greenwalt9258c642014-03-26 16:47:06 -07004623 // notify only this one new request of the current state
4624 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4625 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4626 // TODO - read state from monitor to decide what to send.
4627// if (nai.networkMonitor.isLingering()) {
4628// notifyType = NetworkCallbacks.LOSING;
4629// } else if (nai.networkMonitor.isEvaluating()) {
4630// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4631// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004632 if (nri.mPendingIntent == null) {
4633 callCallbackForRequest(nri, nai, notifyType);
4634 } else {
4635 sendPendingIntentForRequest(nri, nai, notifyType);
4636 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004637 }
4638
Robert Greenwalt8d482522015-06-24 13:23:42 -07004639 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004640 // The NetworkInfo we actually send out has no bearing on the real
4641 // state of affairs. For example, if the default connection is mobile,
4642 // and a request for HIPRI has just gone away, we need to pretend that
4643 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4644 // the state to DISCONNECTED, even though the network is of type MOBILE
4645 // and is still connected.
4646 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4647 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004648 if (state != DetailedState.DISCONNECTED) {
4649 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004650 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004651 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004652 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004653 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4654 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4655 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4656 if (info.isFailover()) {
4657 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4658 nai.networkInfo.setFailover(false);
4659 }
4660 if (info.getReason() != null) {
4661 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4662 }
4663 if (info.getExtraInfo() != null) {
4664 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4665 }
4666 NetworkAgentInfo newDefaultAgent = null;
4667 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4668 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4669 if (newDefaultAgent != null) {
4670 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4671 newDefaultAgent.networkInfo);
4672 } else {
4673 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4674 }
4675 }
4676 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4677 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004678 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004679 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004680 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004681 }
4682 }
4683 }
4684
Robert Greenwalt7b816022014-04-18 15:25:25 -07004685 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004686 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004687 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004688 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4689 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4690 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004691 if (nri.mPendingIntent == null) {
4692 callCallbackForRequest(nri, networkAgent, notifyType);
4693 } else {
4694 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4695 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004696 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004697 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004698
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004699 private String notifyTypeToName(int notifyType) {
4700 switch (notifyType) {
4701 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4702 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4703 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4704 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4705 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4706 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4707 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4708 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4709 }
4710 return "UNKNOWN";
4711 }
4712
Jeff Sharkey69736342014-12-08 14:50:12 -08004713 /**
4714 * Notify other system services that set of active ifaces has changed.
4715 */
4716 private void notifyIfacesChanged() {
4717 try {
4718 mStatsService.forceUpdateIfaces();
4719 } catch (Exception ignored) {
4720 }
4721 }
4722
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004723 @Override
4724 public boolean addVpnAddress(String address, int prefixLength) {
4725 throwIfLockdownEnabled();
4726 int user = UserHandle.getUserId(Binder.getCallingUid());
4727 synchronized (mVpns) {
4728 return mVpns.get(user).addAddress(address, prefixLength);
4729 }
4730 }
4731
4732 @Override
4733 public boolean removeVpnAddress(String address, int prefixLength) {
4734 throwIfLockdownEnabled();
4735 int user = UserHandle.getUserId(Binder.getCallingUid());
4736 synchronized (mVpns) {
4737 return mVpns.get(user).removeAddress(address, prefixLength);
4738 }
4739 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004740
4741 @Override
4742 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4743 throwIfLockdownEnabled();
4744 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004745 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004746 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004747 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004748 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004749 if (success) {
4750 notifyIfacesChanged();
4751 }
4752 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004753 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004754
4755 @Override
4756 public void factoryReset() {
4757 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004758
4759 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4760 return;
4761 }
4762
Robin Lee3b3dd942015-05-12 18:14:58 +01004763 final int userId = UserHandle.getCallingUserId();
4764
Stuart Scottf1fb3972015-04-02 18:00:02 -07004765 // Turn airplane mode off
4766 setAirplaneMode(false);
4767
Stuart Scotte3e314d2015-04-20 14:07:45 -07004768 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4769 // Untether
4770 for (String tether : getTetheredIfaces()) {
4771 untether(tether);
4772 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004773 }
4774
Stuart Scotte3e314d2015-04-20 14:07:45 -07004775 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4776 // Turn VPN off
4777 VpnConfig vpnConfig = getVpnConfig(userId);
4778 if (vpnConfig != null) {
4779 if (vpnConfig.legacy) {
4780 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4781 } else {
4782 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4783 // in the future without user intervention.
4784 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004785
Stuart Scotte3e314d2015-04-20 14:07:45 -07004786 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4787 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004788 }
4789 }
4790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004791}