blob: 08754c2b8608da7d5a1369ec7f92e14b726a779c [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070036import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
43import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070046import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090047import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090050import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070058import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070059import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070064import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040070import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040073import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070075import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040076import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070078import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070079import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070080import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Looper;
82import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070083import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070084import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070085import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070086import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070088import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070090import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040091import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070093import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070094import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070095import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070097import android.util.LocalLog;
98import android.util.LocalLog.ReadOnlyLocalLog;
99import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800100import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700101import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500102import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700103import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700104import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Wink Savilleab9321d2013-06-29 21:10:57 -0700106import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400107import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400108import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700109import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700110import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700111import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700112import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800113import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700114import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700115import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700116import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700117import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700118import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700119import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400120import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900121import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900122import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900123import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700124import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400125import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400126import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700127import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800128import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700129import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700130import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700131import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700132import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700133import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700134
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700135import org.xmlpull.v1.XmlPullParser;
136import org.xmlpull.v1.XmlPullParserException;
137
138import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700140import java.io.FileNotFoundException;
141import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700142import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700144import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700145import java.net.InetAddress;
146import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700147import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700148import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700149import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700150import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700151import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700152import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500153import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700154import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700155import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700156import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700157import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
159/**
160 * @hide
161 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800162public class ConnectivityService extends IConnectivityManager.Stub
163 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700164 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700166 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700167 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
Jake Hamby786e71a2014-02-06 14:43:50 -0800169 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700170
Jeff Sharkey899223b2012-08-04 15:24:58 -0700171 // TODO: create better separation between radio types and network types
172
Robert Greenwalt42acef32009-08-12 16:08:25 -0700173 // how long to wait before switching back to a radio's default network
174 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
175 // system property that can override the above value
176 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
177 "android.telephony.apn-restore";
178
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900179 // How long to wait before putting up a "This network doesn't have an Internet connection,
180 // connect anyway?" dialog after the user selects a network that doesn't validate.
181 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
182
Jeremy Joslin79294842014-12-03 17:15:28 -0800183 // How long to delay to removal of a pending intent based request.
184 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
185 private final int mReleasePendingIntentDelayMs;
186
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800187 private Tethering mTethering;
188
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700189 private final PermissionMonitor mPermissionMonitor;
190
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700191 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700192
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700193 @GuardedBy("mVpns")
194 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700195
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700196 private boolean mLockdownEnabled;
197 private LockdownVpnTracker mLockdownTracker;
198
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700199 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
200 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700201 /** Currently active network rules by UID. */
202 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700203 /** Set of ifaces that are costly. */
204 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700205
Erik Klineda4bfa82015-04-30 12:58:40 +0900206 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700208 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700209 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800211 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
213 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700214 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700216 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800217 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700218 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700219
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700220 private String mCurrentTcpBufferSizes;
221
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700222 private static final int ENABLED = 1;
223 private static final int DISABLED = 0;
224
Paul Jensenb10e37f2014-11-25 12:33:08 -0500225 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400226 // Tear down networks that have no chance (e.g. even if validated) of becoming
227 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500228 // all networks have been rematched against all NetworkRequests.
229 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400230 // Don't reap networks. This should be passed when some networks have not yet been
231 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500232 DONT_REAP
233 };
234
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700235 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700236 * used internally to change our mobile data enabled flag
237 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700238 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700239
240 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700241 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700242 * from one net to another. Clear happens when we get a new
243 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
244 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700245 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700246 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700247
Robert Greenwalt434203a2010-10-11 16:00:27 -0700248 /**
249 * used internally to reload global proxy settings
250 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700251 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700252
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700253 /**
Wink Saville628b0852011-08-04 15:01:58 -0700254 * used internally to send a sticky broadcast delayed.
255 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700256 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700257
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700258 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400259 * PAC manager has received new port.
260 */
261 private static final int EVENT_PROXY_HAS_CHANGED = 16;
262
Robert Greenwalte049c232014-04-11 15:53:27 -0700263 /**
264 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700265 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700266 */
267 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
268
Robert Greenwalt7b816022014-04-18 15:25:25 -0700269 /**
270 * used internally when registering NetworkAgents
271 * obj = Messenger
272 */
273 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
274
Robert Greenwalt9258c642014-03-26 16:47:06 -0700275 /**
276 * used to add a network request
277 * includes a NetworkRequestInfo
278 */
279 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
280
281 /**
282 * indicates a timeout period is over - check if we had a network yet or not
283 * and if not, call the timeout calback (but leave the request live until they
284 * cancel it.
285 * includes a NetworkRequestInfo
286 */
287 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
288
289 /**
290 * used to add a network listener - no request
291 * includes a NetworkRequestInfo
292 */
293 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
294
295 /**
296 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400297 * arg1 = UID of caller
298 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700299 */
300 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
301
Robert Greenwalta67be032014-05-16 15:49:14 -0700302 /**
303 * used internally when registering NetworkFactories
304 * obj = Messenger
305 */
306 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
307
Robert Greenwalt27711812014-06-25 16:45:57 -0700308 /**
309 * used internally to expire a wakelock when transitioning
310 * from one net to another. Expire happens when we fail to find
311 * a new network (typically after 1 minute) -
312 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
313 * a replacement network.
314 */
315 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
316
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700317 /**
318 * Used internally to indicate the system is ready.
319 */
320 private static final int EVENT_SYSTEM_READY = 25;
321
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800322 /**
323 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400324 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800325 */
326 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
327
328 /**
329 * used to remove a pending intent and its associated network request.
330 * arg1 = UID of caller
331 * obj = PendingIntent
332 */
333 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
334
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900335 /**
336 * used to specify whether a network should be used even if unvalidated.
337 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
338 * arg2 = whether to remember this choice in the future (1 or 0)
339 * obj = network
340 */
341 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
342
343 /**
344 * used to ask the user to confirm a connection to an unvalidated network.
345 * obj = network
346 */
347 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700348
Erik Klineda4bfa82015-04-30 12:58:40 +0900349 /**
350 * used internally to (re)configure mobile data always-on settings.
351 */
352 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
353
Paul Jensen694f2b82015-06-17 14:15:39 -0400354 /**
355 * used to add a network listener with a pending intent
356 * obj = NetworkRequestInfo
357 */
358 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
359
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700360 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700361 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700362 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700363 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700364
Mike Lockwood0f79b542009-08-14 14:18:49 -0400365 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800366 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400367
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700368 private PowerManager.WakeLock mNetTransitionWakeLock;
369 private String mNetTransitionWakeLockCausedBy = "";
370 private int mNetTransitionWakeLockSerialNumber;
371 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800372 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700373
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700374 private InetAddress mDefaultDns;
375
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700376 // used in DBG mode to track inet condition reports
377 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
378 private ArrayList mInetLog;
379
Robert Greenwalt434203a2010-10-11 16:00:27 -0700380 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400381 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700382 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700383 private boolean mDefaultProxyDisabled = false;
384
Robert Greenwalt434203a2010-10-11 16:00:27 -0700385 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400386 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700387
Jason Monk602b2322013-07-03 17:04:33 -0400388 private PacManager mPacManager = null;
389
Erik Klineda4bfa82015-04-30 12:58:40 +0900390 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700391
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400392 private UserManager mUserManager;
393
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700394 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700395 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700396
Robert Greenwalt50393202011-06-21 17:26:14 -0700397 // the set of network types that can only be enabled by system/sig apps
398 List mProtectedNetworks;
399
John Spurlockbf991a82013-06-24 14:20:23 -0400400 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700401
Wink Savilleab9321d2013-06-29 21:10:57 -0700402 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400403
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900404 private KeepaliveTracker mKeepaliveTracker;
405
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700406 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
407 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700408 private final static int MAX_NET_ID = 65535;
409 private int mNextNetId = MIN_NET_ID;
410
Robert Greenwalt34524f02014-05-18 16:22:10 -0700411 // sequence number of NetworkRequests
412 private int mNextNetworkRequestId = 1;
413
Erik Kline7523eb32015-07-09 18:24:03 +0900414 // NetworkRequest activity String log entries.
415 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
416 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
417
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700418 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
419 private static final int MAX_VALIDATION_LOGS = 10;
420 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
421 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
422
423 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
424 synchronized(mValidationLogs) {
425 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
426 mValidationLogs.removeLast();
427 }
428 mValidationLogs.addFirst(new Pair(network, log));
429 }
430 }
431
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700432 /**
433 * Implements support for the legacy "one network per network type" model.
434 *
435 * We used to have a static array of NetworkStateTrackers, one for each
436 * network type, but that doesn't work any more now that we can have,
437 * for example, more that one wifi network. This class stores all the
438 * NetworkAgentInfo objects that support a given type, but the legacy
439 * API will only see the first one.
440 *
441 * It serves two main purposes:
442 *
443 * 1. Provide information about "the network for a given type" (since this
444 * API only supports one).
445 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
446 * the first network for a given type changes, or if the default network
447 * changes.
448 */
449 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900450
451 private static final boolean DBG = true;
452 private static final boolean VDBG = false;
453 private static final String TAG = "CSLegacyTypeTracker";
454
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700455 /**
456 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
457 * Each list holds references to all NetworkAgentInfos that are used to
458 * satisfy requests for that network type.
459 *
460 * This array is built out at startup such that an unsupported network
461 * doesn't get an ArrayList instance, making this a tristate:
462 * unsupported, supported but not active and active.
463 *
464 * The actual lists are populated when we scan the network types that
465 * are supported on this device.
466 */
467 private ArrayList<NetworkAgentInfo> mTypeLists[];
468
469 public LegacyTypeTracker() {
470 mTypeLists = (ArrayList<NetworkAgentInfo>[])
471 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
472 }
473
474 public void addSupportedType(int type) {
475 if (mTypeLists[type] != null) {
476 throw new IllegalStateException(
477 "legacy list for type " + type + "already initialized");
478 }
479 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
480 }
481
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700482 public boolean isTypeSupported(int type) {
483 return isNetworkTypeValid(type) && mTypeLists[type] != null;
484 }
485
486 public NetworkAgentInfo getNetworkForType(int type) {
487 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
488 return mTypeLists[type].get(0);
489 } else {
490 return null;
491 }
492 }
493
Robert Greenwalt8d482522015-06-24 13:23:42 -0700494 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900495 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900496 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700497 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900499 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900500 }
501 }
502
503 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700504 public void add(int type, NetworkAgentInfo nai) {
505 if (!isTypeSupported(type)) {
506 return; // Invalid network type.
507 }
508 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
509
510 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
511 if (list.contains(nai)) {
512 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
513 return;
514 }
515
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900516 list.add(nai);
517
518 // 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 +0900519 final boolean isDefaultNetwork = isDefaultNetwork(nai);
520 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700521 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
522 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700523 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700524 }
525
Lorenzo Colittia793a672014-07-31 23:20:17 +0900526 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900527 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900528 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
529 if (list == null || list.isEmpty()) {
530 return;
531 }
532
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900534
535 if (!list.remove(nai)) {
536 return;
537 }
538
Robert Greenwalt8d482522015-06-24 13:23:42 -0700539 final DetailedState state = DetailedState.DISCONNECTED;
540
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900541 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700542 maybeLogBroadcast(nai, state, type, wasDefault);
543 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900544 }
545
546 if (!list.isEmpty() && wasFirstNetwork) {
547 if (DBG) log("Other network available for type " + type +
548 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900549 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700550 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
551 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900552 }
553 }
554
555 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900556 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
557 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700558 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900559 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 }
561 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700562
Robert Greenwalt8d482522015-06-24 13:23:42 -0700563 // send out another legacy broadcast - currently only used for suspend/unsuspend
564 // toggle
565 public void update(NetworkAgentInfo nai) {
566 final boolean isDefault = isDefaultNetwork(nai);
567 final DetailedState state = nai.networkInfo.getDetailedState();
568 for (int type = 0; type < mTypeLists.length; type++) {
569 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700570 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700571 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700572 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700573 maybeLogBroadcast(nai, state, type, isDefault);
574 sendLegacyNetworkBroadcast(nai, state, type);
575 }
576 }
577 }
578
Lorenzo Colittia793a672014-07-31 23:20:17 +0900579 private String naiToString(NetworkAgentInfo nai) {
580 String name = (nai != null) ? nai.name() : "null";
581 String state = (nai.networkInfo != null) ?
582 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
583 "???/???";
584 return name + " " + state;
585 }
586
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700587 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900588 pw.println("mLegacyTypeTracker:");
589 pw.increaseIndent();
590 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700591 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900592 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700593 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900594 pw.println();
595 pw.println("Current state:");
596 pw.increaseIndent();
597 for (int type = 0; type < mTypeLists.length; type++) {
598 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
599 for (NetworkAgentInfo nai : mTypeLists[type]) {
600 pw.println(type + " " + naiToString(nai));
601 }
602 }
603 pw.decreaseIndent();
604 pw.decreaseIndent();
605 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700606 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900607
608 // This class needs its own log method because it has a different TAG.
609 private void log(String s) {
610 Slog.d(TAG, s);
611 }
612
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700613 }
614 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
615
Jeff Sharkey899223b2012-08-04 15:24:58 -0700616 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700617 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800618 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800619
Erik Klineda4bfa82015-04-30 12:58:40 +0900620 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900621 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
622 new Binder(), NetworkRequestInfo.REQUEST);
623 mNetworkRequests.put(mDefaultRequest, defaultNRI);
624 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900625
626 mDefaultMobileDataRequest = createInternetRequestForTransport(
627 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700628
Wink Savillebb08caf2010-09-02 19:23:52 -0700629 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
630 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700631 mHandler = new InternalHandler(handlerThread.getLooper());
632 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700633
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800634 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800635 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
636 String id = Settings.Secure.getString(context.getContentResolver(),
637 Settings.Secure.ANDROID_ID);
638 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700639 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800640 SystemProperties.set("net.hostname", name);
641 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800642 }
643
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700644 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700645 String dns = Settings.Global.getString(context.getContentResolver(),
646 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700647 if (dns == null || dns.length() == 0) {
648 dns = context.getResources().getString(
649 com.android.internal.R.string.config_default_dns_server);
650 }
651 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800652 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
653 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800654 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700655 }
656
Jeremy Joslin79294842014-12-03 17:15:28 -0800657 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
658 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
659
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700660 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700661 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800662 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700663 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700664 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700665 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700666
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700667 try {
668 mPolicyManager.registerListener(mPolicyListener);
669 } catch (RemoteException e) {
670 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700671 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700672 }
673
674 final PowerManager powerManager = (PowerManager) context.getSystemService(
675 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700676 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
677 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
678 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800679 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700680
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700681 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700682
Wink Saville51f456f2013-04-23 14:26:51 -0700683 // TODO: What is the "correct" way to do determine if this is a wifi only device?
684 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
685 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700686 String[] naStrings = context.getResources().getStringArray(
687 com.android.internal.R.array.networkAttributes);
688 for (String naString : naStrings) {
689 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700690 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700691 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700692 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800693 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700694 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700695 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700696 }
Wink Saville51f456f2013-04-23 14:26:51 -0700697 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
698 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
699 n.type);
700 continue;
701 }
Wink Saville975c8482011-04-07 14:23:45 -0700702 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800703 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700704 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700705 continue;
706 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700707 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700708
Wink Saville975c8482011-04-07 14:23:45 -0700709 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700710 mNetworksDefined++;
711 } catch(Exception e) {
712 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700713 }
714 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700715
716 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
717 if (mNetConfigs[TYPE_VPN] == null) {
718 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
719 // don't need to add TYPE_VPN to mNetConfigs.
720 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
721 mNetworksDefined++; // used only in the log() statement below.
722 }
723
Wink Saville5e56bc52013-07-29 15:00:57 -0700724 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700725
Robert Greenwalt50393202011-06-21 17:26:14 -0700726 mProtectedNetworks = new ArrayList<Integer>();
727 int[] protectedNetworks = context.getResources().getIntArray(
728 com.android.internal.R.array.config_protectedNetworks);
729 for (int p : protectedNetworks) {
730 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
731 mProtectedNetworks.add(p);
732 } else {
733 if (DBG) loge("Ignoring protectedNetwork " + p);
734 }
735 }
736
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700737 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
738 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700739
Robert Greenwaltfab501672014-07-23 11:44:01 -0700740 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800741
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700742 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
743
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700744 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700745 IntentFilter intentFilter = new IntentFilter();
746 intentFilter.addAction(Intent.ACTION_USER_STARTING);
747 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
748 mContext.registerReceiverAsUser(
749 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900750
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700751 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700752 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700753 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700754 } catch (RemoteException e) {
755 loge("Error registering observer :" + e);
756 }
757
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700758 if (DBG) {
759 mInetLog = new ArrayList();
760 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700761
Erik Klineda4bfa82015-04-30 12:58:40 +0900762 mSettingsObserver = new SettingsObserver(mContext, mHandler);
763 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800764
John Spurlockbf991a82013-06-24 14:20:23 -0400765 mDataConnectionStats = new DataConnectionStats(mContext);
766 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400767
Jason Monkdecd2952013-10-10 14:02:51 -0400768 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700769
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400770 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900771
772 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700774
Erik Klineda4bfa82015-04-30 12:58:40 +0900775 private NetworkRequest createInternetRequestForTransport(int transportType) {
776 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900777 netCap.addCapability(NET_CAPABILITY_INTERNET);
778 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900779 if (transportType > -1) {
780 netCap.addTransportType(transportType);
781 }
782 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
783 }
784
785 private void handleMobileDataAlwaysOn() {
786 final boolean enable = (Settings.Global.getInt(
787 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
788 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
789 if (enable == isEnabled) {
790 return; // Nothing to do.
791 }
792
793 if (enable) {
794 handleRegisterNetworkRequest(new NetworkRequestInfo(
795 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
796 } else {
797 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
798 }
799 }
800
801 private void registerSettingsCallbacks() {
802 // Watch for global HTTP proxy changes.
803 mSettingsObserver.observe(
804 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
805 EVENT_APPLY_GLOBAL_HTTP_PROXY);
806
807 // Watch for whether or not to keep mobile data always on.
808 mSettingsObserver.observe(
809 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
810 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
811 }
812
Robert Greenwalt34524f02014-05-18 16:22:10 -0700813 private synchronized int nextNetworkRequestId() {
814 return mNextNetworkRequestId++;
815 }
816
Paul Jensen67b0b072015-06-10 11:22:17 -0400817 @VisibleForTesting
818 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400819 synchronized (mNetworkForNetId) {
820 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
821 int netId = mNextNetId;
822 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
823 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500824 if (!mNetIdInUse.get(netId)) {
825 mNetIdInUse.put(netId, true);
826 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400827 }
828 }
829 }
830 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700831 }
832
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800833 private NetworkState getFilteredNetworkState(int networkType, int uid) {
834 NetworkInfo info = null;
835 LinkProperties lp = null;
836 NetworkCapabilities nc = null;
837 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800838 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800839
840 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
841 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
842 if (nai != null) {
843 synchronized (nai) {
844 info = new NetworkInfo(nai.networkInfo);
845 lp = new LinkProperties(nai.linkProperties);
846 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400847 // Network objects are outwardly immutable so there is no point to duplicating.
848 // Duplicating also precludes sharing socket factories and connection pools.
849 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800850 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800851 }
852 info.setType(networkType);
853 } else {
854 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
855 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
856 info.setIsAvailable(true);
857 lp = new LinkProperties();
858 nc = new NetworkCapabilities();
859 network = null;
860 }
861 info = getFilteredNetworkInfo(info, lp, uid);
862 }
863
Jeff Sharkey32566012014-12-02 18:30:14 -0800864 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400865 }
866
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800867 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
868 if (network == null) {
869 return null;
870 }
871 synchronized (mNetworkForNetId) {
872 return mNetworkForNetId.get(network.netId);
873 }
874 };
875
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900876 private Network[] getVpnUnderlyingNetworks(int uid) {
877 if (!mLockdownEnabled) {
878 int user = UserHandle.getUserId(uid);
879 synchronized (mVpns) {
880 Vpn vpn = mVpns.get(user);
881 if (vpn != null && vpn.appliesToUid(uid)) {
882 return vpn.getUnderlyingNetworks();
883 }
884 }
885 }
886 return null;
887 }
888
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800889 private NetworkState getUnfilteredActiveNetworkState(int uid) {
890 NetworkInfo info = null;
891 LinkProperties lp = null;
892 NetworkCapabilities nc = null;
893 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800894 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800895
Paul Jensen85cf78e2015-06-25 13:25:07 -0400896 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800897
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900898 final Network[] networks = getVpnUnderlyingNetworks(uid);
899 if (networks != null) {
900 // getUnderlyingNetworks() returns:
901 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
902 // empty array => the VPN explicitly said "no default network".
903 // non-empty array => the VPN specified one or more default networks; we use the
904 // first one.
905 if (networks.length > 0) {
906 nai = getNetworkAgentInfoForNetwork(networks[0]);
907 } else {
908 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800909 }
910 }
911
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800912 if (nai != null) {
913 synchronized (nai) {
914 info = new NetworkInfo(nai.networkInfo);
915 lp = new LinkProperties(nai.linkProperties);
916 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400917 // Network objects are outwardly immutable so there is no point to duplicating.
918 // Duplicating also precludes sharing socket factories and connection pools.
919 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800920 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800921 }
922 }
923
Jeff Sharkey32566012014-12-02 18:30:14 -0800924 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400925 }
926
927 /**
928 * Check if UID should be blocked from using the network with the given LinkProperties.
929 */
930 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700931 final boolean networkCostly;
932 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700933
Robert Greenwalt12e67352014-05-13 21:41:06 -0700934 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700935 synchronized (mRulesLock) {
936 networkCostly = mMeteredIfaces.contains(iface);
937 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700938 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700939
Amith Yamasani15e472352015-04-24 19:06:07 -0700940 if ((uidRules & RULE_REJECT_ALL) != 0
941 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700942 return true;
943 }
944
945 // no restrictive rules; network is visible
946 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700947 }
948
949 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700950 * Return a filtered {@link NetworkInfo}, potentially marked
951 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800952 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700953 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800954 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
955 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400956 // network is blocked; clone and override state
957 info = new NetworkInfo(info);
958 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900959 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900960 log("returning Blocked NetworkInfo for ifname=" +
961 lp.getInterfaceName() + ", uid=" + uid);
962 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700963 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800964 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700965 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900966 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700967 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700968 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700969 }
970
971 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 * Return NetworkInfo for the active (i.e., connected) network interface.
973 * It is assumed that at most one network is active at a time. If more
974 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700975 * @return the info for the active network, or {@code null} if none is
976 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700978 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700980 enforceAccessPermission();
981 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800982 NetworkState state = getUnfilteredActiveNetworkState(uid);
983 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 }
985
Paul Jensen31a94f42015-02-13 14:18:39 -0500986 @Override
987 public Network getActiveNetwork() {
988 enforceAccessPermission();
989 final int uid = Binder.getCallingUid();
990 final int user = UserHandle.getUserId(uid);
991 int vpnNetId = NETID_UNSET;
992 synchronized (mVpns) {
993 final Vpn vpn = mVpns.get(user);
994 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
995 }
996 NetworkAgentInfo nai;
997 if (vpnNetId != NETID_UNSET) {
998 synchronized (mNetworkForNetId) {
999 nai = mNetworkForNetId.get(vpnNetId);
1000 }
1001 if (nai != null) return nai.network;
1002 }
1003 nai = getDefaultNetwork();
1004 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1005 return nai != null ? nai.network : null;
1006 }
1007
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001008 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1009 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001010 final int uid = Binder.getCallingUid();
1011 NetworkState state = getUnfilteredActiveNetworkState(uid);
1012 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001013 }
1014
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001015 @Override
1016 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1017 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 NetworkState state = getUnfilteredActiveNetworkState(uid);
1019 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001020 }
1021
1022 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 public NetworkInfo getNetworkInfo(int networkType) {
1024 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001025 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001026 if (getVpnUnderlyingNetworks(uid) != null) {
1027 // A VPN is active, so we may need to return one of its underlying networks. This
1028 // information is not available in LegacyTypeTracker, so we have to get it from
1029 // getUnfilteredActiveNetworkState.
1030 NetworkState state = getUnfilteredActiveNetworkState(uid);
1031 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1032 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1033 }
1034 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001035 NetworkState state = getFilteredNetworkState(networkType, uid);
1036 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
1038
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001039 @Override
1040 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1041 enforceAccessPermission();
1042 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001043 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001044 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1045 if (nai != null) {
1046 synchronized (nai) {
1047 info = new NetworkInfo(nai.networkInfo);
1048 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001049 }
1050 }
1051 return info;
1052 }
1053
1054 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 public NetworkInfo[] getAllNetworkInfo() {
1056 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001057 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001058 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1059 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001060 NetworkInfo info = getNetworkInfo(networkType);
1061 if (info != null) {
1062 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001065 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
1067
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001068 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001069 public Network getNetworkForType(int networkType) {
1070 enforceAccessPermission();
1071 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001072 NetworkState state = getFilteredNetworkState(networkType, uid);
1073 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1074 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001075 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001076 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001077 }
1078
1079 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001080 public Network[] getAllNetworks() {
1081 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001082 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001083 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001084 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001085 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001086 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001087 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001088 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001089 }
1090
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001091 @Override
1092 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1093 // The basic principle is: if an app's traffic could possibly go over a
1094 // network, without the app doing anything multinetwork-specific,
1095 // (hence, by "default"), then include that network's capabilities in
1096 // the array.
1097 //
1098 // In the normal case, app traffic only goes over the system's default
1099 // network connection, so that's the only network returned.
1100 //
1101 // With a VPN in force, some app traffic may go into the VPN, and thus
1102 // over whatever underlying networks the VPN specifies, while other app
1103 // traffic may go over the system default network (e.g.: a split-tunnel
1104 // VPN, or an app disallowed by the VPN), so the set of networks
1105 // returned includes the VPN's underlying networks and the system
1106 // default.
1107 enforceAccessPermission();
1108
1109 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1110
1111 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001112 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001113 if (nc != null) {
1114 result.put(nai.network, nc);
1115 }
1116
1117 if (!mLockdownEnabled) {
1118 synchronized (mVpns) {
1119 Vpn vpn = mVpns.get(userId);
1120 if (vpn != null) {
1121 Network[] networks = vpn.getUnderlyingNetworks();
1122 if (networks != null) {
1123 for (Network network : networks) {
1124 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001125 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001126 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001127 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001128 }
1129 }
1130 }
1131 }
1132 }
1133 }
1134
1135 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1136 out = result.values().toArray(out);
1137 return out;
1138 }
1139
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001140 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001141 public boolean isNetworkSupported(int networkType) {
1142 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001143 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001144 }
1145
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001146 /**
1147 * Return LinkProperties for the active (i.e., connected) default
1148 * network interface. It is assumed that at most one default network
1149 * is active at a time. If more than one is active, it is indeterminate
1150 * which will be returned.
1151 * @return the ip properties for the active network, or {@code null} if
1152 * none is active
1153 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001154 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001155 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001156 enforceAccessPermission();
1157 final int uid = Binder.getCallingUid();
1158 NetworkState state = getUnfilteredActiveNetworkState(uid);
1159 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001160 }
1161
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001162 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001163 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001164 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001165 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1166 if (nai != null) {
1167 synchronized (nai) {
1168 return new LinkProperties(nai.linkProperties);
1169 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001170 }
1171 return null;
1172 }
1173
Robert Greenwalt12e67352014-05-13 21:41:06 -07001174 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001175 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001176 public LinkProperties getLinkProperties(Network network) {
1177 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001178 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001179 if (nai != null) {
1180 synchronized (nai) {
1181 return new LinkProperties(nai.linkProperties);
1182 }
1183 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001184 return null;
1185 }
1186
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001187 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001188 if (nai != null) {
1189 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001190 if (nai.networkCapabilities != null) {
1191 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001192 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001193 }
1194 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001195 return null;
1196 }
1197
1198 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001199 public NetworkCapabilities getNetworkCapabilities(Network network) {
1200 enforceAccessPermission();
1201 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1202 }
1203
1204 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001205 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001206 // Require internal since we're handing out IMSI details
1207 enforceConnectivityInternalPermission();
1208
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001209 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001210 for (Network network : getAllNetworks()) {
1211 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1212 if (nai != null) {
1213 synchronized (nai) {
1214 final String subscriberId = (nai.networkMisc != null)
1215 ? nai.networkMisc.subscriberId : null;
1216 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1217 nai.networkCapabilities, network, subscriberId, null));
1218 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001219 }
1220 }
1221 return result.toArray(new NetworkState[result.size()]);
1222 }
1223
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001224 @Override
1225 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1226 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001227 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001228 final long token = Binder.clearCallingIdentity();
1229 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001230 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1231 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001232 try {
1233 return mPolicyManager.getNetworkQuotaInfo(state);
1234 } catch (RemoteException e) {
1235 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001236 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001237 return null;
1238 } finally {
1239 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001240 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001241 }
1242
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001243 @Override
1244 public boolean isActiveNetworkMetered() {
1245 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001246 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001247 final long token = Binder.clearCallingIdentity();
1248 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001249 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001250 } finally {
1251 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001252 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001253 }
1254
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001255 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1256 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1257 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001258 try {
1259 return mPolicyManager.isNetworkMetered(state);
1260 } catch (RemoteException e) {
1261 }
1262 }
1263 return false;
1264 }
1265
Jeff Sharkey216c1812012-08-05 14:29:23 -07001266 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1267 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001268 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001269 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001270 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001271 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001272 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001273
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001274 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 * Ensure that a network route exists to deliver traffic to the specified
1276 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001277 * @param networkType the type of the network over which traffic to the
1278 * specified host is to be routed
1279 * @param hostAddress the IP address of the host to which the route is
1280 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 * @return {@code true} on success, {@code false} on failure
1282 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001283 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001285 if (mProtectedNetworks.contains(networkType)) {
1286 enforceConnectivityInternalPermission();
1287 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001288
Chad Brubakerc0234532014-02-14 13:24:29 -08001289 InetAddress addr;
1290 try {
1291 addr = InetAddress.getByAddress(hostAddress);
1292 } catch (UnknownHostException e) {
1293 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1294 return false;
1295 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001298 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 return false;
1300 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001301
1302 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1303 if (nai == null) {
1304 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1305 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1306 } else {
1307 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1308 }
1309 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001310 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001311
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001312 DetailedState netState;
1313 synchronized (nai) {
1314 netState = nai.networkInfo.getDetailedState();
1315 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001316
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001317 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001318 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001319 log("requestRouteToHostAddress on down network "
1320 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001321 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001322 }
1323 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001325
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001326 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001327 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001328 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001329 LinkProperties lp;
1330 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001331 synchronized (nai) {
1332 lp = nai.linkProperties;
1333 netId = nai.network.netId;
1334 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001335 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001336 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1337 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001338 } finally {
1339 Binder.restoreCallingIdentity(token);
1340 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001341 }
1342
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001343 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001344 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001345 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001346 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001347 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001348 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001349 if (bestRoute.getGateway().equals(addr)) {
1350 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001351 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001352 } else {
1353 // if we will connect to this through another route, add a direct route
1354 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001355 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001356 }
1357 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001358 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001359 try {
1360 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1361 } catch (Exception e) {
1362 // never crash - catch them all
1363 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001364 return false;
1365 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001366 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
1368
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001369 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1370 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001371 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001372 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001373 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001374 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001375 }
1376
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001377 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001378 // skip update when we've already applied rules
1379 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1380 if (oldRules == uidRules) return;
1381
1382 mUidRules.put(uid, uidRules);
1383 }
1384
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001385 // TODO: notify UID when it has requested targeted updates
1386 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001387
1388 @Override
1389 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001390 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001391 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001392 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001393 }
1394
1395 synchronized (mRulesLock) {
1396 mMeteredIfaces.clear();
1397 for (String iface : meteredIfaces) {
1398 mMeteredIfaces.add(iface);
1399 }
1400 }
1401 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001402
1403 @Override
1404 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1405 // caller is NPMS, since we only register with them
1406 if (LOGD_RULES) {
1407 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1408 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001409 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001410 };
1411
Robin Lee3b3dd942015-05-12 18:14:58 +01001412 /**
1413 * Require that the caller is either in the same user or has appropriate permission to interact
1414 * across users.
1415 *
1416 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1417 */
1418 private void enforceCrossUserPermission(int userId) {
1419 if (userId == UserHandle.getCallingUserId()) {
1420 // Not a cross-user call.
1421 return;
1422 }
1423 mContext.enforceCallingOrSelfPermission(
1424 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1425 "ConnectivityService");
1426 }
1427
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001428 private void enforceInternetPermission() {
1429 mContext.enforceCallingOrSelfPermission(
1430 android.Manifest.permission.INTERNET,
1431 "ConnectivityService");
1432 }
1433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001435 mContext.enforceCallingOrSelfPermission(
1436 android.Manifest.permission.ACCESS_NETWORK_STATE,
1437 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439
1440 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001441 mContext.enforceCallingOrSelfPermission(
1442 android.Manifest.permission.CHANGE_NETWORK_STATE,
1443 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 }
1445
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001446 private void enforceTetherAccessPermission() {
1447 mContext.enforceCallingOrSelfPermission(
1448 android.Manifest.permission.ACCESS_NETWORK_STATE,
1449 "ConnectivityService");
1450 }
1451
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001452 private void enforceConnectivityInternalPermission() {
1453 mContext.enforceCallingOrSelfPermission(
1454 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1455 "ConnectivityService");
1456 }
1457
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001458 private void enforceKeepalivePermission() {
1459 mContext.enforceCallingPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
1460 }
1461
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001462 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001463 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001464 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001465 }
1466
1467 private void sendInetConditionBroadcast(NetworkInfo info) {
1468 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1469 }
1470
Wink Saville628b0852011-08-04 15:01:58 -07001471 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001472 if (mLockdownTracker != null) {
1473 info = mLockdownTracker.augmentNetworkInfo(info);
1474 }
1475
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001476 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001477 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001478 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 if (info.isFailover()) {
1480 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1481 info.setFailover(false);
1482 }
1483 if (info.getReason() != null) {
1484 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1485 }
1486 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001487 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1488 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001490 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001491 return intent;
1492 }
1493
1494 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1495 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1496 }
1497
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001498 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001499 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1500 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1501 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001502 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001503 final long ident = Binder.clearCallingIdentity();
1504 try {
1505 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1506 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1507 } finally {
1508 Binder.restoreCallingIdentity(ident);
1509 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001510 }
1511
Mike Lockwood0f79b542009-08-14 14:18:49 -04001512 private void sendStickyBroadcast(Intent intent) {
1513 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001514 if (!mSystemReady) {
1515 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001516 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001517 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001518 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001519 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001520 }
1521
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001522 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001523 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1524 final IBatteryStats bs = BatteryStatsService.getService();
1525 try {
1526 NetworkInfo ni = intent.getParcelableExtra(
1527 ConnectivityManager.EXTRA_NETWORK_INFO);
1528 bs.noteConnectivityChanged(intent.getIntExtra(
1529 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1530 ni != null ? ni.getState().toString() : "?");
1531 } catch (RemoteException e) {
1532 }
1533 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001534 try {
1535 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1536 } finally {
1537 Binder.restoreCallingIdentity(ident);
1538 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001539 }
1540 }
1541
1542 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001543 loadGlobalProxy();
1544
Mike Lockwood0f79b542009-08-14 14:18:49 -04001545 synchronized(this) {
1546 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001547 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001548 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001549 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001550 }
1551 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001552 // load the global proxy at startup
1553 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001554
1555 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1556 // for user to unlock device.
1557 if (!updateLockdownVpn()) {
1558 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1559 mContext.registerReceiver(mUserPresentReceiver, filter);
1560 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001561
Erik Klineda4bfa82015-04-30 12:58:40 +09001562 // Configure whether mobile data is always on.
1563 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1564
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001565 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001566
1567 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 }
1569
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001570 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1571 @Override
1572 public void onReceive(Context context, Intent intent) {
1573 // Try creating lockdown tracker, since user present usually means
1574 // unlocked keystore.
1575 if (updateLockdownVpn()) {
1576 mContext.unregisterReceiver(this);
1577 }
1578 }
1579 };
1580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001582 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001583 *
1584 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001585 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001586 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001587 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1588 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001589
1590 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001591 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001592
Robert Greenwalt7b816022014-04-18 15:25:25 -07001593 if (networkAgent.networkCapabilities.hasTransport(
1594 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001595 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1596 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001597 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001598 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001599 } else if (networkAgent.networkCapabilities.hasTransport(
1600 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001601 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1602 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001603 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001604 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001605 } else {
1606 // do not track any other networks
1607 timeout = 0;
1608 }
1609
Robert Greenwalt7b816022014-04-18 15:25:25 -07001610 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001611 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001612 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001613 } catch (Exception e) {
1614 // You shall not crash!
1615 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001616 }
1617 }
1618 }
1619
1620 /**
1621 * Remove data activity tracking when network disconnects.
1622 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001623 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1624 final String iface = networkAgent.linkProperties.getInterfaceName();
1625 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001626
Robert Greenwalt7b816022014-04-18 15:25:25 -07001627 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1628 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001629 try {
1630 // the call fails silently if no idletimer setup for this interface
1631 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001632 } catch (Exception e) {
1633 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001634 }
1635 }
1636 }
1637
1638 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001639 * Reads the network specific MTU size from reources.
1640 * and set it on it's iface.
1641 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001642 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1643 final String iface = newLp.getInterfaceName();
1644 final int mtu = newLp.getMtu();
1645 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1646 if (VDBG) log("identical MTU - not setting");
1647 return;
1648 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001649
Robert Greenwalt43074032014-08-15 17:53:05 -07001650 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001651 loge("Unexpected mtu value: " + mtu + ", " + iface);
1652 return;
1653 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001654
w1997615afd812014-08-05 15:18:11 -07001655 // Cannot set MTU without interface name
1656 if (TextUtils.isEmpty(iface)) {
1657 loge("Setting MTU size with null iface.");
1658 return;
1659 }
1660
Robert Greenwalt7b816022014-04-18 15:25:25 -07001661 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001662 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001663 mNetd.setMtu(iface, mtu);
1664 } catch (Exception e) {
1665 Slog.e(TAG, "exception in setMtu()" + e);
1666 }
1667 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001668
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001669 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001670 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1671
1672 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001673 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001674 protected int getDefaultTcpRwnd() {
1675 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1676 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001677
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001678 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1679 if (isDefaultNetwork(nai) == false) {
1680 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001681 }
1682
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001683 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1684 String[] values = null;
1685 if (tcpBufferSizes != null) {
1686 values = tcpBufferSizes.split(",");
1687 }
1688
1689 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001690 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001691 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1692 values = tcpBufferSizes.split(",");
1693 }
1694
1695 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1696
1697 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001698 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001699
1700 final String prefix = "/sys/kernel/ipv4/tcp_";
1701 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1702 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1703 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1704 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1705 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1706 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1707 mCurrentTcpBufferSizes = tcpBufferSizes;
1708 } catch (IOException e) {
1709 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001710 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001711
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001712 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001713 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001714 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1715 if (rwndValue != 0) {
1716 SystemProperties.set(sysctlKey, rwndValue.toString());
1717 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001718 }
1719
Mattias Falk8b47b362011-08-23 14:15:13 +02001720 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001721 /*
1722 * Tell the VMs to toss their DNS caches
1723 */
1724 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1725 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001726 /*
1727 * Connectivity events can happen before boot has completed ...
1728 */
1729 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001730 final long ident = Binder.clearCallingIdentity();
1731 try {
1732 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1733 } finally {
1734 Binder.restoreCallingIdentity(ident);
1735 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001736 }
1737
Robert Greenwalt562cc542014-05-15 18:07:26 -07001738 @Override
1739 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001740 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1741 NETWORK_RESTORE_DELAY_PROP_NAME);
1742 if(restoreDefaultNetworkDelayStr != null &&
1743 restoreDefaultNetworkDelayStr.length() != 0) {
1744 try {
1745 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1746 } catch (NumberFormatException e) {
1747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001749 // if the system property isn't set, use the value for the apn type
1750 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1751
1752 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1753 (mNetConfigs[networkType] != null)) {
1754 ret = mNetConfigs[networkType].restoreTime;
1755 }
1756 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 }
1758
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001759 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001760 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001761 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001762 }
1763 return false;
1764 }
1765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001767 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1768 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001769 if (mContext.checkCallingOrSelfPermission(
1770 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001772 pw.println("Permission Denial: can't dump ConnectivityService " +
1773 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1774 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 return;
1776 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001777
Erik Kline379747a2015-06-05 17:47:34 +09001778 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001779 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001780 final long DIAG_TIME_MS = 5000;
1781 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1782 // Start gathering diagnostic information.
1783 netDiags.add(new NetworkDiagnostics(
1784 nai.network,
1785 new LinkProperties(nai.linkProperties),
1786 DIAG_TIME_MS));
1787 }
1788
1789 for (NetworkDiagnostics netDiag : netDiags) {
1790 pw.println();
1791 netDiag.waitForMeasurements();
1792 netDiag.dump(pw);
1793 }
1794
1795 return;
1796 }
1797
Lorenzo Colittie3805462015-06-03 11:18:24 +09001798 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001799 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001800 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001801 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001802 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001803 pw.println();
1804
Paul Jensen85cf78e2015-06-25 13:25:07 -04001805 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001806 pw.print("Active default network: ");
1807 if (defaultNai == null) {
1808 pw.println("none");
1809 } else {
1810 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001812 pw.println();
1813
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001814 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001815 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001816 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1817 pw.println(nai.toString());
1818 pw.increaseIndent();
1819 pw.println("Requests:");
1820 pw.increaseIndent();
1821 for (int i = 0; i < nai.networkRequests.size(); i++) {
1822 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001823 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001824 pw.decreaseIndent();
1825 pw.println("Lingered:");
1826 pw.increaseIndent();
1827 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1828 pw.decreaseIndent();
1829 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001830 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001831 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001832 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001833
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001834 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001835 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001836 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1837 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001838 }
1839 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001840 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001841
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001842 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001843
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001844 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001845 pw.print("mNetTransitionWakeLock: currently " +
1846 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1847 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1848 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1849 } else {
1850 pw.println(", last requested never");
1851 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001852 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001853
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001854 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001855 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001856
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001857 pw.println();
1858 mKeepaliveTracker.dump(pw);
1859
Lorenzo Colittie3805462015-06-03 11:18:24 +09001860 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001861 pw.println();
1862 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001863 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001864 for(int i = 0; i < mInetLog.size(); i++) {
1865 pw.println(mInetLog.get(i));
1866 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001867 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001868 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001869
1870 if (argsContain(args, "--short") == false) {
1871 pw.println();
1872 synchronized (mValidationLogs) {
1873 pw.println("mValidationLogs (most recent first):");
1874 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1875 pw.println(p.first);
1876 pw.increaseIndent();
1877 p.second.dump(fd, pw, args);
1878 pw.decreaseIndent();
1879 }
1880 }
Erik Kline7523eb32015-07-09 18:24:03 +09001881
1882 pw.println();
1883 pw.println("mNetworkRequestInfoLogs (most recent first):");
1884 pw.increaseIndent();
1885 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1886 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 }
1889
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001890 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001891 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001892 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001893 if (officialNai != null && officialNai.equals(nai)) return true;
1894 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001895 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001896 " - " + nai);
1897 }
1898 return false;
1899 }
1900
Paul Jensenc8b9a742014-09-30 15:37:41 -04001901 private boolean isRequest(NetworkRequest request) {
1902 return mNetworkRequests.get(request).isRequest;
1903 }
1904
Robert Greenwalt42acef32009-08-12 16:08:25 -07001905 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001906 private class NetworkStateTrackerHandler extends Handler {
1907 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001908 super(looper);
1909 }
1910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 @Override
1912 public void handleMessage(Message msg) {
1913 NetworkInfo info;
1914 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001915 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001916 handleAsyncChannelHalfConnect(msg);
1917 break;
1918 }
1919 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1920 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1921 if (nai != null) nai.asyncChannel.disconnect();
1922 break;
1923 }
1924 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1925 handleAsyncChannelDisconnected(msg);
1926 break;
1927 }
1928 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1929 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1930 if (nai == null) {
1931 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1932 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001933 final NetworkCapabilities networkCapabilities =
1934 (NetworkCapabilities)msg.obj;
1935 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1936 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1937 Slog.wtf(TAG, "BUG: " + nai + " has stateful capability.");
1938 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001939 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1940 networkCapabilities)) {
1941 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1942 + nai.networkCapabilities + " -> " + networkCapabilities);
1943 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001944 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001945 }
1946 break;
1947 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001948 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1949 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1950 if (nai == null) {
1951 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1952 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001953 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001954 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001955 "; created=" + nai.created);
1956 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001957 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001958 synchronized (nai) {
1959 nai.linkProperties = (LinkProperties)msg.obj;
1960 }
Paul Jenseneec75412014-08-04 12:21:19 -04001961 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001962 }
1963 break;
1964 }
1965 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1966 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1967 if (nai == null) {
1968 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1969 break;
1970 }
1971 info = (NetworkInfo) msg.obj;
1972 updateNetworkInfo(nai, info);
1973 break;
1974 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001975 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1976 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1977 if (nai == null) {
1978 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1979 break;
1980 }
1981 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001982 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001983 break;
1984 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001985 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1986 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1987 if (nai == null) {
1988 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1989 break;
1990 }
1991 try {
1992 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001993 } catch (Exception e) {
1994 // Never crash!
1995 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001996 }
1997 break;
1998 }
1999 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2000 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2001 if (nai == null) {
2002 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
2003 break;
2004 }
2005 try {
2006 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002007 } catch (Exception e) {
2008 // Never crash!
2009 loge("Exception in removeVpnUidRanges: " + e);
2010 }
2011 break;
2012 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002013 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2014 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2015 if (nai == null) {
2016 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
2017 break;
2018 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002019 if (nai.created && !nai.networkMisc.explicitlySelected) {
2020 loge("ERROR: created network explicitly selected.");
2021 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002022 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002023 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002024 break;
2025 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002026 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2027 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2028 if (nai == null) {
2029 loge("EVENT_PACKET_KEEPALIVE from unknown NetworkAgent");
2030 break;
2031 }
2032 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2033 break;
2034 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002035 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002036 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002037 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2038 final boolean valid =
2039 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002040 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2041 if (valid != nai.lastValidated) {
2042 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002043 nai.lastValidated = valid;
2044 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002045 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002046 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2047 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002048 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002049 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002050 // Let the NetworkAgent know the state of its network
2051 nai.asyncChannel.sendMessage(
2052 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2053 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2054 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002055 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002056 break;
2057 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002058 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002059 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002060 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2061 handleLingerComplete(nai);
2062 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002063 break;
2064 }
Paul Jensen869868be2014-05-15 10:33:05 -04002065 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002066 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002067 final boolean visible = (msg.arg1 != 0);
2068 final NetworkAgentInfo nai;
2069 synchronized (mNetworkForNetId) {
2070 nai = mNetworkForNetId.get(netId);
2071 }
2072 // If captive portal status has changed, update capabilities.
2073 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2074 nai.lastCaptivePortalDetected = visible;
2075 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002076 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002077 }
2078 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002079 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002080 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002081 if (nai == null) {
2082 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2083 break;
2084 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002085 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002086 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2087 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002088 }
Paul Jensen869868be2014-05-15 10:33:05 -04002089 break;
2090 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002091 }
2092 }
2093 }
2094
Paul Jensen85cf78e2015-06-25 13:25:07 -04002095 private void linger(NetworkAgentInfo nai) {
2096 nai.lingering = true;
2097 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2098 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2099 }
2100
Paul Jensen0cc17322014-11-25 15:26:53 -05002101 // Cancel any lingering so the linger timeout doesn't teardown a network.
2102 // This should be called when a network begins satisfying a NetworkRequest.
2103 // Note: depending on what state the NetworkMonitor is in (e.g.,
2104 // if it's awaiting captive portal login, or if validation failed), this
2105 // may trigger a re-evaluation of the network.
2106 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002107 nai.networkLingered.clear();
2108 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002109 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002110 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002111 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2112 }
2113
Robert Greenwalt7b816022014-04-18 15:25:25 -07002114 private void handleAsyncChannelHalfConnect(Message msg) {
2115 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002116 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002117 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2118 if (VDBG) log("NetworkFactory connected");
2119 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002120 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002121 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002122 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002123 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002124 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002125 }
2126 } else {
2127 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002128 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002129 }
2130 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2131 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2132 if (VDBG) log("NetworkAgent connected");
2133 // A network agent has requested a connection. Establish the connection.
2134 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2135 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2136 } else {
2137 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002138 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002139 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002140 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002141 synchronized (mNetworkForNetId) {
2142 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002143 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002144 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002145 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002146 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002147 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002148 }
2149 }
2150 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002151
Robert Greenwalt7b816022014-04-18 15:25:25 -07002152 private void handleAsyncChannelDisconnected(Message msg) {
2153 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2154 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002155 if (DBG) {
2156 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2157 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002158 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002159 // TODO - if we move the logic to the network agent (have them disconnect
2160 // because they lost all their requests or because their score isn't good)
2161 // then they would disconnect organically, report their new state and then
2162 // disconnect the channel.
2163 if (nai.networkInfo.isConnected()) {
2164 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2165 null, null);
2166 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002167 final boolean wasDefault = isDefaultNetwork(nai);
2168 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002169 mDefaultInetConditionPublished = 0;
2170 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002171 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002172 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002173 mKeepaliveTracker.handleStopAllKeepalives(nai,
2174 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002175 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002176 mNetworkAgentInfos.remove(msg.replyTo);
2177 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002178 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002179 // Remove the NetworkAgent, but don't mark the netId as
2180 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002181 mNetworkForNetId.remove(nai.network.netId);
2182 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002183 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002184 for (int i = 0; i < nai.networkRequests.size(); i++) {
2185 NetworkRequest request = nai.networkRequests.valueAt(i);
2186 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2187 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2188 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002189 sendUpdatedScoreToFactories(request, 0);
2190 }
2191 }
2192 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2193 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002194 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002195 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002196 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002197 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002198 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002199 if (nai.created) {
2200 // Tell netd to clean up the configuration for this network
2201 // (routing rules, DNS, etc).
2202 // This may be slow as it requires a lot of netd shelling out to ip and
2203 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2204 // after we've rematched networks with requests which should make a potential
2205 // fallback network the default or requested a new network from the
2206 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2207 // long time.
2208 try {
2209 mNetd.removeNetwork(nai.network.netId);
2210 } catch (Exception e) {
2211 loge("Exception removing network: " + e);
2212 }
2213 }
2214 synchronized (mNetworkForNetId) {
2215 mNetIdInUse.delete(nai.network.netId);
2216 }
2217 } else {
2218 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2219 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002220 }
2221 }
2222
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002223 // If this method proves to be too slow then we can maintain a separate
2224 // pendingIntent => NetworkRequestInfo map.
2225 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2226 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2227 Intent intent = pendingIntent.getIntent();
2228 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2229 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2230 if (existingPendingIntent != null &&
2231 existingPendingIntent.getIntent().filterEquals(intent)) {
2232 return entry.getValue();
2233 }
2234 }
2235 return null;
2236 }
2237
2238 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2239 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2240
2241 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2242 if (existingRequest != null) { // remove the existing request.
2243 if (DBG) log("Replacing " + existingRequest.request + " with "
2244 + nri.request + " because their intents matched.");
2245 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2246 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002247 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002248 }
2249
Erik Klineda4bfa82015-04-30 12:58:40 +09002250 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002251 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002252 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002253 rematchAllNetworksAndRequests(null, 0);
2254 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2255 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002256 }
2257 }
2258
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002259 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2260 int callingUid) {
2261 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2262 if (nri != null) {
2263 handleReleaseNetworkRequest(nri.request, callingUid);
2264 }
2265 }
2266
Paul Jensen99364842014-12-09 11:43:45 -05002267 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002268 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2269 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002270 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002271 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002272 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2273 // If this Network is already the highest scoring Network for a request, or if
2274 // there is hope for it to become one if it validated, then it is needed.
2275 if (nri.isRequest && nai.satisfies(nri.request) &&
2276 (nai.networkRequests.get(nri.request.requestId) != null ||
2277 // Note that this catches two important cases:
2278 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2279 // is currently satisfying the request. This is desirable when
2280 // cellular ends up validating but WiFi does not.
2281 // 2. Unvalidated WiFi will not be reaped when validated cellular
2282 // is currently satsifying the request. This is desirable when
2283 // WiFi ends up validating and out scoring cellular.
2284 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2285 nai.getCurrentScoreAsValidated())) {
2286 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002287 }
2288 }
Paul Jensene0988542015-06-25 15:30:08 -04002289 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002290 }
2291
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002292 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2293 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002294 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002295 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002296 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2297 return;
2298 }
2299 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002300 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002301 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002302 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002303 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002304 // Find all networks that are satisfying this request and remove the request
2305 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002306 // TODO - it's my understanding that for a request there is only a single
2307 // network satisfying it, so this loop is wasteful
2308 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002309 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2310 if (nai.networkRequests.get(nri.request.requestId) != null) {
2311 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002312 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002313 log(" Removing from current network " + nai.name() +
2314 ", leaving " + nai.networkRequests.size() +
2315 " requests.");
2316 }
Paul Jensen99364842014-12-09 11:43:45 -05002317 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002318 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002319 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002320 } else {
2321 // suspect there should only be one pass through here
2322 // but if any were kept do the check below
2323 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002324 }
2325 }
2326 }
2327
Robert Greenwalt51481852015-01-08 14:43:31 -08002328 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2329 if (nai != null) {
2330 mNetworkForRequestId.remove(nri.request.requestId);
2331 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002332 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002333 // that a network connected to serve it, even though the network was already
2334 // connected. Now that this request has gone away, we might have to pretend
2335 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002336 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002337 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2338 boolean doRemove = true;
2339 if (wasKept) {
2340 // check if any of the remaining requests for this network are for the
2341 // same legacy type - if so, don't remove the nai
2342 for (int i = 0; i < nai.networkRequests.size(); i++) {
2343 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2344 if (otherRequest.legacyType == nri.request.legacyType &&
2345 isRequest(otherRequest)) {
2346 if (DBG) log(" still have other legacy request - leaving");
2347 doRemove = false;
2348 }
2349 }
2350 }
2351
2352 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002353 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002354 }
2355 }
2356
Robert Greenwalta67be032014-05-16 15:49:14 -07002357 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002358 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2359 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002360 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002361 } else {
2362 // listens don't have a singular affectedNetwork. Check all networks to see
2363 // if this listen request applies and remove it.
2364 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2365 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002366 }
2367 }
2368 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2369 }
2370 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002371
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002372 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2373 enforceConnectivityInternalPermission();
2374 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2375 accept ? 1 : 0, always ? 1: 0, network));
2376 }
2377
2378 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2379 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2380 " accept=" + accept + " always=" + always);
2381
2382 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2383 if (nai == null) {
2384 // Nothing to do.
2385 return;
2386 }
2387
2388 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002389 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002390 return;
2391 }
2392
2393 if (!nai.networkMisc.explicitlySelected) {
2394 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2395 }
2396
2397 if (accept != nai.networkMisc.acceptUnvalidated) {
2398 int oldScore = nai.getCurrentScore();
2399 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002400 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002401 sendUpdatedScoreToFactories(nai);
2402 }
2403
2404 if (always) {
2405 nai.asyncChannel.sendMessage(
2406 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2407 }
2408
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002409 if (!accept) {
2410 // Tell the NetworkAgent that the network does not have Internet access (because that's
2411 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2412 // the future. We do this now because NetworkMonitor might not yet have finished
2413 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2414 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2415 NetworkAgent.INVALID_NETWORK, 0, null);
2416 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2417 // to reconnect to it immediately. http://b/20739299
2418 }
2419
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002420 }
2421
2422 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002423 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002424 mHandler.sendMessageDelayed(
2425 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2426 PROMPT_UNVALIDATED_DELAY_MS);
2427 }
2428
2429 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002430 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002431 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2432
2433 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2434 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002435 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002436 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002437 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2438 return;
2439 }
2440
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002441 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002442 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002443 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2444 intent.setClassName("com.android.settings",
2445 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002446
2447 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2448 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2449 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002450 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002451 }
2452
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002453 private class InternalHandler extends Handler {
2454 public InternalHandler(Looper looper) {
2455 super(looper);
2456 }
2457
2458 @Override
2459 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002460 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002461 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002462 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002463 String causedBy = null;
2464 synchronized (ConnectivityService.this) {
2465 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2466 mNetTransitionWakeLock.isHeld()) {
2467 mNetTransitionWakeLock.release();
2468 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002469 } else {
2470 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002471 }
2472 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002473 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2474 log("Failed to find a new network - expiring NetTransition Wakelock");
2475 } else {
2476 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2477 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002478 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002479 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002480 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002481 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002482 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002483 break;
2484 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002485 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002486 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002487 sendStickyBroadcast(intent);
2488 break;
2489 }
Jason Monkdecd2952013-10-10 14:02:51 -04002490 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002491 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002492 break;
2493 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002494 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002495 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2496 break;
2497 }
2498 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2499 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002500 break;
2501 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002502 case EVENT_REGISTER_NETWORK_AGENT: {
2503 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2504 break;
2505 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002506 case EVENT_REGISTER_NETWORK_REQUEST:
2507 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002508 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002509 break;
2510 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002511 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2512 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002513 handleRegisterNetworkRequestWithIntent(msg);
2514 break;
2515 }
2516 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2517 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2518 break;
2519 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002520 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002521 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002522 break;
2523 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002524 case EVENT_SET_ACCEPT_UNVALIDATED: {
2525 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2526 break;
2527 }
2528 case EVENT_PROMPT_UNVALIDATED: {
2529 handlePromptUnvalidated((Network) msg.obj);
2530 break;
2531 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002532 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2533 handleMobileDataAlwaysOn();
2534 break;
2535 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002536 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2537 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2538 mKeepaliveTracker.handleStartKeepalive(msg);
2539 break;
2540 }
2541 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2542 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2543 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2544 int slot = msg.arg1;
2545 int reason = msg.arg2;
2546 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2547 break;
2548 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002549 case EVENT_SYSTEM_READY: {
2550 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2551 nai.networkMonitor.systemReady = true;
2552 }
2553 break;
2554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 }
2556 }
2557 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002558
2559 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002560 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002561 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002562 if (isTetheringSupported()) {
2563 return mTethering.tether(iface);
2564 } else {
2565 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2566 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002567 }
2568
2569 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002570 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002571 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002572
2573 if (isTetheringSupported()) {
2574 return mTethering.untether(iface);
2575 } else {
2576 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2577 }
2578 }
2579
2580 // javadoc from interface
2581 public int getLastTetherError(String iface) {
2582 enforceTetherAccessPermission();
2583
2584 if (isTetheringSupported()) {
2585 return mTethering.getLastTetherError(iface);
2586 } else {
2587 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2588 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002589 }
2590
2591 // TODO - proper iface API for selection by property, inspection, etc
2592 public String[] getTetherableUsbRegexs() {
2593 enforceTetherAccessPermission();
2594 if (isTetheringSupported()) {
2595 return mTethering.getTetherableUsbRegexs();
2596 } else {
2597 return new String[0];
2598 }
2599 }
2600
2601 public String[] getTetherableWifiRegexs() {
2602 enforceTetherAccessPermission();
2603 if (isTetheringSupported()) {
2604 return mTethering.getTetherableWifiRegexs();
2605 } else {
2606 return new String[0];
2607 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002608 }
2609
Danica Chang6fdd0c62010-08-11 14:54:43 -07002610 public String[] getTetherableBluetoothRegexs() {
2611 enforceTetherAccessPermission();
2612 if (isTetheringSupported()) {
2613 return mTethering.getTetherableBluetoothRegexs();
2614 } else {
2615 return new String[0];
2616 }
2617 }
2618
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002619 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002620 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002621 if (isTetheringSupported()) {
2622 return mTethering.setUsbTethering(enable);
2623 } else {
2624 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2625 }
2626 }
2627
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002628 // TODO - move iface listing, queries, etc to new module
2629 // javadoc from interface
2630 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002631 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002632 return mTethering.getTetherableIfaces();
2633 }
2634
2635 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002636 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002637 return mTethering.getTetheredIfaces();
2638 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002639
Robert Greenwalt5a735062010-03-02 17:25:02 -08002640 public String[] getTetheringErroredIfaces() {
2641 enforceTetherAccessPermission();
2642 return mTethering.getErroredIfaces();
2643 }
2644
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002645 public String[] getTetheredDhcpRanges() {
2646 enforceConnectivityInternalPermission();
2647 return mTethering.getTetheredDhcpRanges();
2648 }
2649
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002650 // if ro.tether.denied = true we default to no tethering
2651 // gservices could set the secure setting to 1 though to enable it on a build where it
2652 // had previously been turned off.
2653 public boolean isTetheringSupported() {
2654 enforceTetherAccessPermission();
2655 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002656 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002657 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2658 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002659 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2660 mTethering.getTetherableWifiRegexs().length != 0 ||
2661 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2662 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002663 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002664
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002665 // Called when we lose the default network and have no replacement yet.
2666 // This will automatically be cleared after X seconds or a new default network
2667 // becomes CONNECTED, whichever happens first. The timer is started by the
2668 // first caller and not restarted by subsequent callers.
2669 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002670 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002671 synchronized (this) {
2672 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002673 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002674 mNetTransitionWakeLock.acquire();
2675 mNetTransitionWakeLockCausedBy = forWhom;
2676 }
2677 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002678 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002679 mNetTransitionWakeLockTimeout);
2680 return;
2681 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002682
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002683 // 100 percent is full good, 0 is full bad.
2684 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002685 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002686 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002687 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002688 }
2689
Paul Jensenbfd17b72015-04-07 12:43:13 -04002690 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002691 enforceAccessPermission();
2692 enforceInternetPermission();
2693
Paul Jensenbfd17b72015-04-07 12:43:13 -04002694 NetworkAgentInfo nai;
2695 if (network == null) {
2696 nai = getDefaultNetwork();
2697 } else {
2698 nai = getNetworkAgentInfoForNetwork(network);
2699 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002700 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2701 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2702 return;
2703 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002704 // Revalidate if the app report does not match our current validated state.
2705 if (hasConnectivity == nai.lastValidated) return;
2706 final int uid = Binder.getCallingUid();
2707 if (DBG) {
2708 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2709 ") by " + uid);
2710 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002711 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002712 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2713 // which isn't meant to work on uncreated networks.
2714 if (!nai.created) return;
2715
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002716 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002717
2718 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2719 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002720 }
2721
Paul Jensencee9b512015-05-06 07:32:40 -04002722 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002723 // this information is already available as a world read/writable jvm property
2724 // so this API change wouldn't have a benifit. It also breaks the passing
2725 // of proxy info to all the JVMs.
2726 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002727 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002728 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002729 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2730 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002731 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002732 }
2733
Paul Jensencee9b512015-05-06 07:32:40 -04002734 public ProxyInfo getProxyForNetwork(Network network) {
2735 if (network == null) return getDefaultProxy();
2736 final ProxyInfo globalProxy = getGlobalProxy();
2737 if (globalProxy != null) return globalProxy;
2738 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2739 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2740 // caller may not have.
2741 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2742 if (nai == null) return null;
2743 synchronized (nai) {
2744 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2745 if (proxyInfo == null) return null;
2746 return new ProxyInfo(proxyInfo);
2747 }
2748 }
2749
Paul Jensene0bef712014-12-10 15:12:18 -05002750 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2751 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2752 // proxy is null then there is no proxy in place).
2753 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2754 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2755 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2756 proxy = null;
2757 }
2758 return proxy;
2759 }
2760
2761 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2762 // better for determining if a new proxy broadcast is necessary:
2763 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2764 // avoid unnecessary broadcasts.
2765 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2766 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2767 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2768 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2769 // all set.
2770 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2771 a = canonicalizeProxyInfo(a);
2772 b = canonicalizeProxyInfo(b);
2773 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2774 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2775 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2776 }
2777
Jason Monk207900c2014-04-25 15:00:09 -04002778 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002779 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002780
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002781 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002782 if (proxyProperties == mGlobalProxy) return;
2783 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2784 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2785
2786 String host = "";
2787 int port = 0;
2788 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002789 String pacFileUrl = "";
2790 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002791 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002792 if (!proxyProperties.isValid()) {
2793 if (DBG)
2794 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2795 return;
2796 }
Jason Monk207900c2014-04-25 15:00:09 -04002797 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002798 host = mGlobalProxy.getHost();
2799 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002800 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002801 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002802 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002803 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002804 } else {
2805 mGlobalProxy = null;
2806 }
2807 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002808 final long token = Binder.clearCallingIdentity();
2809 try {
2810 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2811 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2812 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2813 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002814 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002815 } finally {
2816 Binder.restoreCallingIdentity(token);
2817 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002818
Jason Monkcf0f97a2014-10-02 15:39:38 -04002819 if (mGlobalProxy == null) {
2820 proxyProperties = mDefaultProxy;
2821 }
2822 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002823 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002824 }
2825
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002826 private void loadGlobalProxy() {
2827 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002828 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2829 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2830 String exclList = Settings.Global.getString(res,
2831 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002832 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2833 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002834 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002835 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002836 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002837 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002838 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002839 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002840 if (!proxyProperties.isValid()) {
2841 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2842 return;
2843 }
2844
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002845 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002846 mGlobalProxy = proxyProperties;
2847 }
2848 }
2849 }
2850
Jason Monk207900c2014-04-25 15:00:09 -04002851 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002852 // this information is already available as a world read/writable jvm property
2853 // so this API change wouldn't have a benifit. It also breaks the passing
2854 // of proxy info to all the JVMs.
2855 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002856 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002857 return mGlobalProxy;
2858 }
2859 }
2860
Jason Monk207900c2014-04-25 15:00:09 -04002861 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002862 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002863 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002864 proxy = null;
2865 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002866 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002867 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002868 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002869 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002870 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2871 return;
2872 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002873
2874 // This call could be coming from the PacManager, containing the port of the local
2875 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2876 // global (to get the correct local port), and send a broadcast.
2877 // TODO: Switch PacManager to have its own message to send back rather than
2878 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002879 if ((mGlobalProxy != null) && (proxy != null)
2880 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002881 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2882 mGlobalProxy = proxy;
2883 sendProxyBroadcast(mGlobalProxy);
2884 return;
2885 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002886 mDefaultProxy = proxy;
2887
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002888 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002889 if (!mDefaultProxyDisabled) {
2890 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002891 }
2892 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002893 }
2894
Paul Jensene0bef712014-12-10 15:12:18 -05002895 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2896 // This method gets called when any network changes proxy, but the broadcast only ever contains
2897 // the default proxy (even if it hasn't changed).
2898 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2899 // world where an app might be bound to a non-default network.
2900 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2901 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2902 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2903
2904 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2905 sendProxyBroadcast(getDefaultProxy());
2906 }
2907 }
2908
Robert Greenwalt434203a2010-10-11 16:00:27 -07002909 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002910 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2911 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002912 if (!TextUtils.isEmpty(proxy)) {
2913 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002914 if (data.length == 0) {
2915 return;
2916 }
2917
Robert Greenwalt434203a2010-10-11 16:00:27 -07002918 String proxyHost = data[0];
2919 int proxyPort = 8080;
2920 if (data.length > 1) {
2921 try {
2922 proxyPort = Integer.parseInt(data[1]);
2923 } catch (NumberFormatException e) {
2924 return;
2925 }
2926 }
Jason Monk207900c2014-04-25 15:00:09 -04002927 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002928 setGlobalProxy(p);
2929 }
2930 }
2931
Jason Monk207900c2014-04-25 15:00:09 -04002932 private void sendProxyBroadcast(ProxyInfo proxy) {
2933 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002934 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002935 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002936 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002937 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2938 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002939 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002940 final long ident = Binder.clearCallingIdentity();
2941 try {
2942 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2943 } finally {
2944 Binder.restoreCallingIdentity(ident);
2945 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002946 }
2947
2948 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002949 final private HashMap<Uri, Integer> mUriEventMap;
2950 final private Context mContext;
2951 final private Handler mHandler;
2952
2953 SettingsObserver(Context context, Handler handler) {
2954 super(null);
2955 mUriEventMap = new HashMap<Uri, Integer>();
2956 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002957 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002958 }
2959
Erik Klineda4bfa82015-04-30 12:58:40 +09002960 void observe(Uri uri, int what) {
2961 mUriEventMap.put(uri, what);
2962 final ContentResolver resolver = mContext.getContentResolver();
2963 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002964 }
2965
2966 @Override
2967 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002968 Slog.wtf(TAG, "Should never be reached.");
2969 }
2970
2971 @Override
2972 public void onChange(boolean selfChange, Uri uri) {
2973 final Integer what = mUriEventMap.get(uri);
2974 if (what != null) {
2975 mHandler.obtainMessage(what.intValue()).sendToTarget();
2976 } else {
2977 loge("No matching event to send for URI=" + uri);
2978 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002979 }
2980 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002981
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002982 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002983 Slog.d(TAG, s);
2984 }
2985
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002986 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002987 Slog.e(TAG, s);
2988 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002989
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002990 private static <T> T checkNotNull(T value, String message) {
2991 if (value == null) {
2992 throw new NullPointerException(message);
2993 }
2994 return value;
2995 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002996
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002997 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002998 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002999 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3000 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3001 *
3002 * @param oldPackage Package name of the application which currently controls VPN, which will
3003 * be replaced. If there is no such application, this should should either be
3004 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3005 * @param newPackage Package name of the application which should gain control of VPN, or
3006 * {@code null} to disable.
3007 * @param userId User for whom to prepare the new VPN.
3008 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003009 * @hide
3010 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003011 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003012 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3013 int userId) {
3014 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003015 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003016
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003017 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003018 Vpn vpn = mVpns.get(userId);
3019 if (vpn != null) {
3020 return vpn.prepare(oldPackage, newPackage);
3021 } else {
3022 return false;
3023 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003024 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003025 }
3026
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003027 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003028 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3029 * This method is used by system-privileged apps.
3030 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3031 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3032 *
3033 * @param packageName The package for which authorization state should change.
3034 * @param userId User for whom {@code packageName} is installed.
3035 * @param authorized {@code true} if this app should be able to start a VPN connection without
3036 * explicit user approval, {@code false} if not.
3037 *
Jeff Davidson05542602014-08-11 14:07:27 -07003038 * @hide
3039 */
3040 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003041 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3042 enforceCrossUserPermission(userId);
3043
Jeff Davidson05542602014-08-11 14:07:27 -07003044 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003045 Vpn vpn = mVpns.get(userId);
3046 if (vpn != null) {
3047 vpn.setPackageAuthorization(packageName, authorized);
3048 }
Jeff Davidson05542602014-08-11 14:07:27 -07003049 }
3050 }
3051
3052 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003053 * Configure a TUN interface and return its file descriptor. Parameters
3054 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003055 * and not available in ConnectivityManager. Permissions are checked in
3056 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003057 * @hide
3058 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003059 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003060 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003061 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003062 int user = UserHandle.getUserId(Binder.getCallingUid());
3063 synchronized(mVpns) {
3064 return mVpns.get(user).establish(config);
3065 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003066 }
3067
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003068 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003069 * Start legacy VPN, controlling native daemons as needed. Creates a
3070 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003071 */
3072 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003073 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003074 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003075 final LinkProperties egress = getActiveLinkProperties();
3076 if (egress == null) {
3077 throw new IllegalStateException("Missing active network connection");
3078 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003079 int user = UserHandle.getUserId(Binder.getCallingUid());
3080 synchronized(mVpns) {
3081 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3082 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003083 }
3084
3085 /**
3086 * Return the information of the ongoing legacy VPN. This method is used
3087 * by VpnSettings and not available in ConnectivityManager. Permissions
3088 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003089 */
3090 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003091 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3092 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003093 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003094 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003095 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003096 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003097 }
3098
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003099 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003100 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3101 * and not available in ConnectivityManager.
3102 */
3103 @Override
3104 public VpnInfo[] getAllVpnInfo() {
3105 enforceConnectivityInternalPermission();
3106 if (mLockdownEnabled) {
3107 return new VpnInfo[0];
3108 }
3109
3110 synchronized(mVpns) {
3111 List<VpnInfo> infoList = new ArrayList<>();
3112 for (int i = 0; i < mVpns.size(); i++) {
3113 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3114 if (info != null) {
3115 infoList.add(info);
3116 }
3117 }
3118 return infoList.toArray(new VpnInfo[infoList.size()]);
3119 }
3120 }
3121
3122 /**
3123 * @return VPN information for accounting, or null if we can't retrieve all required
3124 * information, e.g primary underlying iface.
3125 */
3126 @Nullable
3127 private VpnInfo createVpnInfo(Vpn vpn) {
3128 VpnInfo info = vpn.getVpnInfo();
3129 if (info == null) {
3130 return null;
3131 }
3132 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3133 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3134 // the underlyingNetworks list.
3135 if (underlyingNetworks == null) {
3136 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3137 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3138 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3139 }
3140 } else if (underlyingNetworks.length > 0) {
3141 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3142 if (linkProperties != null) {
3143 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3144 }
3145 }
3146 return info.primaryUnderlyingIface == null ? null : info;
3147 }
3148
3149 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003150 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3151 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003152 * Permissions are checked in Vpn class.
3153 * @hide
3154 */
3155 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003156 public VpnConfig getVpnConfig(int userId) {
3157 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003158 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003159 Vpn vpn = mVpns.get(userId);
3160 if (vpn != null) {
3161 return vpn.getVpnConfig();
3162 } else {
3163 return null;
3164 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003165 }
3166 }
3167
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003168 @Override
3169 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003170 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3171 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3172 return false;
3173 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003174
3175 // Tear down existing lockdown if profile was removed
3176 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3177 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003178 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003179 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3180 return false;
3181 }
3182
3183 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3184 final VpnProfile profile = VpnProfile.decode(
3185 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003186 int user = UserHandle.getUserId(Binder.getCallingUid());
3187 synchronized(mVpns) {
3188 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3189 profile));
3190 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003191 } else {
3192 setLockdownTracker(null);
3193 }
3194
3195 return true;
3196 }
3197
3198 /**
3199 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3200 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3201 */
3202 private void setLockdownTracker(LockdownVpnTracker tracker) {
3203 // Shutdown any existing tracker
3204 final LockdownVpnTracker existing = mLockdownTracker;
3205 mLockdownTracker = null;
3206 if (existing != null) {
3207 existing.shutdown();
3208 }
3209
3210 try {
3211 if (tracker != null) {
3212 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003213 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003214 mLockdownTracker = tracker;
3215 mLockdownTracker.init();
3216 } else {
3217 mNetd.setFirewallEnabled(false);
3218 }
3219 } catch (RemoteException e) {
3220 // ignored; NMS lives inside system_server
3221 }
3222 }
3223
3224 private void throwIfLockdownEnabled() {
3225 if (mLockdownEnabled) {
3226 throw new IllegalStateException("Unavailable in lockdown mode");
3227 }
3228 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003229
Wink Savilleab9321d2013-06-29 21:10:57 -07003230 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003231 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003232 // TODO: Remove? Any reason to trigger a provisioning check?
3233 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003234 }
3235
3236 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003237 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003238
Paul Jensen89e0f092014-09-15 15:59:36 -04003239 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003240 if (DBG) {
3241 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003242 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003243 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003244 Intent intent = new Intent(action);
3245 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003246 // Concatenate the range of types onto the range of NetIDs.
3247 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003248 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003249 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003250 }
3251
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003252 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003253 * Show or hide network provisioning notifications.
3254 *
3255 * We use notifications for two purposes: to notify that a network requires sign in
3256 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3257 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3258 * particular network we can display the notification type that was most recently requested.
3259 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3260 * might first display NO_INTERNET, and then when the captive portal check completes, display
3261 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003262 *
3263 * @param id an identifier that uniquely identifies this notification. This must match
3264 * between show and hide calls. We use the NetID value but for legacy callers
3265 * we concatenate the range of types with the range of NetIDs.
3266 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003267 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003268 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3269 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003270 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003271 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3272 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003273 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003274 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003275
3276 Resources r = Resources.getSystem();
3277 NotificationManager notificationManager = (NotificationManager) mContext
3278 .getSystemService(Context.NOTIFICATION_SERVICE);
3279
3280 if (visible) {
3281 CharSequence title;
3282 CharSequence details;
3283 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003284 if (notifyType == NotificationType.NO_INTERNET &&
3285 networkType == ConnectivityManager.TYPE_WIFI) {
3286 title = r.getString(R.string.wifi_no_internet, 0);
3287 details = r.getString(R.string.wifi_no_internet_detailed);
3288 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3289 } else if (notifyType == NotificationType.SIGN_IN) {
3290 switch (networkType) {
3291 case ConnectivityManager.TYPE_WIFI:
3292 title = r.getString(R.string.wifi_available_sign_in, 0);
3293 details = r.getString(R.string.network_available_sign_in_detailed,
3294 extraInfo);
3295 icon = R.drawable.stat_notify_wifi_in_range;
3296 break;
3297 case ConnectivityManager.TYPE_MOBILE:
3298 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3299 title = r.getString(R.string.network_available_sign_in, 0);
3300 // TODO: Change this to pull from NetworkInfo once a printable
3301 // name has been added to it
3302 details = mTelephonyManager.getNetworkOperatorName();
3303 icon = R.drawable.stat_notify_rssi_in_range;
3304 break;
3305 default:
3306 title = r.getString(R.string.network_available_sign_in, 0);
3307 details = r.getString(R.string.network_available_sign_in_detailed,
3308 extraInfo);
3309 icon = R.drawable.stat_notify_rssi_in_range;
3310 break;
3311 }
3312 } else {
3313 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3314 + getNetworkTypeName(networkType));
3315 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003316 }
3317
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003318 Notification notification = new Notification.Builder(mContext)
3319 .setWhen(0)
3320 .setSmallIcon(icon)
3321 .setAutoCancel(true)
3322 .setTicker(title)
3323 .setColor(mContext.getColor(
3324 com.android.internal.R.color.system_notification_accent_color))
3325 .setContentTitle(title)
3326 .setContentText(details)
3327 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003328 .setLocalOnly(true)
3329 .setPriority(highPriority ?
3330 Notification.PRIORITY_HIGH :
3331 Notification.PRIORITY_DEFAULT)
3332 .setDefaults(Notification.DEFAULT_ALL)
3333 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003334 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003335
Wink Saville948282b2013-08-29 08:55:16 -07003336 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003337 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003338 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003339 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003340 npe.printStackTrace();
3341 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003342 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003343 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003344 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003345 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003346 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003347 npe.printStackTrace();
3348 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003349 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003350 }
3351
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003352 /** Location to an updatable file listing carrier provisioning urls.
3353 * An example:
3354 *
3355 * <?xml version="1.0" encoding="utf-8"?>
3356 * <provisioningUrls>
3357 * <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 -07003358 * </provisioningUrls>
3359 */
3360 private static final String PROVISIONING_URL_PATH =
3361 "/data/misc/radio/provisioning_urls.xml";
3362 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003363
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003364 /** XML tag for root element. */
3365 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3366 /** XML tag for individual url */
3367 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003368 /** XML attribute for mcc */
3369 private static final String ATTR_MCC = "mcc";
3370 /** XML attribute for mnc */
3371 private static final String ATTR_MNC = "mnc";
3372
Paul Jensen434dde82015-06-11 09:43:30 -04003373 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003374 FileReader fileReader = null;
3375 XmlPullParser parser = null;
3376 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003377
3378 try {
3379 fileReader = new FileReader(mProvisioningUrlFile);
3380 parser = Xml.newPullParser();
3381 parser.setInput(fileReader);
3382 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3383
3384 while (true) {
3385 XmlUtils.nextElement(parser);
3386
3387 String element = parser.getName();
3388 if (element == null) break;
3389
Paul Jensen434dde82015-06-11 09:43:30 -04003390 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003391 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3392 try {
3393 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3394 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3395 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3396 parser.next();
3397 if (parser.getEventType() == XmlPullParser.TEXT) {
3398 return parser.getText();
3399 }
3400 }
3401 }
3402 } catch (NumberFormatException e) {
3403 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3404 }
3405 }
3406 }
3407 return null;
3408 } catch (FileNotFoundException e) {
3409 loge("Carrier Provisioning Urls file not found");
3410 } catch (XmlPullParserException e) {
3411 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3412 } catch (IOException e) {
3413 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3414 } finally {
3415 if (fileReader != null) {
3416 try {
3417 fileReader.close();
3418 } catch (IOException e) {}
3419 }
3420 }
3421 return null;
3422 }
3423
Wink Saville42d4f082013-07-20 20:31:59 -07003424 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003425 public String getMobileProvisioningUrl() {
3426 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003427 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003428 if (TextUtils.isEmpty(url)) {
3429 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003430 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003431 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003432 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003433 }
Wink Saville8cf35602013-07-10 23:00:07 -07003434 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003435 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003436 String phoneNumber = mTelephonyManager.getLine1Number();
3437 if (TextUtils.isEmpty(phoneNumber)) {
3438 phoneNumber = "0000000000";
3439 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003440 url = String.format(url,
3441 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3442 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003443 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003444 }
3445
Wink Savilleab9321d2013-06-29 21:10:57 -07003446 return url;
3447 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003448
Wink Saville948282b2013-08-29 08:55:16 -07003449 @Override
3450 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003451 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003452 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003453 final long ident = Binder.clearCallingIdentity();
3454 try {
3455 setProvNotificationVisible(visible, networkType, action);
3456 } finally {
3457 Binder.restoreCallingIdentity(ident);
3458 }
Wink Saville948282b2013-08-29 08:55:16 -07003459 }
Wink Saville7788c612013-08-29 14:57:08 -07003460
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003461 @Override
3462 public void setAirplaneMode(boolean enable) {
3463 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003464 final long ident = Binder.clearCallingIdentity();
3465 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003466 final ContentResolver cr = mContext.getContentResolver();
3467 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3468 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3469 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003470 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003471 } finally {
3472 Binder.restoreCallingIdentity(ident);
3473 }
3474 }
3475
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003476 private void onUserStart(int userId) {
3477 synchronized(mVpns) {
3478 Vpn userVpn = mVpns.get(userId);
3479 if (userVpn != null) {
3480 loge("Starting user already has a VPN");
3481 return;
3482 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003483 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003484 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003485 }
3486 }
3487
3488 private void onUserStop(int userId) {
3489 synchronized(mVpns) {
3490 Vpn userVpn = mVpns.get(userId);
3491 if (userVpn == null) {
3492 loge("Stopping user has no VPN");
3493 return;
3494 }
3495 mVpns.delete(userId);
3496 }
3497 }
3498
3499 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3500 @Override
3501 public void onReceive(Context context, Intent intent) {
3502 final String action = intent.getAction();
3503 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3504 if (userId == UserHandle.USER_NULL) return;
3505
3506 if (Intent.ACTION_USER_STARTING.equals(action)) {
3507 onUserStart(userId);
3508 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3509 onUserStop(userId);
3510 }
3511 }
3512 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003513
Robert Greenwalta67be032014-05-16 15:49:14 -07003514 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3515 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003516 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3517 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003518
Robert Greenwalta67be032014-05-16 15:49:14 -07003519 private static class NetworkFactoryInfo {
3520 public final String name;
3521 public final Messenger messenger;
3522 public final AsyncChannel asyncChannel;
3523
3524 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3525 this.name = name;
3526 this.messenger = messenger;
3527 this.asyncChannel = asyncChannel;
3528 }
3529 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003530
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003531 /**
3532 * Tracks info about the requester.
3533 * Also used to notice when the calling process dies so we can self-expire
3534 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003535 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3536 static final boolean REQUEST = true;
3537 static final boolean LISTEN = false;
3538
3539 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003540 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003541 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003542 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003543 final int mPid;
3544 final int mUid;
3545 final Messenger messenger;
3546 final boolean isRequest;
3547
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003548 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3549 request = r;
3550 mPendingIntent = pi;
3551 messenger = null;
3552 mBinder = null;
3553 mPid = getCallingPid();
3554 mUid = getCallingUid();
3555 this.isRequest = isRequest;
3556 }
3557
Robert Greenwalt9258c642014-03-26 16:47:06 -07003558 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3559 super();
3560 messenger = m;
3561 request = r;
3562 mBinder = binder;
3563 mPid = getCallingPid();
3564 mUid = getCallingUid();
3565 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003566 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003567
3568 try {
3569 mBinder.linkToDeath(this, 0);
3570 } catch (RemoteException e) {
3571 binderDied();
3572 }
3573 }
3574
3575 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003576 if (mBinder != null) {
3577 mBinder.unlinkToDeath(this, 0);
3578 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003579 }
3580
3581 public void binderDied() {
3582 log("ConnectivityService NetworkRequestInfo binderDied(" +
3583 request + ", " + mBinder + ")");
3584 releaseNetworkRequest(request);
3585 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003586
3587 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003588 return (isRequest ? "Request" : "Listen") +
3589 " from uid/pid:" + mUid + "/" + mPid +
3590 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003591 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003592 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003593 }
3594
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003595 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3596 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3597 if (badCapability != null) {
3598 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003599 }
3600 }
3601
Robert Greenwalt9258c642014-03-26 16:47:06 -07003602 @Override
3603 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003604 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003605 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003606 enforceNetworkRequestPermissions(networkCapabilities);
3607 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003608 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003609
Robert Greenwalt6078b502014-06-11 16:05:07 -07003610 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003611 throw new IllegalArgumentException("Bad timeout specified");
3612 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003613
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003614 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3615 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003616 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3617 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003618 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003619
3620 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003621 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003622 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003623 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003624 }
3625 return networkRequest;
3626 }
3627
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003628 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003629 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003630 enforceConnectivityInternalPermission();
3631 } else {
3632 enforceChangePermission();
3633 }
3634 }
3635
fenglub15e72b2015-03-20 11:29:56 -07003636 @Override
fengludb571472015-04-21 17:12:05 -07003637 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003638 enforceAccessPermission();
3639 NetworkAgentInfo nai = null;
3640 if (network == null) {
3641 return false;
3642 }
3643 synchronized (mNetworkForNetId) {
3644 nai = mNetworkForNetId.get(network.netId);
3645 }
3646 if (nai != null) {
3647 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3648 return true;
3649 }
3650 return false;
3651 }
3652
3653
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003654 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3655 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003656 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003657 final int uidRules;
3658 final int uid = Binder.getCallingUid();
3659 synchronized(mRulesLock) {
3660 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3661 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003662 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003663 // we could silently fail or we can filter the available nets to only give
3664 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003665 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003666 }
3667 }
3668 }
3669
Robert Greenwalt9258c642014-03-26 16:47:06 -07003670 @Override
3671 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3672 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003673 checkNotNull(operation, "PendingIntent cannot be null.");
3674 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3675 enforceNetworkRequestPermissions(networkCapabilities);
3676 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003677 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003678
3679 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3680 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003681 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3682 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003683 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003684 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3685 nri));
3686 return networkRequest;
3687 }
3688
Jeremy Joslin79294842014-12-03 17:15:28 -08003689 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3690 mHandler.sendMessageDelayed(
3691 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3692 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3693 }
3694
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003695 @Override
3696 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003697 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003698 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3699 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003700 }
3701
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003702 // In order to implement the compatibility measure for pre-M apps that call
3703 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3704 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3705 // This ensures it has permission to do so.
3706 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3707 if (nc == null) {
3708 return false;
3709 }
3710 int[] transportTypes = nc.getTransportTypes();
3711 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3712 return false;
3713 }
3714 try {
3715 mContext.enforceCallingOrSelfPermission(
3716 android.Manifest.permission.ACCESS_WIFI_STATE,
3717 "ConnectivityService");
3718 } catch (SecurityException e) {
3719 return false;
3720 }
3721 return true;
3722 }
3723
Robert Greenwalt9258c642014-03-26 16:47:06 -07003724 @Override
3725 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3726 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003727 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3728 enforceAccessPermission();
3729 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003730
Erik Kline7523eb32015-07-09 18:24:03 +09003731 NetworkRequest networkRequest = new NetworkRequest(
3732 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003733 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3734 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003735 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003736
3737 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3738 return networkRequest;
3739 }
3740
3741 @Override
3742 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3743 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003744 checkNotNull(operation, "PendingIntent cannot be null.");
3745 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3746 enforceAccessPermission();
3747 }
3748
Erik Kline7523eb32015-07-09 18:24:03 +09003749 NetworkRequest networkRequest = new NetworkRequest(
3750 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003751 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3752 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003753 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003754
3755 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003756 }
3757
3758 @Override
3759 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003760 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3761 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003762 }
3763
3764 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003765 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003766 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003767 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3768 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003769 }
3770
Robert Greenwalta67be032014-05-16 15:49:14 -07003771 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003772 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003773 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3774 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3775 }
3776
3777 @Override
3778 public void unregisterNetworkFactory(Messenger messenger) {
3779 enforceConnectivityInternalPermission();
3780 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3781 }
3782
3783 private void handleUnregisterNetworkFactory(Messenger messenger) {
3784 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3785 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003786 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003787 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003788 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003789 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003790 }
3791
Robert Greenwalt7b816022014-04-18 15:25:25 -07003792 /**
3793 * NetworkAgentInfo supporting a request by requestId.
3794 * These have already been vetted (their Capabilities satisfy the request)
3795 * and the are the highest scored network available.
3796 * the are keyed off the Requests requestId.
3797 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003798 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003799 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3800 new SparseArray<NetworkAgentInfo>();
3801
Paul Jensen31a94f42015-02-13 14:18:39 -05003802 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3803 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003804 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3805 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003806 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3807 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3808 // there may not be a strict 1:1 correlation between the two.
3809 @GuardedBy("mNetworkForNetId")
3810 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003811
Robert Greenwalt7b816022014-04-18 15:25:25 -07003812 // NetworkAgentInfo keyed off its connecting messenger
3813 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003814 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003815 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3816 new HashMap<Messenger, NetworkAgentInfo>();
3817
Paul Jensen2c311d62014-11-17 12:34:51 -05003818 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003819 private final NetworkRequest mDefaultRequest;
3820
Erik Klineda4bfa82015-04-30 12:58:40 +09003821 // Request used to optionally keep mobile data active even when higher
3822 // priority networks like Wi-Fi are active.
3823 private final NetworkRequest mDefaultMobileDataRequest;
3824
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003825 private NetworkAgentInfo getDefaultNetwork() {
3826 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3827 }
3828
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003829 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003830 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003831 }
3832
Paul Jensen31a94f42015-02-13 14:18:39 -05003833 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003834 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003835 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003836 enforceConnectivityInternalPermission();
3837
Paul Jensen2c311d62014-11-17 12:34:51 -05003838 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3839 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003840 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003841 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3842 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3843 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003844 synchronized (this) {
3845 nai.networkMonitor.systemReady = mSystemReady;
3846 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003847 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003848 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003849 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003850 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003851 }
3852
3853 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3854 if (VDBG) log("Got NetworkAgent Messenger");
3855 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003856 synchronized (mNetworkForNetId) {
3857 mNetworkForNetId.put(na.network.netId, na);
3858 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003859 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3860 NetworkInfo networkInfo = na.networkInfo;
3861 na.networkInfo = null;
3862 updateNetworkInfo(na, networkInfo);
3863 }
3864
3865 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3866 LinkProperties newLp = networkAgent.linkProperties;
3867 int netId = networkAgent.network.netId;
3868
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003869 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3870 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003871 if (networkAgent.clatd != null) {
3872 networkAgent.clatd.fixupLinkProperties(oldLp);
3873 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003874
Paul Jensen992f2522014-04-28 10:33:11 -04003875 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003876 updateMtu(newLp, oldLp);
3877 // TODO - figure out what to do for clat
3878// for (LinkProperties lp : newLp.getStackedLinks()) {
3879// updateMtu(lp, null);
3880// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003881 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003882
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003883 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3884 // In L, we used it only when the network had Internet access but provided no DNS servers.
3885 // For now, just disable it, and if disabling it doesn't break things, remove it.
3886 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3887 // NET_CAPABILITY_INTERNET);
3888 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003889 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003890 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3891
Paul Jensen3b759822014-05-13 11:44:01 -04003892 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003893 if (isDefaultNetwork(networkAgent)) {
3894 handleApplyDefaultProxy(newLp.getHttpProxy());
3895 } else {
3896 updateProxy(newLp, oldLp, networkAgent);
3897 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003898 // TODO - move this check to cover the whole function
3899 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003900 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003901 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3902 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003903
3904 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04003905 }
3906
Lorenzo Colitti95439462014-10-09 13:44:48 +09003907 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3908 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3909 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003910
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003911 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003912 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3913 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003914 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003915 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003916 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003917 }
Paul Jensen992f2522014-04-28 10:33:11 -04003918
3919 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3920 CompareResult<String> interfaceDiff = new CompareResult<String>();
3921 if (oldLp != null) {
3922 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3923 } else if (newLp != null) {
3924 interfaceDiff.added = newLp.getAllInterfaceNames();
3925 }
3926 for (String iface : interfaceDiff.added) {
3927 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003928 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003929 mNetd.addInterfaceToNetwork(iface, netId);
3930 } catch (Exception e) {
3931 loge("Exception adding interface: " + e);
3932 }
3933 }
3934 for (String iface : interfaceDiff.removed) {
3935 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003936 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003937 mNetd.removeInterfaceFromNetwork(iface, netId);
3938 } catch (Exception e) {
3939 loge("Exception removing interface: " + e);
3940 }
3941 }
3942 }
3943
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003944 /**
3945 * Have netd update routes from oldLp to newLp.
3946 * @return true if routes changed between oldLp and newLp
3947 */
3948 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003949 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3950 if (oldLp != null) {
3951 routeDiff = oldLp.compareAllRoutes(newLp);
3952 } else if (newLp != null) {
3953 routeDiff.added = newLp.getAllRoutes();
3954 }
3955
3956 // add routes before removing old in case it helps with continuous connectivity
3957
3958 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3959 for (RouteInfo route : routeDiff.added) {
3960 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003961 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003962 try {
3963 mNetd.addRoute(netId, route);
3964 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003965 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3966 loge("Exception in addRoute for non-gateway: " + e);
3967 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003968 }
3969 }
3970 for (RouteInfo route : routeDiff.added) {
3971 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003972 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003973 try {
3974 mNetd.addRoute(netId, route);
3975 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003976 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3977 loge("Exception in addRoute for gateway: " + e);
3978 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003979 }
3980 }
3981
3982 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003983 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003984 try {
3985 mNetd.removeRoute(netId, route);
3986 } catch (Exception e) {
3987 loge("Exception in removeRoute: " + e);
3988 }
3989 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003990 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003991 }
Erik Kline41368502015-06-17 13:19:54 +09003992
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003993 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3994 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003995 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09003996 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003997 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003998 dnses = new ArrayList();
3999 dnses.add(mDefaultDns);
4000 if (DBG) {
4001 loge("no dns provided for netId " + netId + ", so using defaults");
4002 }
4003 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004004 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004005 try {
4006 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4007 newLp.getDomains());
4008 } catch (Exception e) {
4009 loge("Exception in setDnsServersForNetwork: " + e);
4010 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04004011 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004012 if (defaultNai != null && defaultNai.network.netId == netId) {
4013 setDefaultDnsSystemProperties(dnses);
4014 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004015 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004016 } else if (flush) {
4017 try {
4018 mNetd.flushNetworkDnsCache(netId);
4019 } catch (Exception e) {
4020 loge("Exception in flushNetworkDnsCache: " + e);
4021 }
4022 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004023 }
4024 }
4025
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004026 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4027 int last = 0;
4028 for (InetAddress dns : dnses) {
4029 ++last;
4030 String key = "net.dns" + last;
4031 String value = dns.getHostAddress();
4032 SystemProperties.set(key, value);
4033 }
4034 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4035 String key = "net.dns" + i;
4036 SystemProperties.set(key, "");
4037 }
4038 mNumDnsEntries = last;
4039 }
4040
Paul Jensen3d194ea2015-06-16 14:27:36 -04004041 /**
4042 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4043 * augmented with any stateful capabilities implied from {@code networkAgent}
4044 * (e.g., validated status and captive portal status).
4045 *
Paul Jensene0988542015-06-25 15:30:08 -04004046 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004047 * @param networkCapabilities the new network capabilities.
4048 */
Paul Jensene0988542015-06-25 15:30:08 -04004049 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004050 // Don't modify caller's NetworkCapabilities.
4051 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004052 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004053 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4054 } else {
4055 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4056 }
Paul Jensene0988542015-06-25 15:30:08 -04004057 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004058 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4059 } else {
4060 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4061 }
Paul Jensene0988542015-06-25 15:30:08 -04004062 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4063 final int oldScore = nai.getCurrentScore();
4064 synchronized (nai) {
4065 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004066 }
Paul Jensene0988542015-06-25 15:30:08 -04004067 rematchAllNetworksAndRequests(nai, oldScore);
4068 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004069 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004070 }
4071
Paul Jensenc8b9a742014-09-30 15:37:41 -04004072 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4073 for (int i = 0; i < nai.networkRequests.size(); i++) {
4074 NetworkRequest nr = nai.networkRequests.valueAt(i);
4075 // Don't send listening requests to factories. b/17393458
4076 if (!isRequest(nr)) continue;
4077 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4078 }
4079 }
4080
Robert Greenwalt7b816022014-04-18 15:25:25 -07004081 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4082 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004083 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004084 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4085 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004086 }
4087 }
4088
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004089 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4090 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004091 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004092 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004093 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4094 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004095 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004096 sendIntent(nri.mPendingIntent, intent);
4097 }
4098 // else not handled
4099 }
4100
4101 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4102 mPendingIntentWakeLock.acquire();
4103 try {
4104 if (DBG) log("Sending " + pendingIntent);
4105 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4106 } catch (PendingIntent.CanceledException e) {
4107 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4108 mPendingIntentWakeLock.release();
4109 releasePendingNetworkRequest(pendingIntent);
4110 }
4111 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4112 }
4113
4114 @Override
4115 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4116 String resultData, Bundle resultExtras) {
4117 if (DBG) log("Finished sending " + pendingIntent);
4118 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004119 // Release with a delay so the receiving client has an opportunity to put in its
4120 // own request.
4121 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004122 }
4123
Robert Greenwalt9258c642014-03-26 16:47:06 -07004124 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004125 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004126 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004127 Bundle bundle = new Bundle();
4128 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4129 new NetworkRequest(nri.request));
4130 Message msg = Message.obtain();
4131 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4132 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4133 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4134 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004135 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004136 case ConnectivityManager.CALLBACK_LOSING: {
4137 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4138 break;
4139 }
4140 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4141 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4142 new NetworkCapabilities(networkAgent.networkCapabilities));
4143 break;
4144 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004145 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004146 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4147 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004148 break;
4149 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004150 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004151 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004152 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004153 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004154 if (VDBG) {
4155 log("sending notification " + notifyTypeToName(notificationType) +
4156 " for " + nri.request);
4157 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004158 nri.messenger.send(msg);
4159 } catch (RemoteException e) {
4160 // may occur naturally in the race of binder death.
4161 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4162 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004163 }
4164
Paul Jensenc8b9a742014-09-30 15:37:41 -04004165 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4166 for (int i = 0; i < nai.networkRequests.size(); i++) {
4167 NetworkRequest nr = nai.networkRequests.valueAt(i);
4168 // Ignore listening requests.
4169 if (!isRequest(nr)) continue;
4170 loge("Dead network still had at least " + nr);
4171 break;
4172 }
4173 nai.asyncChannel.disconnect();
4174 }
4175
Robert Greenwalt7b816022014-04-18 15:25:25 -07004176 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4177 if (oldNetwork == null) {
4178 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4179 return;
4180 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004181 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4182 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004183 }
4184
Paul Jensen27b02b72014-07-14 12:03:33 -04004185 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004186 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004187 setupDataActivityTracking(newNetwork);
4188 try {
4189 mNetd.setDefaultNetId(newNetwork.network.netId);
4190 } catch (Exception e) {
4191 loge("Exception setting default network :" + e);
4192 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004193 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004194 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004195 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004196 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004197 }
4198
Paul Jensen2161a8e2014-09-11 11:00:39 -04004199 // Handles a network appearing or improving its score.
4200 //
4201 // - Evaluates all current NetworkRequests that can be
4202 // satisfied by newNetwork, and reassigns to newNetwork
4203 // any such requests for which newNetwork is the best.
4204 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004205 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004206 // needed. A network is needed if it is the best network for
4207 // one or more NetworkRequests, or if it is a VPN.
4208 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004209 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004210 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004211 //
4212 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4213 // networks that have no chance (i.e. even if validated)
4214 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004215 //
4216 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4217 // it does not remove NetworkRequests that other Networks could better satisfy.
4218 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4219 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4220 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004221 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004222 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004223 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4224 // performed to tear down unvalidated networks that have no chance (i.e. even if
4225 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004226 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004227 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004228 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004229 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004230 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004231 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004232 if (DBG) log("rematching " + newNetwork.name());
4233 // Find and migrate to this Network any NetworkRequests for
4234 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004235 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004236 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004237 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004238 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004239 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4240 if (newNetwork == currentNetwork) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004241 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004242 log("Network " + newNetwork.name() + " was already satisfying" +
4243 " request " + nri.request.requestId + ". No change.");
4244 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004245 keep = true;
4246 continue;
4247 }
4248
4249 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004250 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004251 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004252 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004253 // This is not a request, it's a callback listener.
4254 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004255 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004256 continue;
4257 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004258
Robert Greenwalt7b816022014-04-18 15:25:25 -07004259 // next check if it's better than any current network we're using for
4260 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004261 if (VDBG) {
4262 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004263 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4264 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004265 }
4266 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004267 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004268 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004269 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004270 currentNetwork.networkRequests.remove(nri.request.requestId);
4271 currentNetwork.networkLingered.add(nri.request);
4272 affectedNetworks.add(currentNetwork);
4273 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004274 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004275 }
Paul Jensen573a0352015-01-08 10:49:34 -05004276 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004277 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004278 if (!newNetwork.addRequest(nri.request)) {
4279 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4280 }
4281 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004282 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004283 // Tell NetworkFactories about the new score, so they can stop
4284 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004285 // TODO - this could get expensive if we have alot of requests for this
4286 // network. Think about if there is a way to reduce this. Push
4287 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004288 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004289 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004290 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004291 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004292 }
4293 }
4294 }
4295 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004296 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004297 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004298 if (nai.lingering) {
4299 // Already lingered. Nothing to do. This can only happen if "nai" is in
4300 // "affectedNetworks" twice. The reasoning being that to get added to
4301 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4302 // (i.e. not lingered) so it could have only been lingered by this loop.
4303 // unneeded(nai) will be false and we'll call unlinger() below which would
4304 // be bad, so handle it here.
4305 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004306 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004307 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004308 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004309 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004310 }
4311 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004312 if (keep) {
4313 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004314 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004315 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004316 synchronized (ConnectivityService.this) {
4317 // have a new default network, release the transition wakelock in
4318 // a second if it's held. The second pause is to allow apps
4319 // to reconnect over the new network
4320 if (mNetTransitionWakeLock.isHeld()) {
4321 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4322 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4323 mNetTransitionWakeLockSerialNumber, 0),
4324 1000);
4325 }
4326 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004327 }
4328
4329 // do this after the default net is switched, but
4330 // before LegacyTypeTracker sends legacy broadcasts
Paul Jensen3d911462015-06-12 06:40:24 -04004331 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
Robert Greenwalt152ed372014-12-17 17:19:53 -08004332
4333 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004334 // Maintain the illusion: since the legacy API only
4335 // understands one network at a time, we must pretend
4336 // that the current default network disconnected before
4337 // the new one connected.
4338 if (oldDefaultNetwork != null) {
4339 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004340 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004341 }
Paul Jensene0988542015-06-25 15:30:08 -04004342 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004343 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4344 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004345 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004346
4347 // Notify battery stats service about this network, both the normal
4348 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004349 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004350 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004351 final IBatteryStats bs = BatteryStatsService.getService();
4352 final int type = newNetwork.networkInfo.getType();
4353
4354 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4355 bs.noteNetworkInterfaceType(baseIface, type);
4356 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4357 final String stackedIface = stacked.getInterfaceName();
4358 bs.noteNetworkInterfaceType(stackedIface, type);
4359 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4360 }
4361 } catch (RemoteException ignored) {
4362 }
4363
Robert Greenwalt152ed372014-12-17 17:19:53 -08004364 // This has to happen after the notifyNetworkCallbacks as that tickles each
4365 // ConnectivityManager instance so that legacy requests correctly bind dns
4366 // requests to this network. The legacy users are listening for this bcast
4367 // and will generally do a dns request so they can ensureRouteToHost and if
4368 // they do that before the callbacks happen they'll use the default network.
4369 //
4370 // TODO: Is there still a race here? We send the broadcast
4371 // after sending the callback, but if the app can receive the
4372 // broadcast before the callback, it might still break.
4373 //
4374 // This *does* introduce a race where if the user uses the new api
4375 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4376 // they may get old info. Reverse this after the old startUsing api is removed.
4377 // This is on top of the multiple intent sequencing referenced in the todo above.
4378 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4379 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4380 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4381 // legacy type tracker filters out repeat adds
4382 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4383 }
4384 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004385
4386 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4387 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4388 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4389 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4390 if (newNetwork.isVPN()) {
4391 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4392 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004393 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004394 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4395 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004396 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004397 if (DBG) log("Reaping " + nai.name());
4398 teardownUnneededNetwork(nai);
4399 }
4400 }
4401 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004402 }
4403
Paul Jensen1c7ba022015-06-16 14:27:36 -04004404 /**
4405 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4406 * being disconnected.
4407 * @param changed If only one Network's score or capabilities have been modified since the last
4408 * time this function was called, pass this Network in this argument, otherwise pass
4409 * null.
4410 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4411 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4412 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4413 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4414 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004415 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004416 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004417 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4418 // to avoid the slowness. It is not simply enough to process just "changed", for
4419 // example in the case where "changed"'s score decreases and another network should begin
4420 // satifying a NetworkRequest that "changed" currently satisfies.
4421
4422 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4423 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4424 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004425 if (changed != null && oldScore < changed.getCurrentScore()) {
4426 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004427 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004428 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4429 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4430 // Rematch higher scoring networks first to prevent requests first matching a lower
4431 // scoring network and then a higher scoring network, which could produce multiple
4432 // callbacks and inadvertently unlinger networks.
4433 Arrays.sort(nais);
4434 for (NetworkAgentInfo nai : nais) {
4435 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004436 // Only reap the last time through the loop. Reaping before all rematching
4437 // is complete could incorrectly teardown a network that hasn't yet been
4438 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004439 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004440 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004441 }
4442 }
4443 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004444
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004445 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004446 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004447 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004448 // For now only update icons for default connection.
4449 // TODO: Update WiFi and cellular icons separately. b/17237507
4450 if (!isDefaultNetwork(nai)) return;
4451
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004452 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004453 // Don't repeat publish.
4454 if (newInetCondition == mDefaultInetConditionPublished) return;
4455
4456 mDefaultInetConditionPublished = newInetCondition;
4457 sendInetConditionBroadcast(nai.networkInfo);
4458 }
4459
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004460 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4461 if (mLockdownTracker != null) {
4462 if (nai != null && nai.isVPN()) {
4463 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4464 } else {
4465 mLockdownTracker.onNetworkInfoChanged();
4466 }
4467 }
4468 }
4469
Robert Greenwalt7b816022014-04-18 15:25:25 -07004470 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4471 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004472 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004473 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004474 synchronized (networkAgent) {
4475 oldInfo = networkAgent.networkInfo;
4476 networkAgent.networkInfo = newInfo;
4477 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004478 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004479
4480 if (oldInfo != null && oldInfo.getState() == state) {
4481 if (VDBG) log("ignoring duplicate network state non-change");
4482 return;
4483 }
4484 if (DBG) {
4485 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4486 (oldInfo == null ? "null" : oldInfo.getState()) +
4487 " to " + state);
4488 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004489
Paul Jenseneec75412014-08-04 12:21:19 -04004490 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004491 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004492 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004493 if (networkAgent.isVPN()) {
4494 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004495 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4496 (networkAgent.networkMisc == null ||
4497 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004498 } else {
4499 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4500 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004501 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004502 loge("Error creating network " + networkAgent.network.netId + ": "
4503 + e.getMessage());
4504 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004505 }
Paul Jenseneec75412014-08-04 12:21:19 -04004506 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004507 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004508 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004509
Paul Jensenca8f16a2014-05-09 12:47:55 -04004510 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004511 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004512
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004513 if (networkAgent.isVPN()) {
4514 // Temporarily disable the default proxy (not global).
4515 synchronized (mProxyLock) {
4516 if (!mDefaultProxyDisabled) {
4517 mDefaultProxyDisabled = true;
4518 if (mGlobalProxy == null && mDefaultProxy != null) {
4519 sendProxyBroadcast(null);
4520 }
4521 }
4522 }
4523 // TODO: support proxy per network.
4524 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004525
Paul Jensen2161a8e2014-09-11 11:00:39 -04004526 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004527 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004528
4529 // This has to happen after matching the requests, because callbacks are just requests.
4530 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004531 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004533 if (networkAgent.isVPN()) {
4534 synchronized (mProxyLock) {
4535 if (mDefaultProxyDisabled) {
4536 mDefaultProxyDisabled = false;
4537 if (mGlobalProxy == null && mDefaultProxy != null) {
4538 sendProxyBroadcast(mDefaultProxy);
4539 }
4540 }
4541 }
4542 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004543 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4544 state == NetworkInfo.State.SUSPENDED) {
4545 // going into or coming out of SUSPEND: rescore and notify
4546 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004547 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004548 }
4549 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4550 ConnectivityManager.CALLBACK_SUSPENDED :
4551 ConnectivityManager.CALLBACK_RESUMED));
4552 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004553 }
4554 }
4555
Robert Greenwaltac96c522014-06-03 16:43:57 -07004556 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4557 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004558 if (score < 0) {
4559 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4560 "). Bumping score to min of 0");
4561 score = 0;
4562 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004563
Paul Jensen2161a8e2014-09-11 11:00:39 -04004564 final int oldScore = nai.getCurrentScore();
4565 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004566
Paul Jensen85cf78e2015-06-25 13:25:07 -04004567 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004568
Paul Jensenc8b9a742014-09-30 15:37:41 -04004569 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004570 }
4571
Robert Greenwalt9258c642014-03-26 16:47:06 -07004572 // notify only this one new request of the current state
4573 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4574 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4575 // TODO - read state from monitor to decide what to send.
4576// if (nai.networkMonitor.isLingering()) {
4577// notifyType = NetworkCallbacks.LOSING;
4578// } else if (nai.networkMonitor.isEvaluating()) {
4579// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4580// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004581 if (nri.mPendingIntent == null) {
4582 callCallbackForRequest(nri, nai, notifyType);
4583 } else {
4584 sendPendingIntentForRequest(nri, nai, notifyType);
4585 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004586 }
4587
Robert Greenwalt8d482522015-06-24 13:23:42 -07004588 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004589 // The NetworkInfo we actually send out has no bearing on the real
4590 // state of affairs. For example, if the default connection is mobile,
4591 // and a request for HIPRI has just gone away, we need to pretend that
4592 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4593 // the state to DISCONNECTED, even though the network is of type MOBILE
4594 // and is still connected.
4595 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4596 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004597 if (state != DetailedState.DISCONNECTED) {
4598 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004599 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004600 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004601 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004602 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4603 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4604 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4605 if (info.isFailover()) {
4606 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4607 nai.networkInfo.setFailover(false);
4608 }
4609 if (info.getReason() != null) {
4610 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4611 }
4612 if (info.getExtraInfo() != null) {
4613 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4614 }
4615 NetworkAgentInfo newDefaultAgent = null;
4616 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004617 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004618 if (newDefaultAgent != null) {
4619 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4620 newDefaultAgent.networkInfo);
4621 } else {
4622 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4623 }
4624 }
4625 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4626 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004627 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004628 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004629 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004630 }
4631 }
4632 }
4633
Robert Greenwalt7b816022014-04-18 15:25:25 -07004634 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004635 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004636 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004637 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4638 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4639 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004640 if (nri.mPendingIntent == null) {
4641 callCallbackForRequest(nri, networkAgent, notifyType);
4642 } else {
4643 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4644 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004645 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004646 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004647
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004648 private String notifyTypeToName(int notifyType) {
4649 switch (notifyType) {
4650 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4651 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4652 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4653 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4654 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4655 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4656 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4657 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4658 }
4659 return "UNKNOWN";
4660 }
4661
Jeff Sharkey69736342014-12-08 14:50:12 -08004662 /**
4663 * Notify other system services that set of active ifaces has changed.
4664 */
4665 private void notifyIfacesChanged() {
4666 try {
4667 mStatsService.forceUpdateIfaces();
4668 } catch (Exception ignored) {
4669 }
4670 }
4671
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004672 @Override
4673 public boolean addVpnAddress(String address, int prefixLength) {
4674 throwIfLockdownEnabled();
4675 int user = UserHandle.getUserId(Binder.getCallingUid());
4676 synchronized (mVpns) {
4677 return mVpns.get(user).addAddress(address, prefixLength);
4678 }
4679 }
4680
4681 @Override
4682 public boolean removeVpnAddress(String address, int prefixLength) {
4683 throwIfLockdownEnabled();
4684 int user = UserHandle.getUserId(Binder.getCallingUid());
4685 synchronized (mVpns) {
4686 return mVpns.get(user).removeAddress(address, prefixLength);
4687 }
4688 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004689
4690 @Override
4691 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4692 throwIfLockdownEnabled();
4693 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004694 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004695 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004696 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004697 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004698 if (success) {
4699 notifyIfacesChanged();
4700 }
4701 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004702 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004703
4704 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004705 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4706 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4707 enforceKeepalivePermission();
4708 mKeepaliveTracker.startNattKeepalive(
4709 getNetworkAgentInfoForNetwork(network),
4710 intervalSeconds, messenger, binder,
4711 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4712 }
4713
4714 @Override
4715 public void stopKeepalive(Network network, int slot) {
4716 mHandler.sendMessage(mHandler.obtainMessage(
4717 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
4718 }
4719
4720 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07004721 public void factoryReset() {
4722 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004723
4724 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4725 return;
4726 }
4727
Robin Lee3b3dd942015-05-12 18:14:58 +01004728 final int userId = UserHandle.getCallingUserId();
4729
Stuart Scottf1fb3972015-04-02 18:00:02 -07004730 // Turn airplane mode off
4731 setAirplaneMode(false);
4732
Stuart Scotte3e314d2015-04-20 14:07:45 -07004733 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4734 // Untether
4735 for (String tether : getTetheredIfaces()) {
4736 untether(tether);
4737 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004738 }
4739
Stuart Scotte3e314d2015-04-20 14:07:45 -07004740 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4741 // Turn VPN off
4742 VpnConfig vpnConfig = getVpnConfig(userId);
4743 if (vpnConfig != null) {
4744 if (vpnConfig.legacy) {
4745 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4746 } else {
4747 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4748 // in the future without user intervention.
4749 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004750
Stuart Scotte3e314d2015-04-20 14:07:45 -07004751 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4752 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004753 }
4754 }
4755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004756}