blob: ed64c2b37a4a0849fcf14c950ccf5201f074cee7 [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;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080037import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070038import android.app.Notification;
39import android.app.NotificationManager;
40import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070041import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.ContentResolver;
43import android.content.Context;
44import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070045import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070047import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090048import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070049import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090051import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070053import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070054import android.net.INetworkPolicyListener;
55import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070056import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080057import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070058import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070059import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070060import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070061import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070062import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070064import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070065import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070066import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070067import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070068import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070069import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070070import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040071import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070072import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040073import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040074import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080076import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070077import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040078import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070080import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070081import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070082import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.Looper;
84import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070085import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070086import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070087import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070088import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070089import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070090import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070092import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040093import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070095import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070096import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070097import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070098import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070099import android.util.LocalLog;
100import android.util.LocalLog.ReadOnlyLocalLog;
101import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800102import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700103import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500104import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700105import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700106import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Wink Savilleab9321d2013-06-29 21:10:57 -0700108import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400109import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400110import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700111import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700112import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700113import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700114import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800115import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700116import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700117import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700118import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700119import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700120import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700121import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400122import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900123import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900124import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900125import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700126import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400127import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400128import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700129import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800130import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700131import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700132import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700133import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700134import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700135import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700136
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700137import org.xmlpull.v1.XmlPullParser;
138import org.xmlpull.v1.XmlPullParserException;
139
140import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700142import java.io.FileNotFoundException;
143import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700144import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700146import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700147import java.net.InetAddress;
148import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700149import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700150import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700151import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700152import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700153import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700154import java.util.HashSet;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900155import java.util.SortedSet;
156import java.util.TreeSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500157import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700158import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700159import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700160import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700161import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
163/**
164 * @hide
165 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800166public class ConnectivityService extends IConnectivityManager.Stub
167 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700168 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700170 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700171 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
Jake Hamby786e71a2014-02-06 14:43:50 -0800173 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700174
Jeff Sharkey899223b2012-08-04 15:24:58 -0700175 // TODO: create better separation between radio types and network types
176
Robert Greenwalt42acef32009-08-12 16:08:25 -0700177 // how long to wait before switching back to a radio's default network
178 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
179 // system property that can override the above value
180 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
181 "android.telephony.apn-restore";
182
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900183 // How long to wait before putting up a "This network doesn't have an Internet connection,
184 // connect anyway?" dialog after the user selects a network that doesn't validate.
185 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
186
Jeremy Joslin79294842014-12-03 17:15:28 -0800187 // How long to delay to removal of a pending intent based request.
188 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
189 private final int mReleasePendingIntentDelayMs;
190
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800191 private Tethering mTethering;
192
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700193 private final PermissionMonitor mPermissionMonitor;
194
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700195 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700196
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700197 @GuardedBy("mVpns")
198 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700199
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700200 private boolean mLockdownEnabled;
201 private LockdownVpnTracker mLockdownTracker;
202
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700203 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
204 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700205 /** Currently active network rules by UID. */
206 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700207 /** Set of ifaces that are costly. */
208 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700209
Erik Klineda4bfa82015-04-30 12:58:40 +0900210 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700212 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700213 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800215 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
217 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700218 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700220 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800221 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700223
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700224 private String mCurrentTcpBufferSizes;
225
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700226 private static final int ENABLED = 1;
227 private static final int DISABLED = 0;
228
Paul Jensenb10e37f2014-11-25 12:33:08 -0500229 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400230 // Tear down networks that have no chance (e.g. even if validated) of becoming
231 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500232 // all networks have been rematched against all NetworkRequests.
233 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400234 // Don't reap networks. This should be passed when some networks have not yet been
235 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500236 DONT_REAP
237 };
238
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700239 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700240 * used internally to change our mobile data enabled flag
241 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700242 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700243
244 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700245 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700246 * from one net to another. Clear happens when we get a new
247 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
248 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700249 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700250 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700251
Robert Greenwalt434203a2010-10-11 16:00:27 -0700252 /**
253 * used internally to reload global proxy settings
254 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700255 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700256
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700257 /**
Wink Saville628b0852011-08-04 15:01:58 -0700258 * used internally to send a sticky broadcast delayed.
259 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700260 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700261
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700262 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400263 * PAC manager has received new port.
264 */
265 private static final int EVENT_PROXY_HAS_CHANGED = 16;
266
Robert Greenwalte049c232014-04-11 15:53:27 -0700267 /**
268 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700269 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700270 */
271 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
272
Robert Greenwalt7b816022014-04-18 15:25:25 -0700273 /**
274 * used internally when registering NetworkAgents
275 * obj = Messenger
276 */
277 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
278
Robert Greenwalt9258c642014-03-26 16:47:06 -0700279 /**
280 * used to add a network request
281 * includes a NetworkRequestInfo
282 */
283 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
284
285 /**
286 * indicates a timeout period is over - check if we had a network yet or not
287 * and if not, call the timeout calback (but leave the request live until they
288 * cancel it.
289 * includes a NetworkRequestInfo
290 */
291 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
292
293 /**
294 * used to add a network listener - no request
295 * includes a NetworkRequestInfo
296 */
297 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
298
299 /**
300 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400301 * arg1 = UID of caller
302 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700303 */
304 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
305
Robert Greenwalta67be032014-05-16 15:49:14 -0700306 /**
307 * used internally when registering NetworkFactories
308 * obj = Messenger
309 */
310 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
311
Robert Greenwalt27711812014-06-25 16:45:57 -0700312 /**
313 * used internally to expire a wakelock when transitioning
314 * from one net to another. Expire happens when we fail to find
315 * a new network (typically after 1 minute) -
316 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
317 * a replacement network.
318 */
319 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
320
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700321 /**
322 * Used internally to indicate the system is ready.
323 */
324 private static final int EVENT_SYSTEM_READY = 25;
325
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800326 /**
327 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400328 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800329 */
330 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
331
332 /**
333 * used to remove a pending intent and its associated network request.
334 * arg1 = UID of caller
335 * obj = PendingIntent
336 */
337 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
338
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900339 /**
340 * used to specify whether a network should be used even if unvalidated.
341 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
342 * arg2 = whether to remember this choice in the future (1 or 0)
343 * obj = network
344 */
345 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
346
347 /**
348 * used to ask the user to confirm a connection to an unvalidated network.
349 * obj = network
350 */
351 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700352
Erik Klineda4bfa82015-04-30 12:58:40 +0900353 /**
354 * used internally to (re)configure mobile data always-on settings.
355 */
356 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
357
Paul Jensen694f2b82015-06-17 14:15:39 -0400358 /**
359 * used to add a network listener with a pending intent
360 * obj = NetworkRequestInfo
361 */
362 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
363
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900364 /** Handler thread used for both of the handlers below. */
365 @VisibleForTesting
366 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700367 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700368 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700369 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700370 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700371
Mike Lockwood0f79b542009-08-14 14:18:49 -0400372 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800373 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400374
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700375 private PowerManager.WakeLock mNetTransitionWakeLock;
376 private String mNetTransitionWakeLockCausedBy = "";
377 private int mNetTransitionWakeLockSerialNumber;
378 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800379 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700380
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700381 private InetAddress mDefaultDns;
382
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700383 // used in DBG mode to track inet condition reports
384 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
385 private ArrayList mInetLog;
386
Robert Greenwalt434203a2010-10-11 16:00:27 -0700387 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400388 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700389 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700390 private boolean mDefaultProxyDisabled = false;
391
Robert Greenwalt434203a2010-10-11 16:00:27 -0700392 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400393 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700394
Jason Monk602b2322013-07-03 17:04:33 -0400395 private PacManager mPacManager = null;
396
Erik Klineda4bfa82015-04-30 12:58:40 +0900397 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700398
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400399 private UserManager mUserManager;
400
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700401 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700402 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700403
Robert Greenwalt50393202011-06-21 17:26:14 -0700404 // the set of network types that can only be enabled by system/sig apps
405 List mProtectedNetworks;
406
John Spurlockbf991a82013-06-24 14:20:23 -0400407 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700408
Wink Savilleab9321d2013-06-29 21:10:57 -0700409 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400410
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900411 private KeepaliveTracker mKeepaliveTracker;
412
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700413 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
414 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700415 private final static int MAX_NET_ID = 65535;
416 private int mNextNetId = MIN_NET_ID;
417
Robert Greenwalt34524f02014-05-18 16:22:10 -0700418 // sequence number of NetworkRequests
419 private int mNextNetworkRequestId = 1;
420
Erik Kline7523eb32015-07-09 18:24:03 +0900421 // NetworkRequest activity String log entries.
422 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
423 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
424
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700425 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
426 private static final int MAX_VALIDATION_LOGS = 10;
427 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
428 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
429
430 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
431 synchronized(mValidationLogs) {
432 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
433 mValidationLogs.removeLast();
434 }
435 mValidationLogs.addFirst(new Pair(network, log));
436 }
437 }
438
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700439 /**
440 * Implements support for the legacy "one network per network type" model.
441 *
442 * We used to have a static array of NetworkStateTrackers, one for each
443 * network type, but that doesn't work any more now that we can have,
444 * for example, more that one wifi network. This class stores all the
445 * NetworkAgentInfo objects that support a given type, but the legacy
446 * API will only see the first one.
447 *
448 * It serves two main purposes:
449 *
450 * 1. Provide information about "the network for a given type" (since this
451 * API only supports one).
452 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
453 * the first network for a given type changes, or if the default network
454 * changes.
455 */
456 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900457
458 private static final boolean DBG = true;
459 private static final boolean VDBG = false;
460 private static final String TAG = "CSLegacyTypeTracker";
461
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700462 /**
463 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
464 * Each list holds references to all NetworkAgentInfos that are used to
465 * satisfy requests for that network type.
466 *
467 * This array is built out at startup such that an unsupported network
468 * doesn't get an ArrayList instance, making this a tristate:
469 * unsupported, supported but not active and active.
470 *
471 * The actual lists are populated when we scan the network types that
472 * are supported on this device.
473 */
474 private ArrayList<NetworkAgentInfo> mTypeLists[];
475
476 public LegacyTypeTracker() {
477 mTypeLists = (ArrayList<NetworkAgentInfo>[])
478 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
479 }
480
481 public void addSupportedType(int type) {
482 if (mTypeLists[type] != null) {
483 throw new IllegalStateException(
484 "legacy list for type " + type + "already initialized");
485 }
486 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
487 }
488
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700489 public boolean isTypeSupported(int type) {
490 return isNetworkTypeValid(type) && mTypeLists[type] != null;
491 }
492
493 public NetworkAgentInfo getNetworkForType(int type) {
494 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
495 return mTypeLists[type].get(0);
496 } else {
497 return null;
498 }
499 }
500
Robert Greenwalt8d482522015-06-24 13:23:42 -0700501 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900502 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900503 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700504 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900505 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900506 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900507 }
508 }
509
510 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700511 public void add(int type, NetworkAgentInfo nai) {
512 if (!isTypeSupported(type)) {
513 return; // Invalid network type.
514 }
515 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
516
517 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
518 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700519 return;
520 }
521
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900522 list.add(nai);
523
524 // 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 +0900525 final boolean isDefaultNetwork = isDefaultNetwork(nai);
526 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700527 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
528 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700529 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700530 }
531
Lorenzo Colittia793a672014-07-31 23:20:17 +0900532 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900534 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
535 if (list == null || list.isEmpty()) {
536 return;
537 }
538
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900539 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900540
541 if (!list.remove(nai)) {
542 return;
543 }
544
Robert Greenwalt8d482522015-06-24 13:23:42 -0700545 final DetailedState state = DetailedState.DISCONNECTED;
546
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900547 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700548 maybeLogBroadcast(nai, state, type, wasDefault);
549 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900550 }
551
552 if (!list.isEmpty() && wasFirstNetwork) {
553 if (DBG) log("Other network available for type " + type +
554 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900555 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700556 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
557 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900558 }
559 }
560
561 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900562 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
563 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700564 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900565 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700566 }
567 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700568
Robert Greenwalt8d482522015-06-24 13:23:42 -0700569 // send out another legacy broadcast - currently only used for suspend/unsuspend
570 // toggle
571 public void update(NetworkAgentInfo nai) {
572 final boolean isDefault = isDefaultNetwork(nai);
573 final DetailedState state = nai.networkInfo.getDetailedState();
574 for (int type = 0; type < mTypeLists.length; type++) {
575 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700576 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700578 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700579 maybeLogBroadcast(nai, state, type, isDefault);
580 sendLegacyNetworkBroadcast(nai, state, type);
581 }
582 }
583 }
584
Lorenzo Colittia793a672014-07-31 23:20:17 +0900585 private String naiToString(NetworkAgentInfo nai) {
586 String name = (nai != null) ? nai.name() : "null";
587 String state = (nai.networkInfo != null) ?
588 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
589 "???/???";
590 return name + " " + state;
591 }
592
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700593 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900594 pw.println("mLegacyTypeTracker:");
595 pw.increaseIndent();
596 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700597 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900598 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700599 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900600 pw.println();
601 pw.println("Current state:");
602 pw.increaseIndent();
603 for (int type = 0; type < mTypeLists.length; type++) {
604 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
605 for (NetworkAgentInfo nai : mTypeLists[type]) {
606 pw.println(type + " " + naiToString(nai));
607 }
608 }
609 pw.decreaseIndent();
610 pw.decreaseIndent();
611 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700612 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900613
614 // This class needs its own log method because it has a different TAG.
615 private void log(String s) {
616 Slog.d(TAG, s);
617 }
618
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700619 }
620 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
621
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900622 @VisibleForTesting
623 protected HandlerThread createHandlerThread() {
624 return new HandlerThread("ConnectivityServiceThread");
625 }
626
Jeff Sharkey899223b2012-08-04 15:24:58 -0700627 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700628 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800629 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800630
Erik Klineda4bfa82015-04-30 12:58:40 +0900631 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900632 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
633 new Binder(), NetworkRequestInfo.REQUEST);
634 mNetworkRequests.put(mDefaultRequest, defaultNRI);
635 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900636
637 mDefaultMobileDataRequest = createInternetRequestForTransport(
638 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700639
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900640 mHandlerThread = createHandlerThread();
641 mHandlerThread.start();
642 mHandler = new InternalHandler(mHandlerThread.getLooper());
643 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700644
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800645 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800646 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
647 String id = Settings.Secure.getString(context.getContentResolver(),
648 Settings.Secure.ANDROID_ID);
649 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700650 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800651 SystemProperties.set("net.hostname", name);
652 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800653 }
654
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700655 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700656 String dns = Settings.Global.getString(context.getContentResolver(),
657 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700658 if (dns == null || dns.length() == 0) {
659 dns = context.getResources().getString(
660 com.android.internal.R.string.config_default_dns_server);
661 }
662 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800663 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
664 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800665 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700666 }
667
Jeremy Joslin79294842014-12-03 17:15:28 -0800668 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
669 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
670
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700671 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700672 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800673 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700674 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700675 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700676 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700677
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700678 try {
679 mPolicyManager.registerListener(mPolicyListener);
680 } catch (RemoteException e) {
681 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700682 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700683 }
684
685 final PowerManager powerManager = (PowerManager) context.getSystemService(
686 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700687 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
688 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
689 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800690 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700691
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700692 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700693
Wink Saville51f456f2013-04-23 14:26:51 -0700694 // TODO: What is the "correct" way to do determine if this is a wifi only device?
695 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
696 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700697 String[] naStrings = context.getResources().getStringArray(
698 com.android.internal.R.array.networkAttributes);
699 for (String naString : naStrings) {
700 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700701 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700702 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700703 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800704 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700705 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700706 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700707 }
Wink Saville51f456f2013-04-23 14:26:51 -0700708 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
709 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
710 n.type);
711 continue;
712 }
Wink Saville975c8482011-04-07 14:23:45 -0700713 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800714 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700715 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700716 continue;
717 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700718 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700719
Wink Saville975c8482011-04-07 14:23:45 -0700720 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700721 mNetworksDefined++;
722 } catch(Exception e) {
723 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700724 }
725 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700726
727 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
728 if (mNetConfigs[TYPE_VPN] == null) {
729 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
730 // don't need to add TYPE_VPN to mNetConfigs.
731 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
732 mNetworksDefined++; // used only in the log() statement below.
733 }
734
Wink Saville5e56bc52013-07-29 15:00:57 -0700735 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700736
Robert Greenwalt50393202011-06-21 17:26:14 -0700737 mProtectedNetworks = new ArrayList<Integer>();
738 int[] protectedNetworks = context.getResources().getIntArray(
739 com.android.internal.R.array.config_protectedNetworks);
740 for (int p : protectedNetworks) {
741 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
742 mProtectedNetworks.add(p);
743 } else {
744 if (DBG) loge("Ignoring protectedNetwork " + p);
745 }
746 }
747
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700748 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
749 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700750
Robert Greenwaltfab501672014-07-23 11:44:01 -0700751 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800752
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700753 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
754
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700755 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700756 IntentFilter intentFilter = new IntentFilter();
757 intentFilter.addAction(Intent.ACTION_USER_STARTING);
758 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700759 intentFilter.addAction(Intent.ACTION_USER_ADDED);
760 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700761 mContext.registerReceiverAsUser(
762 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900763
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700764 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700765 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700766 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700767 } catch (RemoteException e) {
768 loge("Error registering observer :" + e);
769 }
770
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700771 if (DBG) {
772 mInetLog = new ArrayList();
773 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700774
Erik Klineda4bfa82015-04-30 12:58:40 +0900775 mSettingsObserver = new SettingsObserver(mContext, mHandler);
776 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800777
John Spurlockbf991a82013-06-24 14:20:23 -0400778 mDataConnectionStats = new DataConnectionStats(mContext);
779 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400780
Jason Monkdecd2952013-10-10 14:02:51 -0400781 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700782
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400783 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900784
785 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700787
Erik Klineda4bfa82015-04-30 12:58:40 +0900788 private NetworkRequest createInternetRequestForTransport(int transportType) {
789 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900790 netCap.addCapability(NET_CAPABILITY_INTERNET);
791 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900792 if (transportType > -1) {
793 netCap.addTransportType(transportType);
794 }
795 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
796 }
797
798 private void handleMobileDataAlwaysOn() {
799 final boolean enable = (Settings.Global.getInt(
800 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
801 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
802 if (enable == isEnabled) {
803 return; // Nothing to do.
804 }
805
806 if (enable) {
807 handleRegisterNetworkRequest(new NetworkRequestInfo(
808 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
809 } else {
810 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
811 }
812 }
813
814 private void registerSettingsCallbacks() {
815 // Watch for global HTTP proxy changes.
816 mSettingsObserver.observe(
817 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
818 EVENT_APPLY_GLOBAL_HTTP_PROXY);
819
820 // Watch for whether or not to keep mobile data always on.
821 mSettingsObserver.observe(
822 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
823 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
824 }
825
Robert Greenwalt34524f02014-05-18 16:22:10 -0700826 private synchronized int nextNetworkRequestId() {
827 return mNextNetworkRequestId++;
828 }
829
Paul Jensen67b0b072015-06-10 11:22:17 -0400830 @VisibleForTesting
831 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400832 synchronized (mNetworkForNetId) {
833 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
834 int netId = mNextNetId;
835 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
836 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500837 if (!mNetIdInUse.get(netId)) {
838 mNetIdInUse.put(netId, true);
839 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400840 }
841 }
842 }
843 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700844 }
845
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800846 private NetworkState getFilteredNetworkState(int networkType, int uid) {
847 NetworkInfo info = null;
848 LinkProperties lp = null;
849 NetworkCapabilities nc = null;
850 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800851 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800852
853 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
854 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
855 if (nai != null) {
856 synchronized (nai) {
857 info = new NetworkInfo(nai.networkInfo);
858 lp = new LinkProperties(nai.linkProperties);
859 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400860 // Network objects are outwardly immutable so there is no point to duplicating.
861 // Duplicating also precludes sharing socket factories and connection pools.
862 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800863 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800864 }
865 info.setType(networkType);
866 } else {
867 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
868 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
869 info.setIsAvailable(true);
870 lp = new LinkProperties();
871 nc = new NetworkCapabilities();
872 network = null;
873 }
874 info = getFilteredNetworkInfo(info, lp, uid);
875 }
876
Jeff Sharkey32566012014-12-02 18:30:14 -0800877 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400878 }
879
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800880 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
881 if (network == null) {
882 return null;
883 }
884 synchronized (mNetworkForNetId) {
885 return mNetworkForNetId.get(network.netId);
886 }
887 };
888
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900889 private Network[] getVpnUnderlyingNetworks(int uid) {
890 if (!mLockdownEnabled) {
891 int user = UserHandle.getUserId(uid);
892 synchronized (mVpns) {
893 Vpn vpn = mVpns.get(user);
894 if (vpn != null && vpn.appliesToUid(uid)) {
895 return vpn.getUnderlyingNetworks();
896 }
897 }
898 }
899 return null;
900 }
901
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800902 private NetworkState getUnfilteredActiveNetworkState(int uid) {
903 NetworkInfo info = null;
904 LinkProperties lp = null;
905 NetworkCapabilities nc = null;
906 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800907 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800908
Paul Jensen85cf78e2015-06-25 13:25:07 -0400909 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800910
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900911 final Network[] networks = getVpnUnderlyingNetworks(uid);
912 if (networks != null) {
913 // getUnderlyingNetworks() returns:
914 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
915 // empty array => the VPN explicitly said "no default network".
916 // non-empty array => the VPN specified one or more default networks; we use the
917 // first one.
918 if (networks.length > 0) {
919 nai = getNetworkAgentInfoForNetwork(networks[0]);
920 } else {
921 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800922 }
923 }
924
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800925 if (nai != null) {
926 synchronized (nai) {
927 info = new NetworkInfo(nai.networkInfo);
928 lp = new LinkProperties(nai.linkProperties);
929 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400930 // Network objects are outwardly immutable so there is no point to duplicating.
931 // Duplicating also precludes sharing socket factories and connection pools.
932 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800933 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 }
935 }
936
Jeff Sharkey32566012014-12-02 18:30:14 -0800937 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400938 }
939
940 /**
941 * Check if UID should be blocked from using the network with the given LinkProperties.
942 */
943 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700944 final boolean networkCostly;
945 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700946
Robert Greenwalt12e67352014-05-13 21:41:06 -0700947 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700948 synchronized (mRulesLock) {
949 networkCostly = mMeteredIfaces.contains(iface);
950 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700951 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700952
Jeff Sharkeydc988062015-09-14 10:09:47 -0700953 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700954 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700955 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
956 return true;
957 } else {
958 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700959 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700960 }
961
962 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700963 * Return a filtered {@link NetworkInfo}, potentially marked
964 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800965 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700966 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800967 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
968 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400969 // network is blocked; clone and override state
970 info = new NetworkInfo(info);
971 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900972 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900973 log("returning Blocked NetworkInfo for ifname=" +
974 lp.getInterfaceName() + ", uid=" + uid);
975 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700976 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800977 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700978 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900979 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700980 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700981 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700982 }
983
984 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 * Return NetworkInfo for the active (i.e., connected) network interface.
986 * It is assumed that at most one network is active at a time. If more
987 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700988 * @return the info for the active network, or {@code null} if none is
989 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700991 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700993 enforceAccessPermission();
994 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800995 NetworkState state = getUnfilteredActiveNetworkState(uid);
996 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 }
998
Paul Jensen31a94f42015-02-13 14:18:39 -0500999 @Override
1000 public Network getActiveNetwork() {
1001 enforceAccessPermission();
1002 final int uid = Binder.getCallingUid();
1003 final int user = UserHandle.getUserId(uid);
1004 int vpnNetId = NETID_UNSET;
1005 synchronized (mVpns) {
1006 final Vpn vpn = mVpns.get(user);
1007 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1008 }
1009 NetworkAgentInfo nai;
1010 if (vpnNetId != NETID_UNSET) {
1011 synchronized (mNetworkForNetId) {
1012 nai = mNetworkForNetId.get(vpnNetId);
1013 }
1014 if (nai != null) return nai.network;
1015 }
1016 nai = getDefaultNetwork();
1017 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1018 return nai != null ? nai.network : null;
1019 }
1020
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001021 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1022 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001023 final int uid = Binder.getCallingUid();
1024 NetworkState state = getUnfilteredActiveNetworkState(uid);
1025 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001026 }
1027
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001028 @Override
1029 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1030 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001031 NetworkState state = getUnfilteredActiveNetworkState(uid);
1032 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001033 }
1034
1035 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 public NetworkInfo getNetworkInfo(int networkType) {
1037 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001038 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001039 if (getVpnUnderlyingNetworks(uid) != null) {
1040 // A VPN is active, so we may need to return one of its underlying networks. This
1041 // information is not available in LegacyTypeTracker, so we have to get it from
1042 // getUnfilteredActiveNetworkState.
1043 NetworkState state = getUnfilteredActiveNetworkState(uid);
1044 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1045 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1046 }
1047 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001048 NetworkState state = getFilteredNetworkState(networkType, uid);
1049 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001052 @Override
1053 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1054 enforceAccessPermission();
1055 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001056 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001057 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1058 if (nai != null) {
1059 synchronized (nai) {
1060 info = new NetworkInfo(nai.networkInfo);
1061 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001062 }
1063 }
1064 return info;
1065 }
1066
1067 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 public NetworkInfo[] getAllNetworkInfo() {
1069 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001070 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001071 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1072 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001073 NetworkInfo info = getNetworkInfo(networkType);
1074 if (info != null) {
1075 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001078 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 }
1080
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001081 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001082 public Network getNetworkForType(int networkType) {
1083 enforceAccessPermission();
1084 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001085 NetworkState state = getFilteredNetworkState(networkType, uid);
1086 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1087 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001088 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001089 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001090 }
1091
1092 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001093 public Network[] getAllNetworks() {
1094 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001095 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001096 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001097 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001098 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001099 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001100 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001101 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001102 }
1103
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001104 @Override
1105 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1106 // The basic principle is: if an app's traffic could possibly go over a
1107 // network, without the app doing anything multinetwork-specific,
1108 // (hence, by "default"), then include that network's capabilities in
1109 // the array.
1110 //
1111 // In the normal case, app traffic only goes over the system's default
1112 // network connection, so that's the only network returned.
1113 //
1114 // With a VPN in force, some app traffic may go into the VPN, and thus
1115 // over whatever underlying networks the VPN specifies, while other app
1116 // traffic may go over the system default network (e.g.: a split-tunnel
1117 // VPN, or an app disallowed by the VPN), so the set of networks
1118 // returned includes the VPN's underlying networks and the system
1119 // default.
1120 enforceAccessPermission();
1121
1122 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1123
1124 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001125 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001126 if (nc != null) {
1127 result.put(nai.network, nc);
1128 }
1129
1130 if (!mLockdownEnabled) {
1131 synchronized (mVpns) {
1132 Vpn vpn = mVpns.get(userId);
1133 if (vpn != null) {
1134 Network[] networks = vpn.getUnderlyingNetworks();
1135 if (networks != null) {
1136 for (Network network : networks) {
1137 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001138 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001139 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001140 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001141 }
1142 }
1143 }
1144 }
1145 }
1146 }
1147
1148 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1149 out = result.values().toArray(out);
1150 return out;
1151 }
1152
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001153 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001154 public boolean isNetworkSupported(int networkType) {
1155 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001156 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001157 }
1158
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001159 /**
1160 * Return LinkProperties for the active (i.e., connected) default
1161 * network interface. It is assumed that at most one default network
1162 * is active at a time. If more than one is active, it is indeterminate
1163 * which will be returned.
1164 * @return the ip properties for the active network, or {@code null} if
1165 * none is active
1166 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001167 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001168 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001169 enforceAccessPermission();
1170 final int uid = Binder.getCallingUid();
1171 NetworkState state = getUnfilteredActiveNetworkState(uid);
1172 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001173 }
1174
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001175 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001176 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001177 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001178 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1179 if (nai != null) {
1180 synchronized (nai) {
1181 return new LinkProperties(nai.linkProperties);
1182 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001183 }
1184 return null;
1185 }
1186
Robert Greenwalt12e67352014-05-13 21:41:06 -07001187 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001188 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001189 public LinkProperties getLinkProperties(Network network) {
1190 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001191 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001192 if (nai != null) {
1193 synchronized (nai) {
1194 return new LinkProperties(nai.linkProperties);
1195 }
1196 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001197 return null;
1198 }
1199
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001200 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001201 if (nai != null) {
1202 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001203 if (nai.networkCapabilities != null) {
1204 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001205 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001206 }
1207 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001208 return null;
1209 }
1210
1211 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001212 public NetworkCapabilities getNetworkCapabilities(Network network) {
1213 enforceAccessPermission();
1214 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1215 }
1216
1217 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001218 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001219 // Require internal since we're handing out IMSI details
1220 enforceConnectivityInternalPermission();
1221
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001222 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001223 for (Network network : getAllNetworks()) {
1224 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1225 if (nai != null) {
1226 synchronized (nai) {
1227 final String subscriberId = (nai.networkMisc != null)
1228 ? nai.networkMisc.subscriberId : null;
1229 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1230 nai.networkCapabilities, network, subscriberId, null));
1231 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001232 }
1233 }
1234 return result.toArray(new NetworkState[result.size()]);
1235 }
1236
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001237 @Override
1238 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1239 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001240 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001241 final long token = Binder.clearCallingIdentity();
1242 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1244 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001245 try {
1246 return mPolicyManager.getNetworkQuotaInfo(state);
1247 } catch (RemoteException e) {
1248 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001249 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001250 return null;
1251 } finally {
1252 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001253 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001254 }
1255
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001256 @Override
1257 public boolean isActiveNetworkMetered() {
1258 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001259 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001260 final long token = Binder.clearCallingIdentity();
1261 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001262 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001263 } finally {
1264 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001265 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001266 }
1267
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001268 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1269 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1270 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001271 try {
1272 return mPolicyManager.isNetworkMetered(state);
1273 } catch (RemoteException e) {
1274 }
1275 }
1276 return false;
1277 }
1278
Jeff Sharkey216c1812012-08-05 14:29:23 -07001279 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1280 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001281 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001282 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001283 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001284 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001285 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001286
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001287 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 * Ensure that a network route exists to deliver traffic to the specified
1289 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001290 * @param networkType the type of the network over which traffic to the
1291 * specified host is to be routed
1292 * @param hostAddress the IP address of the host to which the route is
1293 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 * @return {@code true} on success, {@code false} on failure
1295 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001296 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001298 if (mProtectedNetworks.contains(networkType)) {
1299 enforceConnectivityInternalPermission();
1300 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001301
Chad Brubakerc0234532014-02-14 13:24:29 -08001302 InetAddress addr;
1303 try {
1304 addr = InetAddress.getByAddress(hostAddress);
1305 } catch (UnknownHostException e) {
1306 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1307 return false;
1308 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001311 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 return false;
1313 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001314
1315 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1316 if (nai == null) {
1317 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1318 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1319 } else {
1320 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1321 }
1322 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001323 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001324
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001325 DetailedState netState;
1326 synchronized (nai) {
1327 netState = nai.networkInfo.getDetailedState();
1328 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001329
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001330 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001331 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001332 log("requestRouteToHostAddress on down network "
1333 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001334 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001335 }
1336 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001338
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001339 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001340 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001341 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001342 LinkProperties lp;
1343 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001344 synchronized (nai) {
1345 lp = nai.linkProperties;
1346 netId = nai.network.netId;
1347 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001348 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001349 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1350 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001351 } finally {
1352 Binder.restoreCallingIdentity(token);
1353 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001354 }
1355
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001356 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001357 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001358 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001359 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001360 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001361 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001362 if (bestRoute.getGateway().equals(addr)) {
1363 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001364 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001365 } else {
1366 // if we will connect to this through another route, add a direct route
1367 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001368 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001369 }
1370 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001371 if (DBG) log("Adding legacy route " + bestRoute +
1372 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001373 try {
1374 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1375 } catch (Exception e) {
1376 // never crash - catch them all
1377 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001378 return false;
1379 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001380 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 }
1382
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001383 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1384 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001385 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001386 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001387 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001388 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001389 }
1390
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001391 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001392 // skip update when we've already applied rules
1393 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1394 if (oldRules == uidRules) return;
1395
1396 mUidRules.put(uid, uidRules);
1397 }
1398
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001399 // TODO: notify UID when it has requested targeted updates
1400 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001401
1402 @Override
1403 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001404 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001405 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001406 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001407 }
1408
1409 synchronized (mRulesLock) {
1410 mMeteredIfaces.clear();
1411 for (String iface : meteredIfaces) {
1412 mMeteredIfaces.add(iface);
1413 }
1414 }
1415 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001416
1417 @Override
1418 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1419 // caller is NPMS, since we only register with them
1420 if (LOGD_RULES) {
1421 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1422 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001423 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001424 };
1425
Robin Lee3b3dd942015-05-12 18:14:58 +01001426 /**
1427 * Require that the caller is either in the same user or has appropriate permission to interact
1428 * across users.
1429 *
1430 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1431 */
1432 private void enforceCrossUserPermission(int userId) {
1433 if (userId == UserHandle.getCallingUserId()) {
1434 // Not a cross-user call.
1435 return;
1436 }
1437 mContext.enforceCallingOrSelfPermission(
1438 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1439 "ConnectivityService");
1440 }
1441
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001442 private void enforceInternetPermission() {
1443 mContext.enforceCallingOrSelfPermission(
1444 android.Manifest.permission.INTERNET,
1445 "ConnectivityService");
1446 }
1447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001449 mContext.enforceCallingOrSelfPermission(
1450 android.Manifest.permission.ACCESS_NETWORK_STATE,
1451 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 }
1453
1454 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001455 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 }
1457
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001458 private void enforceTetherAccessPermission() {
1459 mContext.enforceCallingOrSelfPermission(
1460 android.Manifest.permission.ACCESS_NETWORK_STATE,
1461 "ConnectivityService");
1462 }
1463
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001464 private void enforceConnectivityInternalPermission() {
1465 mContext.enforceCallingOrSelfPermission(
1466 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1467 "ConnectivityService");
1468 }
1469
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001470 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001471 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001472 }
1473
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001474 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001475 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001476 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001477 }
1478
1479 private void sendInetConditionBroadcast(NetworkInfo info) {
1480 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1481 }
1482
Wink Saville628b0852011-08-04 15:01:58 -07001483 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001484 if (mLockdownTracker != null) {
1485 info = mLockdownTracker.augmentNetworkInfo(info);
1486 }
1487
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001488 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001489 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001490 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 if (info.isFailover()) {
1492 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1493 info.setFailover(false);
1494 }
1495 if (info.getReason() != null) {
1496 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1497 }
1498 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001499 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1500 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001502 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001503 return intent;
1504 }
1505
1506 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1507 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1508 }
1509
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001510 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001511 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1512 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1513 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001514 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001515 final long ident = Binder.clearCallingIdentity();
1516 try {
1517 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1518 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1519 } finally {
1520 Binder.restoreCallingIdentity(ident);
1521 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001522 }
1523
Mike Lockwood0f79b542009-08-14 14:18:49 -04001524 private void sendStickyBroadcast(Intent intent) {
1525 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001526 if (!mSystemReady) {
1527 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001528 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001529 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001530 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001531 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001532 }
1533
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001534 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001535 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001536 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001537 final NetworkInfo ni = intent.getParcelableExtra(
1538 ConnectivityManager.EXTRA_NETWORK_INFO);
1539 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1540 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1541 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001542 } else {
1543 BroadcastOptions opts = BroadcastOptions.makeBasic();
1544 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1545 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001546 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001547 final IBatteryStats bs = BatteryStatsService.getService();
1548 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001549 bs.noteConnectivityChanged(intent.getIntExtra(
1550 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1551 ni != null ? ni.getState().toString() : "?");
1552 } catch (RemoteException e) {
1553 }
1554 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001555 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001556 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001557 } finally {
1558 Binder.restoreCallingIdentity(ident);
1559 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001560 }
1561 }
1562
1563 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001564 loadGlobalProxy();
1565
Mike Lockwood0f79b542009-08-14 14:18:49 -04001566 synchronized(this) {
1567 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001568 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001569 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001570 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001571 }
1572 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001573 // load the global proxy at startup
1574 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001575
1576 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1577 // for user to unlock device.
1578 if (!updateLockdownVpn()) {
1579 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1580 mContext.registerReceiver(mUserPresentReceiver, filter);
1581 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001582
Erik Klineda4bfa82015-04-30 12:58:40 +09001583 // Configure whether mobile data is always on.
1584 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1585
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001586 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001587
1588 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001591 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1592 @Override
1593 public void onReceive(Context context, Intent intent) {
1594 // Try creating lockdown tracker, since user present usually means
1595 // unlocked keystore.
1596 if (updateLockdownVpn()) {
1597 mContext.unregisterReceiver(this);
1598 }
1599 }
1600 };
1601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001603 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001604 *
1605 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001606 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001607 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001608 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1609 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001610
1611 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001612 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001613
Robert Greenwalt7b816022014-04-18 15:25:25 -07001614 if (networkAgent.networkCapabilities.hasTransport(
1615 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001616 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1617 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001618 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001619 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001620 } else if (networkAgent.networkCapabilities.hasTransport(
1621 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001622 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1623 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001624 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001625 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001626 } else {
1627 // do not track any other networks
1628 timeout = 0;
1629 }
1630
Robert Greenwalt7b816022014-04-18 15:25:25 -07001631 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001632 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001633 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001634 } catch (Exception e) {
1635 // You shall not crash!
1636 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001637 }
1638 }
1639 }
1640
1641 /**
1642 * Remove data activity tracking when network disconnects.
1643 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001644 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1645 final String iface = networkAgent.linkProperties.getInterfaceName();
1646 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001647
Robert Greenwalt7b816022014-04-18 15:25:25 -07001648 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1649 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001650 try {
1651 // the call fails silently if no idletimer setup for this interface
1652 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001653 } catch (Exception e) {
1654 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001655 }
1656 }
1657 }
1658
1659 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001660 * Reads the network specific MTU size from reources.
1661 * and set it on it's iface.
1662 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001663 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1664 final String iface = newLp.getInterfaceName();
1665 final int mtu = newLp.getMtu();
1666 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1667 if (VDBG) log("identical MTU - not setting");
1668 return;
1669 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001670
Robert Greenwalt43074032014-08-15 17:53:05 -07001671 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001672 loge("Unexpected mtu value: " + mtu + ", " + iface);
1673 return;
1674 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001675
w1997615afd812014-08-05 15:18:11 -07001676 // Cannot set MTU without interface name
1677 if (TextUtils.isEmpty(iface)) {
1678 loge("Setting MTU size with null iface.");
1679 return;
1680 }
1681
Robert Greenwalt7b816022014-04-18 15:25:25 -07001682 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001683 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001684 mNetd.setMtu(iface, mtu);
1685 } catch (Exception e) {
1686 Slog.e(TAG, "exception in setMtu()" + e);
1687 }
1688 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001689
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001690 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001691 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1692
1693 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001694 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001695 protected int getDefaultTcpRwnd() {
1696 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1697 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001698
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001699 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1700 if (isDefaultNetwork(nai) == false) {
1701 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001702 }
1703
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001704 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1705 String[] values = null;
1706 if (tcpBufferSizes != null) {
1707 values = tcpBufferSizes.split(",");
1708 }
1709
1710 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001711 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001712 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1713 values = tcpBufferSizes.split(",");
1714 }
1715
1716 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1717
1718 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001719 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001720
1721 final String prefix = "/sys/kernel/ipv4/tcp_";
1722 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1723 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1724 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1725 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1726 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1727 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1728 mCurrentTcpBufferSizes = tcpBufferSizes;
1729 } catch (IOException e) {
1730 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001731 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001732
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001733 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001734 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001735 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1736 if (rwndValue != 0) {
1737 SystemProperties.set(sysctlKey, rwndValue.toString());
1738 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001739 }
1740
Mattias Falk8b47b362011-08-23 14:15:13 +02001741 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001742 /*
1743 * Tell the VMs to toss their DNS caches
1744 */
1745 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1746 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001747 /*
1748 * Connectivity events can happen before boot has completed ...
1749 */
1750 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001751 final long ident = Binder.clearCallingIdentity();
1752 try {
1753 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1754 } finally {
1755 Binder.restoreCallingIdentity(ident);
1756 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001757 }
1758
Robert Greenwalt562cc542014-05-15 18:07:26 -07001759 @Override
1760 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001761 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1762 NETWORK_RESTORE_DELAY_PROP_NAME);
1763 if(restoreDefaultNetworkDelayStr != null &&
1764 restoreDefaultNetworkDelayStr.length() != 0) {
1765 try {
1766 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1767 } catch (NumberFormatException e) {
1768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001770 // if the system property isn't set, use the value for the apn type
1771 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1772
1773 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1774 (mNetConfigs[networkType] != null)) {
1775 ret = mNetConfigs[networkType].restoreTime;
1776 }
1777 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 }
1779
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001780 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001781 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001782 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001783 }
1784 return false;
1785 }
1786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001788 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1789 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001790 if (mContext.checkCallingOrSelfPermission(
1791 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001793 pw.println("Permission Denial: can't dump ConnectivityService " +
1794 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1795 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 return;
1797 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001798
Erik Kline379747a2015-06-05 17:47:34 +09001799 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001800 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001801 final long DIAG_TIME_MS = 5000;
1802 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1803 // Start gathering diagnostic information.
1804 netDiags.add(new NetworkDiagnostics(
1805 nai.network,
Lorenzo Colitti87cfc702015-07-27 16:35:33 +09001806 new LinkProperties(nai.linkProperties), // Must be a copy.
Erik Kline379747a2015-06-05 17:47:34 +09001807 DIAG_TIME_MS));
1808 }
1809
1810 for (NetworkDiagnostics netDiag : netDiags) {
1811 pw.println();
1812 netDiag.waitForMeasurements();
1813 netDiag.dump(pw);
1814 }
1815
1816 return;
1817 }
1818
Lorenzo Colittie3805462015-06-03 11:18:24 +09001819 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001820 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001821 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001822 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001823 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001824 pw.println();
1825
Paul Jensen85cf78e2015-06-25 13:25:07 -04001826 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001827 pw.print("Active default network: ");
1828 if (defaultNai == null) {
1829 pw.println("none");
1830 } else {
1831 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001833 pw.println();
1834
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001835 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001836 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001837 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1838 pw.println(nai.toString());
1839 pw.increaseIndent();
1840 pw.println("Requests:");
1841 pw.increaseIndent();
1842 for (int i = 0; i < nai.networkRequests.size(); i++) {
1843 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001844 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001845 pw.decreaseIndent();
1846 pw.println("Lingered:");
1847 pw.increaseIndent();
1848 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1849 pw.decreaseIndent();
1850 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001851 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001852 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001853 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001854
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001855 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001856 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001857 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1858 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001859 }
1860 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001861 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001862
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001863 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001864
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001865 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001866 pw.print("mNetTransitionWakeLock: currently " +
1867 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1868 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1869 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1870 } else {
1871 pw.println(", last requested never");
1872 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001873 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001874
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001875 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001876 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001877
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001878 pw.println();
1879 mKeepaliveTracker.dump(pw);
1880
Lorenzo Colittie3805462015-06-03 11:18:24 +09001881 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001882 pw.println();
1883 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001884 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001885 for(int i = 0; i < mInetLog.size(); i++) {
1886 pw.println(mInetLog.get(i));
1887 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001888 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001889 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001890
1891 if (argsContain(args, "--short") == false) {
1892 pw.println();
1893 synchronized (mValidationLogs) {
1894 pw.println("mValidationLogs (most recent first):");
1895 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1896 pw.println(p.first);
1897 pw.increaseIndent();
1898 p.second.dump(fd, pw, args);
1899 pw.decreaseIndent();
1900 }
1901 }
Erik Kline7523eb32015-07-09 18:24:03 +09001902
1903 pw.println();
1904 pw.println("mNetworkRequestInfoLogs (most recent first):");
1905 pw.increaseIndent();
1906 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1907 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
1910
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001911 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001912 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001913 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001914 if (officialNai != null && officialNai.equals(nai)) return true;
1915 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001916 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001917 " - " + nai);
1918 }
1919 return false;
1920 }
1921
Paul Jensenc8b9a742014-09-30 15:37:41 -04001922 private boolean isRequest(NetworkRequest request) {
1923 return mNetworkRequests.get(request).isRequest;
1924 }
1925
Robert Greenwalt42acef32009-08-12 16:08:25 -07001926 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001927 private class NetworkStateTrackerHandler extends Handler {
1928 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001929 super(looper);
1930 }
1931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 @Override
1933 public void handleMessage(Message msg) {
1934 NetworkInfo info;
1935 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001936 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001937 handleAsyncChannelHalfConnect(msg);
1938 break;
1939 }
1940 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1941 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1942 if (nai != null) nai.asyncChannel.disconnect();
1943 break;
1944 }
1945 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1946 handleAsyncChannelDisconnected(msg);
1947 break;
1948 }
1949 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1950 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1951 if (nai == null) {
1952 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1953 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001954 final NetworkCapabilities networkCapabilities =
1955 (NetworkCapabilities)msg.obj;
1956 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1957 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001958 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Paul Jensen1c7ba022015-06-16 14:27:36 -04001959 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001960 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1961 networkCapabilities)) {
1962 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1963 + nai.networkCapabilities + " -> " + networkCapabilities);
1964 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001965 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001966 }
1967 break;
1968 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001969 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1970 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1971 if (nai == null) {
1972 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1973 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001974 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001975 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001976 "; created=" + nai.created);
1977 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001978 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001979 synchronized (nai) {
1980 nai.linkProperties = (LinkProperties)msg.obj;
1981 }
Paul Jenseneec75412014-08-04 12:21:19 -04001982 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001983 }
1984 break;
1985 }
1986 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1987 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1988 if (nai == null) {
1989 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1990 break;
1991 }
1992 info = (NetworkInfo) msg.obj;
1993 updateNetworkInfo(nai, info);
1994 break;
1995 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001996 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1997 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1998 if (nai == null) {
1999 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
2000 break;
2001 }
2002 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002003 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002004 break;
2005 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002006 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
2007 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2008 if (nai == null) {
2009 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
2010 break;
2011 }
2012 try {
2013 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002014 } catch (Exception e) {
2015 // Never crash!
2016 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002017 }
2018 break;
2019 }
2020 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2021 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2022 if (nai == null) {
2023 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
2024 break;
2025 }
2026 try {
2027 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002028 } catch (Exception e) {
2029 // Never crash!
2030 loge("Exception in removeVpnUidRanges: " + e);
2031 }
2032 break;
2033 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002034 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2035 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2036 if (nai == null) {
2037 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
2038 break;
2039 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002040 if (nai.created && !nai.networkMisc.explicitlySelected) {
2041 loge("ERROR: created network explicitly selected.");
2042 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002043 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002044 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002045 break;
2046 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002047 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2048 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2049 if (nai == null) {
2050 loge("EVENT_PACKET_KEEPALIVE from unknown NetworkAgent");
2051 break;
2052 }
2053 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2054 break;
2055 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002056 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002057 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002058 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2059 final boolean valid =
2060 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002061 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2062 if (valid != nai.lastValidated) {
2063 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002064 nai.lastValidated = valid;
2065 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002066 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002067 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2068 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002069 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002070 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002071 // Let the NetworkAgent know the state of its network
2072 nai.asyncChannel.sendMessage(
2073 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2074 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2075 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002076 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002077 break;
2078 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002079 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002080 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002081 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2082 handleLingerComplete(nai);
2083 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002084 break;
2085 }
Paul Jensen869868be2014-05-15 10:33:05 -04002086 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002087 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002088 final boolean visible = (msg.arg1 != 0);
2089 final NetworkAgentInfo nai;
2090 synchronized (mNetworkForNetId) {
2091 nai = mNetworkForNetId.get(netId);
2092 }
2093 // If captive portal status has changed, update capabilities.
2094 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2095 nai.lastCaptivePortalDetected = visible;
2096 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002097 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002098 }
2099 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002100 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002101 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002102 if (nai == null) {
2103 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2104 break;
2105 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002106 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002107 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2108 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002109 }
Paul Jensen869868be2014-05-15 10:33:05 -04002110 break;
2111 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002112 }
2113 }
2114 }
2115
Paul Jensen85cf78e2015-06-25 13:25:07 -04002116 private void linger(NetworkAgentInfo nai) {
2117 nai.lingering = true;
2118 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2119 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2120 }
2121
Paul Jensen0cc17322014-11-25 15:26:53 -05002122 // Cancel any lingering so the linger timeout doesn't teardown a network.
2123 // This should be called when a network begins satisfying a NetworkRequest.
2124 // Note: depending on what state the NetworkMonitor is in (e.g.,
2125 // if it's awaiting captive portal login, or if validation failed), this
2126 // may trigger a re-evaluation of the network.
2127 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002128 nai.networkLingered.clear();
2129 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002130 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002131 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002132 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2133 }
2134
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 private void handleAsyncChannelHalfConnect(Message msg) {
2136 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002137 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002138 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2139 if (VDBG) log("NetworkFactory connected");
2140 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002141 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002142 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002143 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002144 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002145 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002146 }
2147 } else {
2148 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002149 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 }
2151 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2152 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2153 if (VDBG) log("NetworkAgent connected");
2154 // A network agent has requested a connection. Establish the connection.
2155 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2156 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2157 } else {
2158 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002159 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002160 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002161 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002162 synchronized (mNetworkForNetId) {
2163 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002164 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002165 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002166 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002167 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002168 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002169 }
2170 }
2171 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002172
Robert Greenwalt7b816022014-04-18 15:25:25 -07002173 private void handleAsyncChannelDisconnected(Message msg) {
2174 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2175 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002176 if (DBG) {
2177 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2178 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002179 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002180 // TODO - if we move the logic to the network agent (have them disconnect
2181 // because they lost all their requests or because their score isn't good)
2182 // then they would disconnect organically, report their new state and then
2183 // disconnect the channel.
2184 if (nai.networkInfo.isConnected()) {
2185 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2186 null, null);
2187 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002188 final boolean wasDefault = isDefaultNetwork(nai);
2189 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002190 mDefaultInetConditionPublished = 0;
2191 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002192 notifyIfacesChanged();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002193 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2194 // by other networks that are already connected. Perhaps that can be done by
2195 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2196 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002197 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002198 mKeepaliveTracker.handleStopAllKeepalives(nai,
2199 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002200 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002201 mNetworkAgentInfos.remove(msg.replyTo);
2202 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002203 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002204 // Remove the NetworkAgent, but don't mark the netId as
2205 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002206 mNetworkForNetId.remove(nai.network.netId);
2207 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002208 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002209 for (int i = 0; i < nai.networkRequests.size(); i++) {
2210 NetworkRequest request = nai.networkRequests.valueAt(i);
2211 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2212 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2213 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002214 sendUpdatedScoreToFactories(request, 0);
2215 }
2216 }
2217 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2218 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002219 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002220 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002221 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002222 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002223 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002224 if (nai.created) {
2225 // Tell netd to clean up the configuration for this network
2226 // (routing rules, DNS, etc).
2227 // This may be slow as it requires a lot of netd shelling out to ip and
2228 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2229 // after we've rematched networks with requests which should make a potential
2230 // fallback network the default or requested a new network from the
2231 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2232 // long time.
2233 try {
2234 mNetd.removeNetwork(nai.network.netId);
2235 } catch (Exception e) {
2236 loge("Exception removing network: " + e);
2237 }
2238 }
2239 synchronized (mNetworkForNetId) {
2240 mNetIdInUse.delete(nai.network.netId);
2241 }
2242 } else {
2243 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2244 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002245 }
2246 }
2247
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002248 // If this method proves to be too slow then we can maintain a separate
2249 // pendingIntent => NetworkRequestInfo map.
2250 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2251 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2252 Intent intent = pendingIntent.getIntent();
2253 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2254 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2255 if (existingPendingIntent != null &&
2256 existingPendingIntent.getIntent().filterEquals(intent)) {
2257 return entry.getValue();
2258 }
2259 }
2260 return null;
2261 }
2262
2263 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2264 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2265
2266 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2267 if (existingRequest != null) { // remove the existing request.
2268 if (DBG) log("Replacing " + existingRequest.request + " with "
2269 + nri.request + " because their intents matched.");
2270 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2271 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002272 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002273 }
2274
Erik Klineda4bfa82015-04-30 12:58:40 +09002275 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002276 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002277 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002278 if (!nri.isRequest) {
2279 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002280 if (nri.request.networkCapabilities.hasSignalStrength() &&
2281 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2282 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002283 }
2284 }
2285 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002286 rematchAllNetworksAndRequests(null, 0);
2287 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2288 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002289 }
2290 }
2291
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002292 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2293 int callingUid) {
2294 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2295 if (nri != null) {
2296 handleReleaseNetworkRequest(nri.request, callingUid);
2297 }
2298 }
2299
Paul Jensen99364842014-12-09 11:43:45 -05002300 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002301 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2302 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002303 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002304 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002305 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2306 // If this Network is already the highest scoring Network for a request, or if
2307 // there is hope for it to become one if it validated, then it is needed.
2308 if (nri.isRequest && nai.satisfies(nri.request) &&
2309 (nai.networkRequests.get(nri.request.requestId) != null ||
2310 // Note that this catches two important cases:
2311 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2312 // is currently satisfying the request. This is desirable when
2313 // cellular ends up validating but WiFi does not.
2314 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002315 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002316 // WiFi ends up validating and out scoring cellular.
2317 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2318 nai.getCurrentScoreAsValidated())) {
2319 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002320 }
2321 }
Paul Jensene0988542015-06-25 15:30:08 -04002322 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002323 }
2324
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002325 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2326 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002327 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002328 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002329 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2330 return;
2331 }
2332 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002333 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002334 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002335 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002336 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002337 // Find all networks that are satisfying this request and remove the request
2338 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002339 // TODO - it's my understanding that for a request there is only a single
2340 // network satisfying it, so this loop is wasteful
2341 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002342 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2343 if (nai.networkRequests.get(nri.request.requestId) != null) {
2344 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002345 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002346 log(" Removing from current network " + nai.name() +
2347 ", leaving " + nai.networkRequests.size() +
2348 " requests.");
2349 }
Paul Jensen99364842014-12-09 11:43:45 -05002350 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002351 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002352 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002353 } else {
2354 // suspect there should only be one pass through here
2355 // but if any were kept do the check below
2356 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002357 }
2358 }
2359 }
2360
Robert Greenwalt51481852015-01-08 14:43:31 -08002361 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2362 if (nai != null) {
2363 mNetworkForRequestId.remove(nri.request.requestId);
2364 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002365 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002366 // that a network connected to serve it, even though the network was already
2367 // connected. Now that this request has gone away, we might have to pretend
2368 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002369 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002370 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2371 boolean doRemove = true;
2372 if (wasKept) {
2373 // check if any of the remaining requests for this network are for the
2374 // same legacy type - if so, don't remove the nai
2375 for (int i = 0; i < nai.networkRequests.size(); i++) {
2376 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2377 if (otherRequest.legacyType == nri.request.legacyType &&
2378 isRequest(otherRequest)) {
2379 if (DBG) log(" still have other legacy request - leaving");
2380 doRemove = false;
2381 }
2382 }
2383 }
2384
2385 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002386 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002387 }
2388 }
2389
Robert Greenwalta67be032014-05-16 15:49:14 -07002390 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002391 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2392 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002393 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002394 } else {
2395 // listens don't have a singular affectedNetwork. Check all networks to see
2396 // if this listen request applies and remove it.
2397 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2398 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002399 if (nri.request.networkCapabilities.hasSignalStrength() &&
2400 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2401 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002402 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002403 }
2404 }
2405 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2406 }
2407 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002408
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002409 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2410 enforceConnectivityInternalPermission();
2411 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2412 accept ? 1 : 0, always ? 1: 0, network));
2413 }
2414
2415 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2416 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2417 " accept=" + accept + " always=" + always);
2418
2419 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2420 if (nai == null) {
2421 // Nothing to do.
2422 return;
2423 }
2424
2425 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002426 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002427 return;
2428 }
2429
2430 if (!nai.networkMisc.explicitlySelected) {
2431 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2432 }
2433
2434 if (accept != nai.networkMisc.acceptUnvalidated) {
2435 int oldScore = nai.getCurrentScore();
2436 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002437 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002438 sendUpdatedScoreToFactories(nai);
2439 }
2440
2441 if (always) {
2442 nai.asyncChannel.sendMessage(
2443 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2444 }
2445
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002446 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002447 // Tell the NetworkAgent to not automatically reconnect to the network.
2448 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2449 // Teardown the nework.
2450 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002451 }
2452
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002453 }
2454
2455 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002456 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002457 mHandler.sendMessageDelayed(
2458 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2459 PROMPT_UNVALIDATED_DELAY_MS);
2460 }
2461
2462 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002463 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002464 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2465
2466 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2467 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002468 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002469 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002470 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2471 return;
2472 }
2473
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002474 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002475 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002476 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2477 intent.setClassName("com.android.settings",
2478 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002479
2480 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2481 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2482 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002483 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002484 }
2485
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002486 private class InternalHandler extends Handler {
2487 public InternalHandler(Looper looper) {
2488 super(looper);
2489 }
2490
2491 @Override
2492 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002493 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002494 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002495 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002496 String causedBy = null;
2497 synchronized (ConnectivityService.this) {
2498 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2499 mNetTransitionWakeLock.isHeld()) {
2500 mNetTransitionWakeLock.release();
2501 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002502 } else {
2503 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002504 }
2505 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002506 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2507 log("Failed to find a new network - expiring NetTransition Wakelock");
2508 } else {
2509 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2510 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002511 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002512 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002513 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002514 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002515 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002516 break;
2517 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002518 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002519 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002520 sendStickyBroadcast(intent);
2521 break;
2522 }
Jason Monkdecd2952013-10-10 14:02:51 -04002523 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002524 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002525 break;
2526 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002527 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002528 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2529 break;
2530 }
2531 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2532 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002533 break;
2534 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002535 case EVENT_REGISTER_NETWORK_AGENT: {
2536 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2537 break;
2538 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002539 case EVENT_REGISTER_NETWORK_REQUEST:
2540 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002541 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002542 break;
2543 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002544 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2545 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002546 handleRegisterNetworkRequestWithIntent(msg);
2547 break;
2548 }
2549 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2550 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2551 break;
2552 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002553 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002554 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002555 break;
2556 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002557 case EVENT_SET_ACCEPT_UNVALIDATED: {
2558 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2559 break;
2560 }
2561 case EVENT_PROMPT_UNVALIDATED: {
2562 handlePromptUnvalidated((Network) msg.obj);
2563 break;
2564 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002565 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2566 handleMobileDataAlwaysOn();
2567 break;
2568 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002569 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2570 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2571 mKeepaliveTracker.handleStartKeepalive(msg);
2572 break;
2573 }
2574 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2575 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2576 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2577 int slot = msg.arg1;
2578 int reason = msg.arg2;
2579 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2580 break;
2581 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002582 case EVENT_SYSTEM_READY: {
2583 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2584 nai.networkMonitor.systemReady = true;
2585 }
2586 break;
2587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 }
2589 }
2590 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002591
2592 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002593 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002594 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002595 if (isTetheringSupported()) {
2596 return mTethering.tether(iface);
2597 } else {
2598 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2599 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002600 }
2601
2602 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002603 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002604 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002605
2606 if (isTetheringSupported()) {
2607 return mTethering.untether(iface);
2608 } else {
2609 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2610 }
2611 }
2612
2613 // javadoc from interface
2614 public int getLastTetherError(String iface) {
2615 enforceTetherAccessPermission();
2616
2617 if (isTetheringSupported()) {
2618 return mTethering.getLastTetherError(iface);
2619 } else {
2620 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2621 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002622 }
2623
2624 // TODO - proper iface API for selection by property, inspection, etc
2625 public String[] getTetherableUsbRegexs() {
2626 enforceTetherAccessPermission();
2627 if (isTetheringSupported()) {
2628 return mTethering.getTetherableUsbRegexs();
2629 } else {
2630 return new String[0];
2631 }
2632 }
2633
2634 public String[] getTetherableWifiRegexs() {
2635 enforceTetherAccessPermission();
2636 if (isTetheringSupported()) {
2637 return mTethering.getTetherableWifiRegexs();
2638 } else {
2639 return new String[0];
2640 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002641 }
2642
Danica Chang6fdd0c62010-08-11 14:54:43 -07002643 public String[] getTetherableBluetoothRegexs() {
2644 enforceTetherAccessPermission();
2645 if (isTetheringSupported()) {
2646 return mTethering.getTetherableBluetoothRegexs();
2647 } else {
2648 return new String[0];
2649 }
2650 }
2651
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002652 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002653 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002654 if (isTetheringSupported()) {
2655 return mTethering.setUsbTethering(enable);
2656 } else {
2657 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2658 }
2659 }
2660
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002661 // TODO - move iface listing, queries, etc to new module
2662 // javadoc from interface
2663 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002664 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002665 return mTethering.getTetherableIfaces();
2666 }
2667
2668 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002669 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002670 return mTethering.getTetheredIfaces();
2671 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002672
Robert Greenwalt5a735062010-03-02 17:25:02 -08002673 public String[] getTetheringErroredIfaces() {
2674 enforceTetherAccessPermission();
2675 return mTethering.getErroredIfaces();
2676 }
2677
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002678 public String[] getTetheredDhcpRanges() {
2679 enforceConnectivityInternalPermission();
2680 return mTethering.getTetheredDhcpRanges();
2681 }
2682
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002683 // if ro.tether.denied = true we default to no tethering
2684 // gservices could set the secure setting to 1 though to enable it on a build where it
2685 // had previously been turned off.
2686 public boolean isTetheringSupported() {
2687 enforceTetherAccessPermission();
2688 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002689 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002690 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2691 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002692 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2693 mTethering.getTetherableWifiRegexs().length != 0 ||
2694 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2695 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002696 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002697
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002698 // Called when we lose the default network and have no replacement yet.
2699 // This will automatically be cleared after X seconds or a new default network
2700 // becomes CONNECTED, whichever happens first. The timer is started by the
2701 // first caller and not restarted by subsequent callers.
2702 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002703 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002704 synchronized (this) {
2705 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002706 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002707 mNetTransitionWakeLock.acquire();
2708 mNetTransitionWakeLockCausedBy = forWhom;
2709 }
2710 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002711 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002712 mNetTransitionWakeLockTimeout);
2713 return;
2714 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002715
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002716 // 100 percent is full good, 0 is full bad.
2717 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002718 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002719 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002720 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002721 }
2722
Paul Jensenbfd17b72015-04-07 12:43:13 -04002723 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002724 enforceAccessPermission();
2725 enforceInternetPermission();
2726
Paul Jensenbfd17b72015-04-07 12:43:13 -04002727 NetworkAgentInfo nai;
2728 if (network == null) {
2729 nai = getDefaultNetwork();
2730 } else {
2731 nai = getNetworkAgentInfoForNetwork(network);
2732 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002733 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2734 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2735 return;
2736 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002737 // Revalidate if the app report does not match our current validated state.
2738 if (hasConnectivity == nai.lastValidated) return;
2739 final int uid = Binder.getCallingUid();
2740 if (DBG) {
2741 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2742 ") by " + uid);
2743 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002744 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002745 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2746 // which isn't meant to work on uncreated networks.
2747 if (!nai.created) return;
2748
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002749 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002750
2751 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2752 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002753 }
2754
Paul Jensencee9b512015-05-06 07:32:40 -04002755 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002756 // this information is already available as a world read/writable jvm property
2757 // so this API change wouldn't have a benifit. It also breaks the passing
2758 // of proxy info to all the JVMs.
2759 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002760 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002761 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002762 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2763 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002764 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002765 }
2766
Paul Jensencee9b512015-05-06 07:32:40 -04002767 public ProxyInfo getProxyForNetwork(Network network) {
2768 if (network == null) return getDefaultProxy();
2769 final ProxyInfo globalProxy = getGlobalProxy();
2770 if (globalProxy != null) return globalProxy;
2771 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2772 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2773 // caller may not have.
2774 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2775 if (nai == null) return null;
2776 synchronized (nai) {
2777 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2778 if (proxyInfo == null) return null;
2779 return new ProxyInfo(proxyInfo);
2780 }
2781 }
2782
Paul Jensene0bef712014-12-10 15:12:18 -05002783 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2784 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2785 // proxy is null then there is no proxy in place).
2786 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2787 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2788 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2789 proxy = null;
2790 }
2791 return proxy;
2792 }
2793
2794 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2795 // better for determining if a new proxy broadcast is necessary:
2796 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2797 // avoid unnecessary broadcasts.
2798 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2799 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2800 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2801 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2802 // all set.
2803 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2804 a = canonicalizeProxyInfo(a);
2805 b = canonicalizeProxyInfo(b);
2806 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2807 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2808 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2809 }
2810
Jason Monk207900c2014-04-25 15:00:09 -04002811 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002812 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002813
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002814 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002815 if (proxyProperties == mGlobalProxy) return;
2816 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2817 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2818
2819 String host = "";
2820 int port = 0;
2821 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002822 String pacFileUrl = "";
2823 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002824 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002825 if (!proxyProperties.isValid()) {
2826 if (DBG)
2827 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2828 return;
2829 }
Jason Monk207900c2014-04-25 15:00:09 -04002830 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002831 host = mGlobalProxy.getHost();
2832 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002833 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002834 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002835 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002836 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002837 } else {
2838 mGlobalProxy = null;
2839 }
2840 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002841 final long token = Binder.clearCallingIdentity();
2842 try {
2843 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2844 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2845 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2846 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002847 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002848 } finally {
2849 Binder.restoreCallingIdentity(token);
2850 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002851
Jason Monkcf0f97a2014-10-02 15:39:38 -04002852 if (mGlobalProxy == null) {
2853 proxyProperties = mDefaultProxy;
2854 }
2855 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002856 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002857 }
2858
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002859 private void loadGlobalProxy() {
2860 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002861 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2862 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2863 String exclList = Settings.Global.getString(res,
2864 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002865 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2866 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002867 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002868 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002869 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002870 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002871 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002872 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002873 if (!proxyProperties.isValid()) {
2874 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2875 return;
2876 }
2877
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002878 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002879 mGlobalProxy = proxyProperties;
2880 }
2881 }
2882 }
2883
Jason Monk207900c2014-04-25 15:00:09 -04002884 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002885 // this information is already available as a world read/writable jvm property
2886 // so this API change wouldn't have a benifit. It also breaks the passing
2887 // of proxy info to all the JVMs.
2888 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002889 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002890 return mGlobalProxy;
2891 }
2892 }
2893
Jason Monk207900c2014-04-25 15:00:09 -04002894 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002895 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002896 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002897 proxy = null;
2898 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002899 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002900 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002901 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002902 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002903 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2904 return;
2905 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002906
2907 // This call could be coming from the PacManager, containing the port of the local
2908 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2909 // global (to get the correct local port), and send a broadcast.
2910 // TODO: Switch PacManager to have its own message to send back rather than
2911 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002912 if ((mGlobalProxy != null) && (proxy != null)
2913 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002914 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2915 mGlobalProxy = proxy;
2916 sendProxyBroadcast(mGlobalProxy);
2917 return;
2918 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002919 mDefaultProxy = proxy;
2920
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002921 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002922 if (!mDefaultProxyDisabled) {
2923 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002924 }
2925 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002926 }
2927
Paul Jensene0bef712014-12-10 15:12:18 -05002928 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2929 // This method gets called when any network changes proxy, but the broadcast only ever contains
2930 // the default proxy (even if it hasn't changed).
2931 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2932 // world where an app might be bound to a non-default network.
2933 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2934 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2935 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2936
2937 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2938 sendProxyBroadcast(getDefaultProxy());
2939 }
2940 }
2941
Robert Greenwalt434203a2010-10-11 16:00:27 -07002942 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002943 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2944 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002945 if (!TextUtils.isEmpty(proxy)) {
2946 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002947 if (data.length == 0) {
2948 return;
2949 }
2950
Robert Greenwalt434203a2010-10-11 16:00:27 -07002951 String proxyHost = data[0];
2952 int proxyPort = 8080;
2953 if (data.length > 1) {
2954 try {
2955 proxyPort = Integer.parseInt(data[1]);
2956 } catch (NumberFormatException e) {
2957 return;
2958 }
2959 }
Jason Monk207900c2014-04-25 15:00:09 -04002960 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002961 setGlobalProxy(p);
2962 }
2963 }
2964
Jason Monk207900c2014-04-25 15:00:09 -04002965 private void sendProxyBroadcast(ProxyInfo proxy) {
2966 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002967 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002968 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002969 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002970 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2971 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002972 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002973 final long ident = Binder.clearCallingIdentity();
2974 try {
2975 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2976 } finally {
2977 Binder.restoreCallingIdentity(ident);
2978 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002979 }
2980
2981 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002982 final private HashMap<Uri, Integer> mUriEventMap;
2983 final private Context mContext;
2984 final private Handler mHandler;
2985
2986 SettingsObserver(Context context, Handler handler) {
2987 super(null);
2988 mUriEventMap = new HashMap<Uri, Integer>();
2989 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002990 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002991 }
2992
Erik Klineda4bfa82015-04-30 12:58:40 +09002993 void observe(Uri uri, int what) {
2994 mUriEventMap.put(uri, what);
2995 final ContentResolver resolver = mContext.getContentResolver();
2996 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002997 }
2998
2999 @Override
3000 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003001 Slog.wtf(TAG, "Should never be reached.");
3002 }
3003
3004 @Override
3005 public void onChange(boolean selfChange, Uri uri) {
3006 final Integer what = mUriEventMap.get(uri);
3007 if (what != null) {
3008 mHandler.obtainMessage(what.intValue()).sendToTarget();
3009 } else {
3010 loge("No matching event to send for URI=" + uri);
3011 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003012 }
3013 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003014
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003015 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003016 Slog.d(TAG, s);
3017 }
3018
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003019 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003020 Slog.e(TAG, s);
3021 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003022
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003023 private static <T> T checkNotNull(T value, String message) {
3024 if (value == null) {
3025 throw new NullPointerException(message);
3026 }
3027 return value;
3028 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003029
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003030 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003031 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003032 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3033 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3034 *
3035 * @param oldPackage Package name of the application which currently controls VPN, which will
3036 * be replaced. If there is no such application, this should should either be
3037 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3038 * @param newPackage Package name of the application which should gain control of VPN, or
3039 * {@code null} to disable.
3040 * @param userId User for whom to prepare the new VPN.
3041 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003042 * @hide
3043 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003044 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003045 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3046 int userId) {
3047 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003048 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003049
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003050 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003051 Vpn vpn = mVpns.get(userId);
3052 if (vpn != null) {
3053 return vpn.prepare(oldPackage, newPackage);
3054 } else {
3055 return false;
3056 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003057 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003058 }
3059
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003060 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003061 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3062 * This method is used by system-privileged apps.
3063 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3064 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3065 *
3066 * @param packageName The package for which authorization state should change.
3067 * @param userId User for whom {@code packageName} is installed.
3068 * @param authorized {@code true} if this app should be able to start a VPN connection without
3069 * explicit user approval, {@code false} if not.
3070 *
Jeff Davidson05542602014-08-11 14:07:27 -07003071 * @hide
3072 */
3073 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003074 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3075 enforceCrossUserPermission(userId);
3076
Jeff Davidson05542602014-08-11 14:07:27 -07003077 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003078 Vpn vpn = mVpns.get(userId);
3079 if (vpn != null) {
3080 vpn.setPackageAuthorization(packageName, authorized);
3081 }
Jeff Davidson05542602014-08-11 14:07:27 -07003082 }
3083 }
3084
3085 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003086 * Configure a TUN interface and return its file descriptor. Parameters
3087 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003088 * and not available in ConnectivityManager. Permissions are checked in
3089 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003090 * @hide
3091 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003092 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003093 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003094 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003095 int user = UserHandle.getUserId(Binder.getCallingUid());
3096 synchronized(mVpns) {
3097 return mVpns.get(user).establish(config);
3098 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003099 }
3100
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003101 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003102 * Start legacy VPN, controlling native daemons as needed. Creates a
3103 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003104 */
3105 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003106 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003107 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003108 final LinkProperties egress = getActiveLinkProperties();
3109 if (egress == null) {
3110 throw new IllegalStateException("Missing active network connection");
3111 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003112 int user = UserHandle.getUserId(Binder.getCallingUid());
3113 synchronized(mVpns) {
3114 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3115 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003116 }
3117
3118 /**
3119 * Return the information of the ongoing legacy VPN. This method is used
3120 * by VpnSettings and not available in ConnectivityManager. Permissions
3121 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003122 */
3123 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003124 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3125 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003126 if (mLockdownEnabled) {
3127 return null;
3128 }
3129
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003130 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003131 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003132 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003133 }
3134
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003135 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003136 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3137 * and not available in ConnectivityManager.
3138 */
3139 @Override
3140 public VpnInfo[] getAllVpnInfo() {
3141 enforceConnectivityInternalPermission();
3142 if (mLockdownEnabled) {
3143 return new VpnInfo[0];
3144 }
3145
3146 synchronized(mVpns) {
3147 List<VpnInfo> infoList = new ArrayList<>();
3148 for (int i = 0; i < mVpns.size(); i++) {
3149 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3150 if (info != null) {
3151 infoList.add(info);
3152 }
3153 }
3154 return infoList.toArray(new VpnInfo[infoList.size()]);
3155 }
3156 }
3157
3158 /**
3159 * @return VPN information for accounting, or null if we can't retrieve all required
3160 * information, e.g primary underlying iface.
3161 */
3162 @Nullable
3163 private VpnInfo createVpnInfo(Vpn vpn) {
3164 VpnInfo info = vpn.getVpnInfo();
3165 if (info == null) {
3166 return null;
3167 }
3168 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3169 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3170 // the underlyingNetworks list.
3171 if (underlyingNetworks == null) {
3172 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3173 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3174 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3175 }
3176 } else if (underlyingNetworks.length > 0) {
3177 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3178 if (linkProperties != null) {
3179 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3180 }
3181 }
3182 return info.primaryUnderlyingIface == null ? null : info;
3183 }
3184
3185 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003186 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3187 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003188 * Permissions are checked in Vpn class.
3189 * @hide
3190 */
3191 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003192 public VpnConfig getVpnConfig(int userId) {
3193 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003194 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003195 Vpn vpn = mVpns.get(userId);
3196 if (vpn != null) {
3197 return vpn.getVpnConfig();
3198 } else {
3199 return null;
3200 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003201 }
3202 }
3203
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003204 @Override
3205 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003206 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3207 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3208 return false;
3209 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003210
3211 // Tear down existing lockdown if profile was removed
3212 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3213 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003214 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003215 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3216 return false;
3217 }
3218
3219 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3220 final VpnProfile profile = VpnProfile.decode(
3221 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003222 if (profile == null) {
3223 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3224 setLockdownTracker(null);
3225 return true;
3226 }
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)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003373 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003374 .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
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003540 private void onUserAdded(int userId) {
3541 synchronized(mVpns) {
3542 final int vpnsSize = mVpns.size();
3543 for (int i = 0; i < vpnsSize; i++) {
3544 Vpn vpn = mVpns.valueAt(i);
3545 vpn.onUserAdded(userId);
3546 }
3547 }
3548 }
3549
3550 private void onUserRemoved(int userId) {
3551 synchronized(mVpns) {
3552 final int vpnsSize = mVpns.size();
3553 for (int i = 0; i < vpnsSize; i++) {
3554 Vpn vpn = mVpns.valueAt(i);
3555 vpn.onUserRemoved(userId);
3556 }
3557 }
3558 }
3559
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003560 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3561 @Override
3562 public void onReceive(Context context, Intent intent) {
3563 final String action = intent.getAction();
3564 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3565 if (userId == UserHandle.USER_NULL) return;
3566
3567 if (Intent.ACTION_USER_STARTING.equals(action)) {
3568 onUserStart(userId);
3569 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3570 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003571 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3572 onUserAdded(userId);
3573 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3574 onUserRemoved(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003575 }
3576 }
3577 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003578
Robert Greenwalta67be032014-05-16 15:49:14 -07003579 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3580 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003581 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3582 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003583
Robert Greenwalta67be032014-05-16 15:49:14 -07003584 private static class NetworkFactoryInfo {
3585 public final String name;
3586 public final Messenger messenger;
3587 public final AsyncChannel asyncChannel;
3588
3589 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3590 this.name = name;
3591 this.messenger = messenger;
3592 this.asyncChannel = asyncChannel;
3593 }
3594 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003595
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003596 /**
3597 * Tracks info about the requester.
3598 * Also used to notice when the calling process dies so we can self-expire
3599 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003600 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3601 static final boolean REQUEST = true;
3602 static final boolean LISTEN = false;
3603
3604 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003605 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003606 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003607 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003608 final int mPid;
3609 final int mUid;
3610 final Messenger messenger;
3611 final boolean isRequest;
3612
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003613 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3614 request = r;
3615 mPendingIntent = pi;
3616 messenger = null;
3617 mBinder = null;
3618 mPid = getCallingPid();
3619 mUid = getCallingUid();
3620 this.isRequest = isRequest;
3621 }
3622
Robert Greenwalt9258c642014-03-26 16:47:06 -07003623 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3624 super();
3625 messenger = m;
3626 request = r;
3627 mBinder = binder;
3628 mPid = getCallingPid();
3629 mUid = getCallingUid();
3630 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003631 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003632
3633 try {
3634 mBinder.linkToDeath(this, 0);
3635 } catch (RemoteException e) {
3636 binderDied();
3637 }
3638 }
3639
3640 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003641 if (mBinder != null) {
3642 mBinder.unlinkToDeath(this, 0);
3643 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003644 }
3645
3646 public void binderDied() {
3647 log("ConnectivityService NetworkRequestInfo binderDied(" +
3648 request + ", " + mBinder + ")");
3649 releaseNetworkRequest(request);
3650 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003651
3652 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003653 return (isRequest ? "Request" : "Listen") +
3654 " from uid/pid:" + mUid + "/" + mPid +
3655 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003656 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003657 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003658 }
3659
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003660 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3661 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3662 if (badCapability != null) {
3663 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003664 }
3665 }
3666
Erik Kline9d598e12015-07-13 16:37:51 +09003667 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003668 final SortedSet<Integer> thresholds = new TreeSet();
3669 synchronized (nai) {
3670 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3671 if (nri.request.networkCapabilities.hasSignalStrength() &&
3672 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3673 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3674 }
3675 }
3676 }
Erik Kline9d598e12015-07-13 16:37:51 +09003677 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003678 }
3679
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003680 private void updateSignalStrengthThresholds(
3681 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3682 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003683 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003684 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3685
3686 // TODO: Switch to VDBG.
3687 if (DBG) {
3688 String detail;
3689 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3690 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3691 } else {
3692 detail = reason;
3693 }
3694 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3695 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3696 }
3697
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003698 nai.asyncChannel.sendMessage(
3699 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003700 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003701 }
3702
Robert Greenwalt9258c642014-03-26 16:47:06 -07003703 @Override
3704 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003705 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003706 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003707 enforceNetworkRequestPermissions(networkCapabilities);
3708 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003709 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003710
Robert Greenwalt6078b502014-06-11 16:05:07 -07003711 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003712 throw new IllegalArgumentException("Bad timeout specified");
3713 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003714
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003715 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3716 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003717 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3718 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003719 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003720
3721 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003722 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003723 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003724 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003725 }
3726 return networkRequest;
3727 }
3728
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003729 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003730 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003731 enforceConnectivityInternalPermission();
3732 } else {
3733 enforceChangePermission();
3734 }
3735 }
3736
fenglub15e72b2015-03-20 11:29:56 -07003737 @Override
fengludb571472015-04-21 17:12:05 -07003738 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003739 enforceAccessPermission();
3740 NetworkAgentInfo nai = null;
3741 if (network == null) {
3742 return false;
3743 }
3744 synchronized (mNetworkForNetId) {
3745 nai = mNetworkForNetId.get(network.netId);
3746 }
3747 if (nai != null) {
3748 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3749 return true;
3750 }
3751 return false;
3752 }
3753
3754
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003755 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3756 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003757 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003758 final int uidRules;
3759 final int uid = Binder.getCallingUid();
3760 synchronized(mRulesLock) {
3761 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3762 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003763 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003764 // we could silently fail or we can filter the available nets to only give
3765 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003766 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003767 }
3768 }
3769 }
3770
Robert Greenwalt9258c642014-03-26 16:47:06 -07003771 @Override
3772 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3773 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003774 checkNotNull(operation, "PendingIntent cannot be null.");
3775 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3776 enforceNetworkRequestPermissions(networkCapabilities);
3777 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003778 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003779
3780 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3781 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003782 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3783 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003784 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003785 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3786 nri));
3787 return networkRequest;
3788 }
3789
Jeremy Joslin79294842014-12-03 17:15:28 -08003790 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3791 mHandler.sendMessageDelayed(
3792 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3793 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3794 }
3795
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003796 @Override
3797 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003798 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003799 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3800 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003801 }
3802
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003803 // In order to implement the compatibility measure for pre-M apps that call
3804 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3805 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3806 // This ensures it has permission to do so.
3807 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3808 if (nc == null) {
3809 return false;
3810 }
3811 int[] transportTypes = nc.getTransportTypes();
3812 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3813 return false;
3814 }
3815 try {
3816 mContext.enforceCallingOrSelfPermission(
3817 android.Manifest.permission.ACCESS_WIFI_STATE,
3818 "ConnectivityService");
3819 } catch (SecurityException e) {
3820 return false;
3821 }
3822 return true;
3823 }
3824
Robert Greenwalt9258c642014-03-26 16:47:06 -07003825 @Override
3826 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3827 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003828 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3829 enforceAccessPermission();
3830 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003831
Erik Kline7523eb32015-07-09 18:24:03 +09003832 NetworkRequest networkRequest = new NetworkRequest(
3833 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003834 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3835 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003836 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003837
3838 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3839 return networkRequest;
3840 }
3841
3842 @Override
3843 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3844 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003845 checkNotNull(operation, "PendingIntent cannot be null.");
3846 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3847 enforceAccessPermission();
3848 }
3849
Erik Kline7523eb32015-07-09 18:24:03 +09003850 NetworkRequest networkRequest = new NetworkRequest(
3851 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003852 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3853 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003854 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003855
3856 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003857 }
3858
3859 @Override
3860 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003861 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3862 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003863 }
3864
3865 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003866 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003867 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003868 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3869 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003870 }
3871
Robert Greenwalta67be032014-05-16 15:49:14 -07003872 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003873 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003874 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3875 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3876 }
3877
3878 @Override
3879 public void unregisterNetworkFactory(Messenger messenger) {
3880 enforceConnectivityInternalPermission();
3881 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3882 }
3883
3884 private void handleUnregisterNetworkFactory(Messenger messenger) {
3885 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3886 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003887 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003888 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003889 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003890 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003891 }
3892
Robert Greenwalt7b816022014-04-18 15:25:25 -07003893 /**
3894 * NetworkAgentInfo supporting a request by requestId.
3895 * These have already been vetted (their Capabilities satisfy the request)
3896 * and the are the highest scored network available.
3897 * the are keyed off the Requests requestId.
3898 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003899 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003900 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3901 new SparseArray<NetworkAgentInfo>();
3902
Paul Jensen31a94f42015-02-13 14:18:39 -05003903 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3904 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003905 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3906 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003907 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3908 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3909 // there may not be a strict 1:1 correlation between the two.
3910 @GuardedBy("mNetworkForNetId")
3911 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003912
Robert Greenwalt7b816022014-04-18 15:25:25 -07003913 // NetworkAgentInfo keyed off its connecting messenger
3914 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003915 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003916 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3917 new HashMap<Messenger, NetworkAgentInfo>();
3918
Paul Jensen2c311d62014-11-17 12:34:51 -05003919 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003920 private final NetworkRequest mDefaultRequest;
3921
Erik Klineda4bfa82015-04-30 12:58:40 +09003922 // Request used to optionally keep mobile data active even when higher
3923 // priority networks like Wi-Fi are active.
3924 private final NetworkRequest mDefaultMobileDataRequest;
3925
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003926 private NetworkAgentInfo getDefaultNetwork() {
3927 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3928 }
3929
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003930 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003931 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003932 }
3933
Paul Jensen31a94f42015-02-13 14:18:39 -05003934 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003935 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003936 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003937 enforceConnectivityInternalPermission();
3938
Paul Jensen2c311d62014-11-17 12:34:51 -05003939 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3940 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04003941 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003942 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3943 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04003944 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003945 synchronized (this) {
3946 nai.networkMonitor.systemReady = mSystemReady;
3947 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003948 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003949 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003950 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003951 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003952 }
3953
3954 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3955 if (VDBG) log("Got NetworkAgent Messenger");
3956 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003957 synchronized (mNetworkForNetId) {
3958 mNetworkForNetId.put(na.network.netId, na);
3959 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003960 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3961 NetworkInfo networkInfo = na.networkInfo;
3962 na.networkInfo = null;
3963 updateNetworkInfo(na, networkInfo);
3964 }
3965
3966 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3967 LinkProperties newLp = networkAgent.linkProperties;
3968 int netId = networkAgent.network.netId;
3969
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003970 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3971 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003972 if (networkAgent.clatd != null) {
3973 networkAgent.clatd.fixupLinkProperties(oldLp);
3974 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003975
Paul Jensen992f2522014-04-28 10:33:11 -04003976 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003977 updateMtu(newLp, oldLp);
3978 // TODO - figure out what to do for clat
3979// for (LinkProperties lp : newLp.getStackedLinks()) {
3980// updateMtu(lp, null);
3981// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003982 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003983
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003984 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3985 // In L, we used it only when the network had Internet access but provided no DNS servers.
3986 // For now, just disable it, and if disabling it doesn't break things, remove it.
3987 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3988 // NET_CAPABILITY_INTERNET);
3989 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003990 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003991 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3992
Paul Jensen3b759822014-05-13 11:44:01 -04003993 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003994 if (isDefaultNetwork(networkAgent)) {
3995 handleApplyDefaultProxy(newLp.getHttpProxy());
3996 } else {
3997 updateProxy(newLp, oldLp, networkAgent);
3998 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003999 // TODO - move this check to cover the whole function
4000 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08004001 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004002 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4003 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004004
4005 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004006 }
4007
Lorenzo Colitti95439462014-10-09 13:44:48 +09004008 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4009 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4010 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004011
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004012 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004013 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4014 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004015 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004016 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004017 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004018 }
Paul Jensen992f2522014-04-28 10:33:11 -04004019
4020 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4021 CompareResult<String> interfaceDiff = new CompareResult<String>();
4022 if (oldLp != null) {
4023 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4024 } else if (newLp != null) {
4025 interfaceDiff.added = newLp.getAllInterfaceNames();
4026 }
4027 for (String iface : interfaceDiff.added) {
4028 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004029 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004030 mNetd.addInterfaceToNetwork(iface, netId);
4031 } catch (Exception e) {
4032 loge("Exception adding interface: " + e);
4033 }
4034 }
4035 for (String iface : interfaceDiff.removed) {
4036 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004037 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004038 mNetd.removeInterfaceFromNetwork(iface, netId);
4039 } catch (Exception e) {
4040 loge("Exception removing interface: " + e);
4041 }
4042 }
4043 }
4044
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004045 /**
4046 * Have netd update routes from oldLp to newLp.
4047 * @return true if routes changed between oldLp and newLp
4048 */
4049 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004050 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4051 if (oldLp != null) {
4052 routeDiff = oldLp.compareAllRoutes(newLp);
4053 } else if (newLp != null) {
4054 routeDiff.added = newLp.getAllRoutes();
4055 }
4056
4057 // add routes before removing old in case it helps with continuous connectivity
4058
4059 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4060 for (RouteInfo route : routeDiff.added) {
4061 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004062 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004063 try {
4064 mNetd.addRoute(netId, route);
4065 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004066 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4067 loge("Exception in addRoute for non-gateway: " + e);
4068 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004069 }
4070 }
4071 for (RouteInfo route : routeDiff.added) {
4072 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004073 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004074 try {
4075 mNetd.addRoute(netId, route);
4076 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004077 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4078 loge("Exception in addRoute for gateway: " + e);
4079 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004080 }
4081 }
4082
4083 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004084 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004085 try {
4086 mNetd.removeRoute(netId, route);
4087 } catch (Exception e) {
4088 loge("Exception in removeRoute: " + e);
4089 }
4090 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004091 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004092 }
Erik Kline41368502015-06-17 13:19:54 +09004093
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004094 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4095 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004096 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09004097 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004098 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004099 dnses = new ArrayList();
4100 dnses.add(mDefaultDns);
4101 if (DBG) {
4102 loge("no dns provided for netId " + netId + ", so using defaults");
4103 }
4104 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004105 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004106 try {
4107 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4108 newLp.getDomains());
4109 } catch (Exception e) {
4110 loge("Exception in setDnsServersForNetwork: " + e);
4111 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04004112 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004113 if (defaultNai != null && defaultNai.network.netId == netId) {
4114 setDefaultDnsSystemProperties(dnses);
4115 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004116 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004117 } else if (flush) {
4118 try {
4119 mNetd.flushNetworkDnsCache(netId);
4120 } catch (Exception e) {
4121 loge("Exception in flushNetworkDnsCache: " + e);
4122 }
4123 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004124 }
4125 }
4126
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004127 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4128 int last = 0;
4129 for (InetAddress dns : dnses) {
4130 ++last;
4131 String key = "net.dns" + last;
4132 String value = dns.getHostAddress();
4133 SystemProperties.set(key, value);
4134 }
4135 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4136 String key = "net.dns" + i;
4137 SystemProperties.set(key, "");
4138 }
4139 mNumDnsEntries = last;
4140 }
4141
Paul Jensen3d194ea2015-06-16 14:27:36 -04004142 /**
4143 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4144 * augmented with any stateful capabilities implied from {@code networkAgent}
4145 * (e.g., validated status and captive portal status).
4146 *
Paul Jensene0988542015-06-25 15:30:08 -04004147 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004148 * @param networkCapabilities the new network capabilities.
4149 */
Paul Jensene0988542015-06-25 15:30:08 -04004150 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004151 // Don't modify caller's NetworkCapabilities.
4152 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004153 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004154 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4155 } else {
4156 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4157 }
Paul Jensene0988542015-06-25 15:30:08 -04004158 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004159 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4160 } else {
4161 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4162 }
Paul Jensene0988542015-06-25 15:30:08 -04004163 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4164 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004165 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4166 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4167 try {
4168 mNetd.setNetworkPermission(nai.network.netId,
4169 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4170 null : NetworkManagementService.PERMISSION_SYSTEM);
4171 } catch (RemoteException e) {
4172 loge("Exception in setNetworkPermission: " + e);
4173 }
4174 }
Paul Jensene0988542015-06-25 15:30:08 -04004175 synchronized (nai) {
4176 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004177 }
Paul Jensene0988542015-06-25 15:30:08 -04004178 rematchAllNetworksAndRequests(nai, oldScore);
4179 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004180 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004181 }
4182
Paul Jensenc8b9a742014-09-30 15:37:41 -04004183 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4184 for (int i = 0; i < nai.networkRequests.size(); i++) {
4185 NetworkRequest nr = nai.networkRequests.valueAt(i);
4186 // Don't send listening requests to factories. b/17393458
4187 if (!isRequest(nr)) continue;
4188 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4189 }
4190 }
4191
Robert Greenwalt7b816022014-04-18 15:25:25 -07004192 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4193 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004194 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004195 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4196 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004197 }
4198 }
4199
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004200 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4201 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004202 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004203 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004204 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4205 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004206 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004207 sendIntent(nri.mPendingIntent, intent);
4208 }
4209 // else not handled
4210 }
4211
4212 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4213 mPendingIntentWakeLock.acquire();
4214 try {
4215 if (DBG) log("Sending " + pendingIntent);
4216 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4217 } catch (PendingIntent.CanceledException e) {
4218 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4219 mPendingIntentWakeLock.release();
4220 releasePendingNetworkRequest(pendingIntent);
4221 }
4222 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4223 }
4224
4225 @Override
4226 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4227 String resultData, Bundle resultExtras) {
4228 if (DBG) log("Finished sending " + pendingIntent);
4229 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004230 // Release with a delay so the receiving client has an opportunity to put in its
4231 // own request.
4232 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004233 }
4234
Robert Greenwalt9258c642014-03-26 16:47:06 -07004235 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004236 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004237 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004238 Bundle bundle = new Bundle();
4239 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4240 new NetworkRequest(nri.request));
4241 Message msg = Message.obtain();
4242 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4243 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4244 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4245 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004246 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004247 case ConnectivityManager.CALLBACK_LOSING: {
4248 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4249 break;
4250 }
4251 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4252 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4253 new NetworkCapabilities(networkAgent.networkCapabilities));
4254 break;
4255 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004256 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004257 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4258 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004259 break;
4260 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004261 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004262 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004263 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004264 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004265 if (VDBG) {
4266 log("sending notification " + notifyTypeToName(notificationType) +
4267 " for " + nri.request);
4268 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004269 nri.messenger.send(msg);
4270 } catch (RemoteException e) {
4271 // may occur naturally in the race of binder death.
4272 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4273 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004274 }
4275
Paul Jensenc8b9a742014-09-30 15:37:41 -04004276 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4277 for (int i = 0; i < nai.networkRequests.size(); i++) {
4278 NetworkRequest nr = nai.networkRequests.valueAt(i);
4279 // Ignore listening requests.
4280 if (!isRequest(nr)) continue;
4281 loge("Dead network still had at least " + nr);
4282 break;
4283 }
4284 nai.asyncChannel.disconnect();
4285 }
4286
Robert Greenwalt7b816022014-04-18 15:25:25 -07004287 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4288 if (oldNetwork == null) {
4289 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4290 return;
4291 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004292 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4293 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004294 }
4295
Paul Jensen27b02b72014-07-14 12:03:33 -04004296 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004297 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004298 setupDataActivityTracking(newNetwork);
4299 try {
4300 mNetd.setDefaultNetId(newNetwork.network.netId);
4301 } catch (Exception e) {
4302 loge("Exception setting default network :" + e);
4303 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004304 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004305 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004306 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004307 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004308 }
4309
Paul Jensen2161a8e2014-09-11 11:00:39 -04004310 // Handles a network appearing or improving its score.
4311 //
4312 // - Evaluates all current NetworkRequests that can be
4313 // satisfied by newNetwork, and reassigns to newNetwork
4314 // any such requests for which newNetwork is the best.
4315 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004316 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004317 // needed. A network is needed if it is the best network for
4318 // one or more NetworkRequests, or if it is a VPN.
4319 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004320 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004321 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004322 //
4323 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4324 // networks that have no chance (i.e. even if validated)
4325 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004326 //
4327 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4328 // it does not remove NetworkRequests that other Networks could better satisfy.
4329 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4330 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4331 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004332 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004333 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004334 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4335 // performed to tear down unvalidated networks that have no chance (i.e. even if
4336 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004337 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004338 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004339 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004340 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004341 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004342 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004343 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004344 // Find and migrate to this Network any NetworkRequests for
4345 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004346 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004347 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004348 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004349 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004350 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4351 final boolean satisfies = newNetwork.satisfies(nri.request);
4352 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004353 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004354 log("Network " + newNetwork.name() + " was already satisfying" +
4355 " request " + nri.request.requestId + ". No change.");
4356 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004357 keep = true;
4358 continue;
4359 }
4360
4361 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004362 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004363 if (satisfies) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004364 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004365 // This is not a request, it's a callback listener.
4366 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004367 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004368 continue;
4369 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004370
Robert Greenwalt7b816022014-04-18 15:25:25 -07004371 // next check if it's better than any current network we're using for
4372 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004373 if (VDBG) {
4374 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004375 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4376 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004377 }
4378 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004379 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004380 if (DBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004381 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004382 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004383 currentNetwork.networkRequests.remove(nri.request.requestId);
4384 currentNetwork.networkLingered.add(nri.request);
4385 affectedNetworks.add(currentNetwork);
4386 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004387 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004388 }
Paul Jensen573a0352015-01-08 10:49:34 -05004389 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004390 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004391 if (!newNetwork.addRequest(nri.request)) {
4392 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4393 }
4394 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004395 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004396 // Tell NetworkFactories about the new score, so they can stop
4397 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004398 // TODO - this could get expensive if we have alot of requests for this
4399 // network. Think about if there is a way to reduce this. Push
4400 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004401 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004402 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004403 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004404 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004405 }
4406 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004407 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4408 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4409 // mark it as no longer satisfying "nri". Because networks are processed by
4410 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4411 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4412 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4413 // This means this code doesn't have to handle the case where "currentNetwork" no
4414 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4415 if (DBG) {
4416 log("Network " + newNetwork.name() + " stopped satisfying" +
4417 " request " + nri.request.requestId);
4418 }
4419 newNetwork.networkRequests.remove(nri.request.requestId);
4420 if (currentNetwork == newNetwork) {
4421 mNetworkForRequestId.remove(nri.request.requestId);
4422 sendUpdatedScoreToFactories(nri.request, 0);
4423 } else {
4424 if (nri.isRequest == true) {
4425 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4426 newNetwork.name() +
4427 " without updating mNetworkForRequestId or factories!");
4428 }
4429 }
4430 // TODO: technically, sending CALLBACK_LOST here is
4431 // incorrect if nri is a request (not a listen) and there
4432 // is a replacement network currently connected that can
4433 // satisfy it. However, the only capability that can both
4434 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4435 // so this code is only incorrect for a network that loses
4436 // the TRUSTED capability, which is a rare case.
4437 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004438 }
4439 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004440 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004441 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004442 if (nai.lingering) {
4443 // Already lingered. Nothing to do. This can only happen if "nai" is in
4444 // "affectedNetworks" twice. The reasoning being that to get added to
4445 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4446 // (i.e. not lingered) so it could have only been lingered by this loop.
4447 // unneeded(nai) will be false and we'll call unlinger() below which would
4448 // be bad, so handle it here.
4449 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004450 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004451 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004452 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004453 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004454 }
4455 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004456 if (isNewDefault) {
4457 // Notify system services that this network is up.
4458 makeDefault(newNetwork);
4459 synchronized (ConnectivityService.this) {
4460 // have a new default network, release the transition wakelock in
4461 // a second if it's held. The second pause is to allow apps
4462 // to reconnect over the new network
4463 if (mNetTransitionWakeLock.isHeld()) {
4464 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4465 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4466 mNetTransitionWakeLockSerialNumber, 0),
4467 1000);
4468 }
4469 }
4470 }
4471
4472 // do this after the default net is switched, but
4473 // before LegacyTypeTracker sends legacy broadcasts
4474 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4475
4476 if (isNewDefault) {
4477 // Maintain the illusion: since the legacy API only
4478 // understands one network at a time, we must pretend
4479 // that the current default network disconnected before
4480 // the new one connected.
4481 if (oldDefaultNetwork != null) {
4482 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4483 oldDefaultNetwork, true);
4484 }
4485 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4486 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4487 notifyLockdownVpn(newNetwork);
4488 }
4489
Robert Greenwalt7b816022014-04-18 15:25:25 -07004490 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004491 // Notify battery stats service about this network, both the normal
4492 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004493 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004494 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004495 final IBatteryStats bs = BatteryStatsService.getService();
4496 final int type = newNetwork.networkInfo.getType();
4497
4498 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4499 bs.noteNetworkInterfaceType(baseIface, type);
4500 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4501 final String stackedIface = stacked.getInterfaceName();
4502 bs.noteNetworkInterfaceType(stackedIface, type);
4503 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4504 }
4505 } catch (RemoteException ignored) {
4506 }
4507
Robert Greenwalt152ed372014-12-17 17:19:53 -08004508 // This has to happen after the notifyNetworkCallbacks as that tickles each
4509 // ConnectivityManager instance so that legacy requests correctly bind dns
4510 // requests to this network. The legacy users are listening for this bcast
4511 // and will generally do a dns request so they can ensureRouteToHost and if
4512 // they do that before the callbacks happen they'll use the default network.
4513 //
4514 // TODO: Is there still a race here? We send the broadcast
4515 // after sending the callback, but if the app can receive the
4516 // broadcast before the callback, it might still break.
4517 //
4518 // This *does* introduce a race where if the user uses the new api
4519 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4520 // they may get old info. Reverse this after the old startUsing api is removed.
4521 // This is on top of the multiple intent sequencing referenced in the todo above.
4522 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4523 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4524 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4525 // legacy type tracker filters out repeat adds
4526 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4527 }
4528 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004529
4530 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4531 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4532 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4533 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4534 if (newNetwork.isVPN()) {
4535 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4536 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004537 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004538 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4539 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004540 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004541 if (DBG) log("Reaping " + nai.name());
4542 teardownUnneededNetwork(nai);
4543 }
4544 }
4545 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004546 }
4547
Paul Jensen1c7ba022015-06-16 14:27:36 -04004548 /**
4549 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4550 * being disconnected.
4551 * @param changed If only one Network's score or capabilities have been modified since the last
4552 * time this function was called, pass this Network in this argument, otherwise pass
4553 * null.
4554 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4555 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4556 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4557 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4558 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004559 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004560 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004561 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4562 // to avoid the slowness. It is not simply enough to process just "changed", for
4563 // example in the case where "changed"'s score decreases and another network should begin
4564 // satifying a NetworkRequest that "changed" currently satisfies.
4565
4566 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4567 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4568 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004569 if (changed != null && oldScore < changed.getCurrentScore()) {
4570 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004571 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004572 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4573 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4574 // Rematch higher scoring networks first to prevent requests first matching a lower
4575 // scoring network and then a higher scoring network, which could produce multiple
4576 // callbacks and inadvertently unlinger networks.
4577 Arrays.sort(nais);
4578 for (NetworkAgentInfo nai : nais) {
4579 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004580 // Only reap the last time through the loop. Reaping before all rematching
4581 // is complete could incorrectly teardown a network that hasn't yet been
4582 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004583 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004584 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004585 }
4586 }
4587 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004588
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004589 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004590 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004591 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004592 // For now only update icons for default connection.
4593 // TODO: Update WiFi and cellular icons separately. b/17237507
4594 if (!isDefaultNetwork(nai)) return;
4595
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004596 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004597 // Don't repeat publish.
4598 if (newInetCondition == mDefaultInetConditionPublished) return;
4599
4600 mDefaultInetConditionPublished = newInetCondition;
4601 sendInetConditionBroadcast(nai.networkInfo);
4602 }
4603
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004604 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4605 if (mLockdownTracker != null) {
4606 if (nai != null && nai.isVPN()) {
4607 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4608 } else {
4609 mLockdownTracker.onNetworkInfoChanged();
4610 }
4611 }
4612 }
4613
Robert Greenwalt7b816022014-04-18 15:25:25 -07004614 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4615 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004616 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004617 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004618 synchronized (networkAgent) {
4619 oldInfo = networkAgent.networkInfo;
4620 networkAgent.networkInfo = newInfo;
4621 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004622 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004623
4624 if (oldInfo != null && oldInfo.getState() == state) {
4625 if (VDBG) log("ignoring duplicate network state non-change");
4626 return;
4627 }
4628 if (DBG) {
4629 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4630 (oldInfo == null ? "null" : oldInfo.getState()) +
4631 " to " + state);
4632 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004633
Paul Jenseneec75412014-08-04 12:21:19 -04004634 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004635 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004636 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004637 if (networkAgent.isVPN()) {
4638 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004639 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4640 (networkAgent.networkMisc == null ||
4641 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004642 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004643 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4644 networkAgent.networkCapabilities.hasCapability(
4645 NET_CAPABILITY_NOT_RESTRICTED) ?
4646 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004647 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004648 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004649 loge("Error creating network " + networkAgent.network.netId + ": "
4650 + e.getMessage());
4651 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004652 }
Paul Jenseneec75412014-08-04 12:21:19 -04004653 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004654 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004655 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004656
Paul Jensenca8f16a2014-05-09 12:47:55 -04004657 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004658 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004659
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004660 if (networkAgent.isVPN()) {
4661 // Temporarily disable the default proxy (not global).
4662 synchronized (mProxyLock) {
4663 if (!mDefaultProxyDisabled) {
4664 mDefaultProxyDisabled = true;
4665 if (mGlobalProxy == null && mDefaultProxy != null) {
4666 sendProxyBroadcast(null);
4667 }
4668 }
4669 }
4670 // TODO: support proxy per network.
4671 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004672
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004673 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4674 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4675 // capabilities, so it only needs to be done once on initial connect, not every time the
4676 // network's capabilities change. Note that we do this before rematching the network,
4677 // so we could decide to tear it down immediately afterwards. That's fine though - on
4678 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4679 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004680 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004681
Paul Jensen2161a8e2014-09-11 11:00:39 -04004682 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004683 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004684
4685 // This has to happen after matching the requests, because callbacks are just requests.
4686 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004687 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004688 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004689 if (networkAgent.isVPN()) {
4690 synchronized (mProxyLock) {
4691 if (mDefaultProxyDisabled) {
4692 mDefaultProxyDisabled = false;
4693 if (mGlobalProxy == null && mDefaultProxy != null) {
4694 sendProxyBroadcast(mDefaultProxy);
4695 }
4696 }
4697 }
4698 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004699 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4700 state == NetworkInfo.State.SUSPENDED) {
4701 // going into or coming out of SUSPEND: rescore and notify
4702 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004703 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004704 }
4705 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4706 ConnectivityManager.CALLBACK_SUSPENDED :
4707 ConnectivityManager.CALLBACK_RESUMED));
4708 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004709 }
4710 }
4711
Robert Greenwaltac96c522014-06-03 16:43:57 -07004712 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4713 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004714 if (score < 0) {
4715 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4716 "). Bumping score to min of 0");
4717 score = 0;
4718 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004719
Paul Jensen2161a8e2014-09-11 11:00:39 -04004720 final int oldScore = nai.getCurrentScore();
4721 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004722
Paul Jensen85cf78e2015-06-25 13:25:07 -04004723 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004724
Paul Jensenc8b9a742014-09-30 15:37:41 -04004725 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004726 }
4727
Robert Greenwalt9258c642014-03-26 16:47:06 -07004728 // notify only this one new request of the current state
4729 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4730 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4731 // TODO - read state from monitor to decide what to send.
4732// if (nai.networkMonitor.isLingering()) {
4733// notifyType = NetworkCallbacks.LOSING;
4734// } else if (nai.networkMonitor.isEvaluating()) {
4735// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4736// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004737 if (nri.mPendingIntent == null) {
4738 callCallbackForRequest(nri, nai, notifyType);
4739 } else {
4740 sendPendingIntentForRequest(nri, nai, notifyType);
4741 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004742 }
4743
Robert Greenwalt8d482522015-06-24 13:23:42 -07004744 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004745 // The NetworkInfo we actually send out has no bearing on the real
4746 // state of affairs. For example, if the default connection is mobile,
4747 // and a request for HIPRI has just gone away, we need to pretend that
4748 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4749 // the state to DISCONNECTED, even though the network is of type MOBILE
4750 // and is still connected.
4751 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4752 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004753 if (state != DetailedState.DISCONNECTED) {
4754 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004755 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004756 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004757 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004758 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4759 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4760 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4761 if (info.isFailover()) {
4762 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4763 nai.networkInfo.setFailover(false);
4764 }
4765 if (info.getReason() != null) {
4766 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4767 }
4768 if (info.getExtraInfo() != null) {
4769 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4770 }
4771 NetworkAgentInfo newDefaultAgent = null;
4772 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004773 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004774 if (newDefaultAgent != null) {
4775 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4776 newDefaultAgent.networkInfo);
4777 } else {
4778 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4779 }
4780 }
4781 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4782 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004783 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004784 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004785 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004786 }
4787 }
4788 }
4789
Robert Greenwalt7b816022014-04-18 15:25:25 -07004790 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004791 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004792 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004793 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4794 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4795 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004796 if (nri.mPendingIntent == null) {
4797 callCallbackForRequest(nri, networkAgent, notifyType);
4798 } else {
4799 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4800 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004801 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004802 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004803
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004804 private String notifyTypeToName(int notifyType) {
4805 switch (notifyType) {
4806 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4807 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4808 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4809 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4810 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4811 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4812 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4813 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4814 }
4815 return "UNKNOWN";
4816 }
4817
Jeff Sharkey69736342014-12-08 14:50:12 -08004818 /**
4819 * Notify other system services that set of active ifaces has changed.
4820 */
4821 private void notifyIfacesChanged() {
4822 try {
4823 mStatsService.forceUpdateIfaces();
4824 } catch (Exception ignored) {
4825 }
4826 }
4827
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004828 @Override
4829 public boolean addVpnAddress(String address, int prefixLength) {
4830 throwIfLockdownEnabled();
4831 int user = UserHandle.getUserId(Binder.getCallingUid());
4832 synchronized (mVpns) {
4833 return mVpns.get(user).addAddress(address, prefixLength);
4834 }
4835 }
4836
4837 @Override
4838 public boolean removeVpnAddress(String address, int prefixLength) {
4839 throwIfLockdownEnabled();
4840 int user = UserHandle.getUserId(Binder.getCallingUid());
4841 synchronized (mVpns) {
4842 return mVpns.get(user).removeAddress(address, prefixLength);
4843 }
4844 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004845
4846 @Override
4847 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4848 throwIfLockdownEnabled();
4849 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004850 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004851 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004852 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004853 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004854 if (success) {
4855 notifyIfacesChanged();
4856 }
4857 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004858 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004859
4860 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004861 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4862 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4863 enforceKeepalivePermission();
4864 mKeepaliveTracker.startNattKeepalive(
4865 getNetworkAgentInfoForNetwork(network),
4866 intervalSeconds, messenger, binder,
4867 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4868 }
4869
4870 @Override
4871 public void stopKeepalive(Network network, int slot) {
4872 mHandler.sendMessage(mHandler.obtainMessage(
4873 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
4874 }
4875
4876 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07004877 public void factoryReset() {
4878 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004879
4880 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4881 return;
4882 }
4883
Robin Lee3b3dd942015-05-12 18:14:58 +01004884 final int userId = UserHandle.getCallingUserId();
4885
Stuart Scottf1fb3972015-04-02 18:00:02 -07004886 // Turn airplane mode off
4887 setAirplaneMode(false);
4888
Stuart Scotte3e314d2015-04-20 14:07:45 -07004889 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4890 // Untether
4891 for (String tether : getTetheredIfaces()) {
4892 untether(tether);
4893 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004894 }
4895
Stuart Scotte3e314d2015-04-20 14:07:45 -07004896 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4897 // Turn VPN off
4898 VpnConfig vpnConfig = getVpnConfig(userId);
4899 if (vpnConfig != null) {
4900 if (vpnConfig.legacy) {
4901 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4902 } else {
4903 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4904 // in the future without user intervention.
4905 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004906
Stuart Scotte3e314d2015-04-20 14:07:45 -07004907 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4908 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004909 }
4910 }
4911 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004912
4913 @VisibleForTesting
4914 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
4915 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
4916 return new NetworkMonitor(context, handler, nai, defaultRequest);
4917 }
4918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004919}