blob: b72b29dbb1d287a1fa212f4ddb0643ce6e926f6a [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
Jeff Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baidb3c8672012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Robert Greenwalt12e67352014-05-13 21:41:06 -070023import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070024import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070025import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070026import static android.net.ConnectivityManager.isNetworkTypeValid;
27import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070028import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070029
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070030import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070031import android.app.Notification;
32import android.app.NotificationManager;
33import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070034import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.ContentResolver;
36import android.content.Context;
37import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070038import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070040import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090041import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070042import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.net.ConnectivityManager;
44import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070045import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070046import android.net.INetworkPolicyListener;
47import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070048import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080049import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070050import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.MobileDataStateTracker;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070052import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070053import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070054import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070055import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070058import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070059import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070061import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070063import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070064import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040065import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070066import android.net.RouteInfo;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070067import android.net.SamplingDataTracker;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040068import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040069import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070071import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040072import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070074import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070075import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070076import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Looper;
78import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070079import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070080import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070081import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070082import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070083import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070084import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070086import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040087import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070089import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070090import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070091import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070092import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080093import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070094import android.util.SparseArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070095import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070096import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
Wink Savilleab9321d2013-06-29 21:10:57 -070098import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -040099import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700100import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700101import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700102import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700103import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700106import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700107import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700108import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700109import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400110import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900111import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700112import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400113import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400114import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700115import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800116import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700117import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700118import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700119import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700120import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700121import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700122
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700123import org.xmlpull.v1.XmlPullParser;
124import org.xmlpull.v1.XmlPullParserException;
125
126import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700128import java.io.FileNotFoundException;
129import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700130import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700132import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700133import java.net.InetAddress;
134import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700135import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700136import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700137import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700138import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700139import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500140import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700141import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700142import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700143import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700144import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146/**
147 * @hide
148 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800149public class ConnectivityService extends IConnectivityManager.Stub
150 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700151 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700153 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700154 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
Robert Greenwalt31106052014-05-16 17:19:24 -0700156 // network sampling debugging
157 private static final boolean SAMPLE_DBG = false;
158
Jake Hamby786e71a2014-02-06 14:43:50 -0800159 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700160
Jeff Sharkey899223b2012-08-04 15:24:58 -0700161 // TODO: create better separation between radio types and network types
162
Robert Greenwalt42acef32009-08-12 16:08:25 -0700163 // how long to wait before switching back to a radio's default network
164 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
165 // system property that can override the above value
166 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
167 "android.telephony.apn-restore";
168
Wink Savilleab9321d2013-06-29 21:10:57 -0700169 // Default value if FAIL_FAST_TIME_MS is not set
170 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
171 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
172 private static final String FAIL_FAST_TIME_MS =
173 "persist.radio.fail_fast_time_ms";
174
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700175 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
176 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
177
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -0700178 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700179
Jeremy Joslin79294842014-12-03 17:15:28 -0800180 // How long to delay to removal of a pending intent based request.
181 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
182 private final int mReleasePendingIntentDelayMs;
183
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700184 private PendingIntent mSampleIntervalElapsedIntent;
185
186 // Set network sampling interval at 12 minutes, this way, even if the timers get
187 // aggregated, it will fire at around 15 minutes, which should allow us to
188 // aggregate this timer with other timers (specially the socket keep alive timers)
Robert Greenwalt31106052014-05-16 17:19:24 -0700189 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 12 * 60);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700190
191 // start network sampling a minute after booting ...
Robert Greenwalt31106052014-05-16 17:19:24 -0700192 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 60);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700193
194 AlarmManager mAlarmManager;
195
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800196 private Tethering mTethering;
197
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700198 private final PermissionMonitor mPermissionMonitor;
199
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700200 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700201
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700202 @GuardedBy("mVpns")
203 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700204
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700205 private boolean mLockdownEnabled;
206 private LockdownVpnTracker mLockdownTracker;
207
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700208 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
209 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210 /** Currently active network rules by UID. */
211 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700212 /** Set of ifaces that are costly. */
213 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 /**
216 * Sometimes we want to refer to the individual network state
217 * trackers separately, and sometimes we just want to treat them
218 * abstractly.
219 */
220 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 private Context mContext;
223 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700224 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700225 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700227 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800228 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
230 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700231 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700233 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800234 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700235 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700236
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700237 private String mCurrentTcpBufferSizes;
238
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700239 private static final int ENABLED = 1;
240 private static final int DISABLED = 0;
241
Paul Jensenb10e37f2014-11-25 12:33:08 -0500242 // Arguments to rematchNetworkAndRequests()
243 private enum NascentState {
244 // Indicates a network was just validated for the first time. If the network is found to
245 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
246 JUST_VALIDATED,
247 // Indicates a network was not validated for the first time immediately prior to this call.
248 NOT_JUST_VALIDATED
249 };
250 private enum ReapUnvalidatedNetworks {
251 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
252 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
253 // known that there may be unvalidated networks that could potentially be reaped, and when
254 // all networks have been rematched against all NetworkRequests.
255 REAP,
256 // Don't reap unvalidated networks. This should be passed when it's known that there are
257 // no unvalidated networks that could potentially be reaped, and when some networks have
258 // not yet been rematched against all NetworkRequests.
259 DONT_REAP
260 };
261
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700262 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700263 * used internally to change our mobile data enabled flag
264 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700265 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700266
267 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700268 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700269 * from one net to another. Clear happens when we get a new
270 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
271 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700272 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700273 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700274
Robert Greenwalt434203a2010-10-11 16:00:27 -0700275 /**
276 * used internally to reload global proxy settings
277 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700278 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700279
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700280 /**
281 * used internally to set external dependency met/unmet
282 * arg1 = ENABLED (met) or DISABLED (unmet)
283 * arg2 = NetworkType
284 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700285 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700286
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700287 /**
Wink Saville628b0852011-08-04 15:01:58 -0700288 * used internally to send a sticky broadcast delayed.
289 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700290 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700291
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700292 /**
Wink Savilleab9321d2013-06-29 21:10:57 -0700293 * Used internally to disable fail fast of mobile data
294 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700295 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Savilleab9321d2013-06-29 21:10:57 -0700296
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700297 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -0700298 * used internally to indicate that data sampling interval is up
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700299 */
300 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
301
Jason Monkdecd2952013-10-10 14:02:51 -0400302 /**
303 * PAC manager has received new port.
304 */
305 private static final int EVENT_PROXY_HAS_CHANGED = 16;
306
Robert Greenwalte049c232014-04-11 15:53:27 -0700307 /**
308 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700309 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700310 */
311 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
312
Robert Greenwalt7b816022014-04-18 15:25:25 -0700313 /**
314 * used internally when registering NetworkAgents
315 * obj = Messenger
316 */
317 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
318
Robert Greenwalt9258c642014-03-26 16:47:06 -0700319 /**
320 * used to add a network request
321 * includes a NetworkRequestInfo
322 */
323 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
324
325 /**
326 * indicates a timeout period is over - check if we had a network yet or not
327 * and if not, call the timeout calback (but leave the request live until they
328 * cancel it.
329 * includes a NetworkRequestInfo
330 */
331 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
332
333 /**
334 * used to add a network listener - no request
335 * includes a NetworkRequestInfo
336 */
337 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
338
339 /**
340 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400341 * arg1 = UID of caller
342 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700343 */
344 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
345
Robert Greenwalta67be032014-05-16 15:49:14 -0700346 /**
347 * used internally when registering NetworkFactories
348 * obj = Messenger
349 */
350 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
351
Robert Greenwalt27711812014-06-25 16:45:57 -0700352 /**
353 * used internally to expire a wakelock when transitioning
354 * from one net to another. Expire happens when we fail to find
355 * a new network (typically after 1 minute) -
356 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
357 * a replacement network.
358 */
359 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
360
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700361 /**
362 * Used internally to indicate the system is ready.
363 */
364 private static final int EVENT_SYSTEM_READY = 25;
365
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800366 /**
367 * used to add a network request with a pending intent
368 * includes a NetworkRequestInfo
369 */
370 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
371
372 /**
373 * used to remove a pending intent and its associated network request.
374 * arg1 = UID of caller
375 * obj = PendingIntent
376 */
377 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
378
Robert Greenwalta67be032014-05-16 15:49:14 -0700379
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700380 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700381 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700382 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700383 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700384
Mike Lockwood0f79b542009-08-14 14:18:49 -0400385 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800386 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400387
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700388 private PowerManager.WakeLock mNetTransitionWakeLock;
389 private String mNetTransitionWakeLockCausedBy = "";
390 private int mNetTransitionWakeLockSerialNumber;
391 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800392 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700393
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700394 private InetAddress mDefaultDns;
395
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700396 // used in DBG mode to track inet condition reports
397 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
398 private ArrayList mInetLog;
399
Robert Greenwalt434203a2010-10-11 16:00:27 -0700400 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400401 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700402 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700403 private boolean mDefaultProxyDisabled = false;
404
Robert Greenwalt434203a2010-10-11 16:00:27 -0700405 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400406 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700407
Jason Monk602b2322013-07-03 17:04:33 -0400408 private PacManager mPacManager = null;
409
Robert Greenwalt434203a2010-10-11 16:00:27 -0700410 private SettingsObserver mSettingsObserver;
411
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400412 private UserManager mUserManager;
413
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700414 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700415 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700416
Robert Greenwalt50393202011-06-21 17:26:14 -0700417 // the set of network types that can only be enabled by system/sig apps
418 List mProtectedNetworks;
419
John Spurlockbf991a82013-06-24 14:20:23 -0400420 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700421
Wink Savilleab9321d2013-06-29 21:10:57 -0700422 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
423
424 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400425
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700426 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
427 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700428 private final static int MAX_NET_ID = 65535;
429 private int mNextNetId = MIN_NET_ID;
430
Robert Greenwalt34524f02014-05-18 16:22:10 -0700431 // sequence number of NetworkRequests
432 private int mNextNetworkRequestId = 1;
433
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700434 /**
435 * Implements support for the legacy "one network per network type" model.
436 *
437 * We used to have a static array of NetworkStateTrackers, one for each
438 * network type, but that doesn't work any more now that we can have,
439 * for example, more that one wifi network. This class stores all the
440 * NetworkAgentInfo objects that support a given type, but the legacy
441 * API will only see the first one.
442 *
443 * It serves two main purposes:
444 *
445 * 1. Provide information about "the network for a given type" (since this
446 * API only supports one).
447 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
448 * the first network for a given type changes, or if the default network
449 * changes.
450 */
451 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900452
453 private static final boolean DBG = true;
454 private static final boolean VDBG = false;
455 private static final String TAG = "CSLegacyTypeTracker";
456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 /**
458 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
459 * Each list holds references to all NetworkAgentInfos that are used to
460 * satisfy requests for that network type.
461 *
462 * This array is built out at startup such that an unsupported network
463 * doesn't get an ArrayList instance, making this a tristate:
464 * unsupported, supported but not active and active.
465 *
466 * The actual lists are populated when we scan the network types that
467 * are supported on this device.
468 */
469 private ArrayList<NetworkAgentInfo> mTypeLists[];
470
471 public LegacyTypeTracker() {
472 mTypeLists = (ArrayList<NetworkAgentInfo>[])
473 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
474 }
475
476 public void addSupportedType(int type) {
477 if (mTypeLists[type] != null) {
478 throw new IllegalStateException(
479 "legacy list for type " + type + "already initialized");
480 }
481 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
482 }
483
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700484 public boolean isTypeSupported(int type) {
485 return isNetworkTypeValid(type) && mTypeLists[type] != null;
486 }
487
488 public NetworkAgentInfo getNetworkForType(int type) {
489 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
490 return mTypeLists[type].get(0);
491 } else {
492 return null;
493 }
494 }
495
Lorenzo Colittia793a672014-07-31 23:20:17 +0900496 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
497 if (DBG) {
498 log("Sending " + (connected ? "connected" : "disconnected") +
499 " broadcast for type " + type + " " + nai.name() +
500 " isDefaultNetwork=" + isDefaultNetwork(nai));
501 }
502 }
503
504 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700505 public void add(int type, NetworkAgentInfo nai) {
506 if (!isTypeSupported(type)) {
507 return; // Invalid network type.
508 }
509 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
510
511 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
512 if (list.contains(nai)) {
513 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
514 return;
515 }
516
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900517 list.add(nai);
518
519 // Send a broadcast if this is the first network of its type or if it's the default.
520 if (list.size() == 1 || isDefaultNetwork(nai)) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900521 maybeLogBroadcast(nai, true, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700522 sendLegacyNetworkBroadcast(nai, true, type);
523 }
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. */
527 public void remove(int type, NetworkAgentInfo nai) {
528 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
529 if (list == null || list.isEmpty()) {
530 return;
531 }
532
533 boolean wasFirstNetwork = list.get(0).equals(nai);
534
535 if (!list.remove(nai)) {
536 return;
537 }
538
539 if (wasFirstNetwork || isDefaultNetwork(nai)) {
540 maybeLogBroadcast(nai, false, type);
541 sendLegacyNetworkBroadcast(nai, false, type);
542 }
543
544 if (!list.isEmpty() && wasFirstNetwork) {
545 if (DBG) log("Other network available for type " + type +
546 ", sending connected broadcast");
547 maybeLogBroadcast(list.get(0), false, type);
548 sendLegacyNetworkBroadcast(list.get(0), false, type);
549 }
550 }
551
552 /** Removes the given network from all legacy type lists. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700553 public void remove(NetworkAgentInfo nai) {
554 if (VDBG) log("Removing agent " + nai);
555 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900556 remove(type, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700557 }
558 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700559
Lorenzo Colittia793a672014-07-31 23:20:17 +0900560 private String naiToString(NetworkAgentInfo nai) {
561 String name = (nai != null) ? nai.name() : "null";
562 String state = (nai.networkInfo != null) ?
563 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
564 "???/???";
565 return name + " " + state;
566 }
567
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700568 public void dump(IndentingPrintWriter pw) {
569 for (int type = 0; type < mTypeLists.length; type++) {
570 if (mTypeLists[type] == null) continue;
571 pw.print(type + " ");
572 pw.increaseIndent();
573 if (mTypeLists[type].size() == 0) pw.println("none");
574 for (NetworkAgentInfo nai : mTypeLists[type]) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900575 pw.println(naiToString(nai));
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700576 }
577 pw.decreaseIndent();
578 }
579 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580
581 // This class needs its own log method because it has a different TAG.
582 private void log(String s) {
583 Slog.d(TAG, s);
584 }
585
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700586 }
587 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
588
Jeff Sharkey899223b2012-08-04 15:24:58 -0700589 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700590 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800591 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800592
Robert Greenwalte049c232014-04-11 15:53:27 -0700593 NetworkCapabilities netCap = new NetworkCapabilities();
Robert Greenwalt7569f182014-06-08 16:42:59 -0700594 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
595 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -0700597 NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(),
598 NetworkRequestInfo.REQUEST);
599 mNetworkRequests.put(mDefaultRequest, nri);
Robert Greenwalte049c232014-04-11 15:53:27 -0700600
Wink Savillebb08caf2010-09-02 19:23:52 -0700601 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
602 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700603 mHandler = new InternalHandler(handlerThread.getLooper());
604 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700605
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800606 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800607 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
608 String id = Settings.Secure.getString(context.getContentResolver(),
609 Settings.Secure.ANDROID_ID);
610 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700611 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800612 SystemProperties.set("net.hostname", name);
613 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800614 }
615
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700616 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700617 String dns = Settings.Global.getString(context.getContentResolver(),
618 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700619 if (dns == null || dns.length() == 0) {
620 dns = context.getResources().getString(
621 com.android.internal.R.string.config_default_dns_server);
622 }
623 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800624 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
625 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800626 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700627 }
628
Jeremy Joslin79294842014-12-03 17:15:28 -0800629 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
630 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
631
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700632 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700633 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800634 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700635 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700636 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700637 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700638
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700639 try {
640 mPolicyManager.registerListener(mPolicyListener);
641 } catch (RemoteException e) {
642 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700643 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700644 }
645
646 final PowerManager powerManager = (PowerManager) context.getSystemService(
647 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700648 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
649 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
650 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800651 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700652
Robert Greenwalt42acef32009-08-12 16:08:25 -0700653 mNetTrackers = new NetworkStateTracker[
654 ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700655
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700656 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700657
Wink Saville51f456f2013-04-23 14:26:51 -0700658 // TODO: What is the "correct" way to do determine if this is a wifi only device?
659 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
660 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700661 String[] naStrings = context.getResources().getStringArray(
662 com.android.internal.R.array.networkAttributes);
663 for (String naString : naStrings) {
664 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700665 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700666 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700667 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800668 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700669 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700670 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700671 }
Wink Saville51f456f2013-04-23 14:26:51 -0700672 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
673 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
674 n.type);
675 continue;
676 }
Wink Saville975c8482011-04-07 14:23:45 -0700677 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800678 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700679 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700680 continue;
681 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700682 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700683
Wink Saville975c8482011-04-07 14:23:45 -0700684 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700685 mNetworksDefined++;
686 } catch(Exception e) {
687 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700688 }
689 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700690
691 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
692 if (mNetConfigs[TYPE_VPN] == null) {
693 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
694 // don't need to add TYPE_VPN to mNetConfigs.
695 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
696 mNetworksDefined++; // used only in the log() statement below.
697 }
698
Wink Saville5e56bc52013-07-29 15:00:57 -0700699 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700700
Robert Greenwalt50393202011-06-21 17:26:14 -0700701 mProtectedNetworks = new ArrayList<Integer>();
702 int[] protectedNetworks = context.getResources().getIntArray(
703 com.android.internal.R.array.config_protectedNetworks);
704 for (int p : protectedNetworks) {
705 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
706 mProtectedNetworks.add(p);
707 } else {
708 if (DBG) loge("Ignoring protectedNetwork " + p);
709 }
710 }
711
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700712 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
713 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700714
Robert Greenwaltfab501672014-07-23 11:44:01 -0700715 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800716
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700717 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
718
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700719 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700720 IntentFilter intentFilter = new IntentFilter();
721 intentFilter.addAction(Intent.ACTION_USER_STARTING);
722 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
723 mContext.registerReceiverAsUser(
724 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900725
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700726 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700727 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700728 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700729 } catch (RemoteException e) {
730 loge("Error registering observer :" + e);
731 }
732
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700733 if (DBG) {
734 mInetLog = new ArrayList();
735 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700736
737 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
738 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800739
John Spurlockbf991a82013-06-24 14:20:23 -0400740 mDataConnectionStats = new DataConnectionStats(mContext);
741 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400742
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700743 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700744
745 IntentFilter filter = new IntentFilter();
746 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
747 mContext.registerReceiver(
748 new BroadcastReceiver() {
749 @Override
750 public void onReceive(Context context, Intent intent) {
751 String action = intent.getAction();
752 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
753 mHandler.sendMessage(mHandler.obtainMessage
754 (EVENT_SAMPLE_INTERVAL_ELAPSED));
755 }
756 }
757 },
758 new IntentFilter(filter));
759
Jason Monkdecd2952013-10-10 14:02:51 -0400760 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700761
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400762 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700764
Robert Greenwalt34524f02014-05-18 16:22:10 -0700765 private synchronized int nextNetworkRequestId() {
766 return mNextNetworkRequestId++;
767 }
768
Paul Jensen60061a62014-08-05 14:13:48 -0400769 private void assignNextNetId(NetworkAgentInfo nai) {
770 synchronized (mNetworkForNetId) {
771 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
772 int netId = mNextNetId;
773 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
774 // Make sure NetID unused. http://b/16815182
775 if (mNetworkForNetId.get(netId) == null) {
776 nai.network = new Network(netId);
777 mNetworkForNetId.put(netId, nai);
778 return;
779 }
780 }
781 }
782 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700783 }
784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 private boolean teardown(NetworkStateTracker netTracker) {
786 if (netTracker.teardown()) {
787 netTracker.setTeardownRequested(true);
788 return true;
789 } else {
790 return false;
791 }
792 }
793
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800794 private NetworkState getFilteredNetworkState(int networkType, int uid) {
795 NetworkInfo info = null;
796 LinkProperties lp = null;
797 NetworkCapabilities nc = null;
798 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800799 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800800
801 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
802 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
803 if (nai != null) {
804 synchronized (nai) {
805 info = new NetworkInfo(nai.networkInfo);
806 lp = new LinkProperties(nai.linkProperties);
807 nc = new NetworkCapabilities(nai.networkCapabilities);
808 network = new Network(nai.network);
Jeff Sharkey32566012014-12-02 18:30:14 -0800809 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800810 }
811 info.setType(networkType);
812 } else {
813 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
814 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
815 info.setIsAvailable(true);
816 lp = new LinkProperties();
817 nc = new NetworkCapabilities();
818 network = null;
819 }
820 info = getFilteredNetworkInfo(info, lp, uid);
821 }
822
Jeff Sharkey32566012014-12-02 18:30:14 -0800823 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400824 }
825
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800826 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
827 if (network == null) {
828 return null;
829 }
830 synchronized (mNetworkForNetId) {
831 return mNetworkForNetId.get(network.netId);
832 }
833 };
834
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900835 private Network[] getVpnUnderlyingNetworks(int uid) {
836 if (!mLockdownEnabled) {
837 int user = UserHandle.getUserId(uid);
838 synchronized (mVpns) {
839 Vpn vpn = mVpns.get(user);
840 if (vpn != null && vpn.appliesToUid(uid)) {
841 return vpn.getUnderlyingNetworks();
842 }
843 }
844 }
845 return null;
846 }
847
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800848 private NetworkState getUnfilteredActiveNetworkState(int uid) {
849 NetworkInfo info = null;
850 LinkProperties lp = null;
851 NetworkCapabilities nc = null;
852 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800853 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800854
855 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800856
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900857 final Network[] networks = getVpnUnderlyingNetworks(uid);
858 if (networks != null) {
859 // getUnderlyingNetworks() returns:
860 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
861 // empty array => the VPN explicitly said "no default network".
862 // non-empty array => the VPN specified one or more default networks; we use the
863 // first one.
864 if (networks.length > 0) {
865 nai = getNetworkAgentInfoForNetwork(networks[0]);
866 } else {
867 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800868 }
869 }
870
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800871 if (nai != null) {
872 synchronized (nai) {
873 info = new NetworkInfo(nai.networkInfo);
874 lp = new LinkProperties(nai.linkProperties);
875 nc = new NetworkCapabilities(nai.networkCapabilities);
876 network = new Network(nai.network);
Jeff Sharkey32566012014-12-02 18:30:14 -0800877 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800878 }
879 }
880
Jeff Sharkey32566012014-12-02 18:30:14 -0800881 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400882 }
883
884 /**
885 * Check if UID should be blocked from using the network with the given LinkProperties.
886 */
887 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700888 final boolean networkCostly;
889 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700890
Robert Greenwalt12e67352014-05-13 21:41:06 -0700891 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700892 synchronized (mRulesLock) {
893 networkCostly = mMeteredIfaces.contains(iface);
894 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700895 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700896
897 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
898 return true;
899 }
900
901 // no restrictive rules; network is visible
902 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700903 }
904
905 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700906 * Return a filtered {@link NetworkInfo}, potentially marked
907 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800908 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700909 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800910 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
911 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400912 // network is blocked; clone and override state
913 info = new NetworkInfo(info);
914 info.setDetailedState(DetailedState.BLOCKED, null, null);
Erik Kline338317e2015-01-19 16:19:09 +0900915 if (DBG) {
916 log("returning Blocked NetworkInfo for ifname=" +
917 lp.getInterfaceName() + ", uid=" + uid);
918 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700919 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800920 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700921 info = mLockdownTracker.augmentNetworkInfo(info);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700922 if (DBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700923 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700924 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700925 }
926
927 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 * Return NetworkInfo for the active (i.e., connected) network interface.
929 * It is assumed that at most one network is active at a time. If more
930 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700931 * @return the info for the active network, or {@code null} if none is
932 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700934 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700936 enforceAccessPermission();
937 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800938 NetworkState state = getUnfilteredActiveNetworkState(uid);
939 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 }
941
Wink Saville948282b2013-08-29 08:55:16 -0700942 /**
943 * Find the first Provisioning network.
944 *
945 * @return NetworkInfo or null if none.
946 */
947 private NetworkInfo getProvisioningNetworkInfo() {
948 enforceAccessPermission();
949
950 // Find the first Provisioning Network
951 NetworkInfo provNi = null;
952 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700953 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700954 provNi = ni;
955 break;
956 }
957 }
958 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
959 return provNi;
960 }
961
962 /**
963 * Find the first Provisioning network or the ActiveDefaultNetwork
964 * if there is no Provisioning network
965 *
966 * @return NetworkInfo or null if none.
967 */
968 @Override
969 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
970 enforceAccessPermission();
971
972 NetworkInfo provNi = getProvisioningNetworkInfo();
973 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800974 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700975 }
976 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
977 return provNi;
978 }
979
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700980 public NetworkInfo getActiveNetworkInfoUnfiltered() {
981 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800982 final int uid = Binder.getCallingUid();
983 NetworkState state = getUnfilteredActiveNetworkState(uid);
984 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700985 }
986
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700987 @Override
988 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
989 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800990 NetworkState state = getUnfilteredActiveNetworkState(uid);
991 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700992 }
993
994 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 public NetworkInfo getNetworkInfo(int networkType) {
996 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700997 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900998 if (getVpnUnderlyingNetworks(uid) != null) {
999 // A VPN is active, so we may need to return one of its underlying networks. This
1000 // information is not available in LegacyTypeTracker, so we have to get it from
1001 // getUnfilteredActiveNetworkState.
1002 NetworkState state = getUnfilteredActiveNetworkState(uid);
1003 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1004 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1005 }
1006 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001007 NetworkState state = getFilteredNetworkState(networkType, uid);
1008 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 }
1010
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001011 @Override
1012 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1013 enforceAccessPermission();
1014 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001015 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001016 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1017 if (nai != null) {
1018 synchronized (nai) {
1019 info = new NetworkInfo(nai.networkInfo);
1020 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001021 }
1022 }
1023 return info;
1024 }
1025
1026 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 public NetworkInfo[] getAllNetworkInfo() {
1028 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001029 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001030 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1031 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001032 NetworkInfo info = getNetworkInfo(networkType);
1033 if (info != null) {
1034 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001037 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
1039
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001040 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001041 public Network getNetworkForType(int networkType) {
1042 enforceAccessPermission();
1043 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001044 NetworkState state = getFilteredNetworkState(networkType, uid);
1045 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1046 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001047 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001048 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001049 }
1050
1051 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001052 public Network[] getAllNetworks() {
1053 enforceAccessPermission();
1054 final ArrayList<Network> result = new ArrayList();
1055 synchronized (mNetworkForNetId) {
1056 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1057 result.add(new Network(mNetworkForNetId.valueAt(i).network));
1058 }
1059 }
1060 return result.toArray(new Network[result.size()]);
1061 }
1062
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001063 private NetworkCapabilities getNetworkCapabilitiesAndValidation(NetworkAgentInfo nai) {
1064 if (nai != null) {
1065 synchronized (nai) {
1066 if (nai.created) {
1067 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001068 if (nai.lastValidated) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001069 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1070 } else {
1071 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1072 }
1073 return nc;
1074 }
1075 }
1076 }
1077 return null;
1078 }
1079
1080 @Override
1081 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1082 // The basic principle is: if an app's traffic could possibly go over a
1083 // network, without the app doing anything multinetwork-specific,
1084 // (hence, by "default"), then include that network's capabilities in
1085 // the array.
1086 //
1087 // In the normal case, app traffic only goes over the system's default
1088 // network connection, so that's the only network returned.
1089 //
1090 // With a VPN in force, some app traffic may go into the VPN, and thus
1091 // over whatever underlying networks the VPN specifies, while other app
1092 // traffic may go over the system default network (e.g.: a split-tunnel
1093 // VPN, or an app disallowed by the VPN), so the set of networks
1094 // returned includes the VPN's underlying networks and the system
1095 // default.
1096 enforceAccessPermission();
1097
1098 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1099
1100 NetworkAgentInfo nai = getDefaultNetwork();
1101 NetworkCapabilities nc = getNetworkCapabilitiesAndValidation(getDefaultNetwork());
1102 if (nc != null) {
1103 result.put(nai.network, nc);
1104 }
1105
1106 if (!mLockdownEnabled) {
1107 synchronized (mVpns) {
1108 Vpn vpn = mVpns.get(userId);
1109 if (vpn != null) {
1110 Network[] networks = vpn.getUnderlyingNetworks();
1111 if (networks != null) {
1112 for (Network network : networks) {
1113 nai = getNetworkAgentInfoForNetwork(network);
1114 nc = getNetworkCapabilitiesAndValidation(nai);
1115 if (nc != null) {
1116 result.put(nai.network, nc);
1117 }
1118 }
1119 }
1120 }
1121 }
1122 }
1123
1124 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1125 out = result.values().toArray(out);
1126 return out;
1127 }
1128
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001129 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001130 public boolean isNetworkSupported(int networkType) {
1131 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001132 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001133 }
1134
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001135 /**
1136 * Return LinkProperties for the active (i.e., connected) default
1137 * network interface. It is assumed that at most one default network
1138 * is active at a time. If more than one is active, it is indeterminate
1139 * which will be returned.
1140 * @return the ip properties for the active network, or {@code null} if
1141 * none is active
1142 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001143 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001144 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001145 enforceAccessPermission();
1146 final int uid = Binder.getCallingUid();
1147 NetworkState state = getUnfilteredActiveNetworkState(uid);
1148 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001149 }
1150
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001151 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001152 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001153 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001154 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1155 if (nai != null) {
1156 synchronized (nai) {
1157 return new LinkProperties(nai.linkProperties);
1158 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001159 }
1160 return null;
1161 }
1162
Robert Greenwalt12e67352014-05-13 21:41:06 -07001163 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001164 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001165 public LinkProperties getLinkProperties(Network network) {
1166 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001167 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001168 if (nai != null) {
1169 synchronized (nai) {
1170 return new LinkProperties(nai.linkProperties);
1171 }
1172 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001173 return null;
1174 }
1175
1176 @Override
1177 public NetworkCapabilities getNetworkCapabilities(Network network) {
1178 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001180 if (nai != null) {
1181 synchronized (nai) {
1182 return new NetworkCapabilities(nai.networkCapabilities);
1183 }
1184 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001185 return null;
1186 }
1187
1188 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001189 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001190 // Require internal since we're handing out IMSI details
1191 enforceConnectivityInternalPermission();
1192
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001193 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001194 for (Network network : getAllNetworks()) {
1195 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1196 if (nai != null) {
1197 synchronized (nai) {
1198 final String subscriberId = (nai.networkMisc != null)
1199 ? nai.networkMisc.subscriberId : null;
1200 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1201 nai.networkCapabilities, network, subscriberId, null));
1202 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001203 }
1204 }
1205 return result.toArray(new NetworkState[result.size()]);
1206 }
1207
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001208 @Override
1209 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1210 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001211 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001212 final long token = Binder.clearCallingIdentity();
1213 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001214 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1215 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001216 try {
1217 return mPolicyManager.getNetworkQuotaInfo(state);
1218 } catch (RemoteException e) {
1219 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001220 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001221 return null;
1222 } finally {
1223 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001224 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001225 }
1226
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001227 @Override
1228 public boolean isActiveNetworkMetered() {
1229 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001230 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001231 final long token = Binder.clearCallingIdentity();
1232 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001233 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001234 } finally {
1235 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001236 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001237 }
1238
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1240 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1241 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001242 try {
1243 return mPolicyManager.isNetworkMetered(state);
1244 } catch (RemoteException e) {
1245 }
1246 }
1247 return false;
1248 }
1249
Jeff Sharkey216c1812012-08-05 14:29:23 -07001250 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1251 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001252 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001253 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001254 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001255 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001256 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001257
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001258 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 * Ensure that a network route exists to deliver traffic to the specified
1260 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001261 * @param networkType the type of the network over which traffic to the
1262 * specified host is to be routed
1263 * @param hostAddress the IP address of the host to which the route is
1264 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 * @return {@code true} on success, {@code false} on failure
1266 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001267 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001269 if (mProtectedNetworks.contains(networkType)) {
1270 enforceConnectivityInternalPermission();
1271 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001272
Chad Brubakerc0234532014-02-14 13:24:29 -08001273 InetAddress addr;
1274 try {
1275 addr = InetAddress.getByAddress(hostAddress);
1276 } catch (UnknownHostException e) {
1277 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1278 return false;
1279 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001282 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 return false;
1284 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001285
1286 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1287 if (nai == null) {
1288 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1289 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1290 } else {
1291 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1292 }
1293 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001294 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001295
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001296 DetailedState netState;
1297 synchronized (nai) {
1298 netState = nai.networkInfo.getDetailedState();
1299 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001300
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001301 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001302 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001303 log("requestRouteToHostAddress on down network "
1304 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001305 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001306 }
1307 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001309
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001310 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001311 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001312 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001313 LinkProperties lp;
1314 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001315 synchronized (nai) {
1316 lp = nai.linkProperties;
1317 netId = nai.network.netId;
1318 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001319 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001320 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1321 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001322 } finally {
1323 Binder.restoreCallingIdentity(token);
1324 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001325 }
1326
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001327 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001328 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001329 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001330 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001331 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001332 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001333 if (bestRoute.getGateway().equals(addr)) {
1334 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001335 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001336 } else {
1337 // if we will connect to this through another route, add a direct route
1338 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001339 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001340 }
1341 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001342 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001343 try {
1344 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1345 } catch (Exception e) {
1346 // never crash - catch them all
1347 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001348 return false;
1349 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001350 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 }
1352
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001353 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001354 enforceConnectivityInternalPermission();
1355
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001356 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1357 (met ? ENABLED : DISABLED), networkType));
1358 }
1359
1360 private void handleSetDependencyMet(int networkType, boolean met) {
1361 if (mNetTrackers[networkType] != null) {
1362 if (DBG) {
1363 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1364 }
1365 mNetTrackers[networkType].setDependencyMet(met);
1366 }
1367 }
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 }
1409
1410 // kick off connectivity change broadcast for active network, since
1411 // global background policy change is radical.
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001412 // TODO: Dead code; remove.
1413 //
1414 // final int networkType = mActiveDefaultNetwork;
1415 // if (isNetworkTypeValid(networkType)) {
1416 // final NetworkStateTracker tracker = mNetTrackers[networkType];
1417 // if (tracker != null) {
1418 // final NetworkInfo info = tracker.getNetworkInfo();
1419 // if (info != null && info.isConnected()) {
1420 // sendConnectedBroadcast(info);
1421 // }
1422 // }
1423 // }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001424 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001425 };
1426
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001427 private void enforceInternetPermission() {
1428 mContext.enforceCallingOrSelfPermission(
1429 android.Manifest.permission.INTERNET,
1430 "ConnectivityService");
1431 }
1432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001434 mContext.enforceCallingOrSelfPermission(
1435 android.Manifest.permission.ACCESS_NETWORK_STATE,
1436 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 }
1438
1439 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001440 mContext.enforceCallingOrSelfPermission(
1441 android.Manifest.permission.CHANGE_NETWORK_STATE,
1442 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 }
1444
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001445 private void enforceTetherAccessPermission() {
1446 mContext.enforceCallingOrSelfPermission(
1447 android.Manifest.permission.ACCESS_NETWORK_STATE,
1448 "ConnectivityService");
1449 }
1450
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001451 private void enforceConnectivityInternalPermission() {
1452 mContext.enforceCallingOrSelfPermission(
1453 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1454 "ConnectivityService");
1455 }
1456
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001457 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001458 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001459 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1460 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001461 }
1462
1463 private void sendInetConditionBroadcast(NetworkInfo info) {
1464 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1465 }
1466
Wink Saville628b0852011-08-04 15:01:58 -07001467 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001468 if (mLockdownTracker != null) {
1469 info = mLockdownTracker.augmentNetworkInfo(info);
1470 }
1471
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001472 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001473 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001474 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 if (info.isFailover()) {
1476 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1477 info.setFailover(false);
1478 }
1479 if (info.getReason() != null) {
1480 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1481 }
1482 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001483 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1484 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001486 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001487 return intent;
1488 }
1489
1490 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1491 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1492 }
1493
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001494 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001495 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1496 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1497 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001498 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001499 final long ident = Binder.clearCallingIdentity();
1500 try {
1501 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1502 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1503 } finally {
1504 Binder.restoreCallingIdentity(ident);
1505 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001506 }
1507
Mike Lockwood0f79b542009-08-14 14:18:49 -04001508 private void sendStickyBroadcast(Intent intent) {
1509 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001510 if (!mSystemReady) {
1511 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001512 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001513 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001514 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001515 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001516 }
1517
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001518 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001519 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1520 final IBatteryStats bs = BatteryStatsService.getService();
1521 try {
1522 NetworkInfo ni = intent.getParcelableExtra(
1523 ConnectivityManager.EXTRA_NETWORK_INFO);
1524 bs.noteConnectivityChanged(intent.getIntExtra(
1525 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1526 ni != null ? ni.getState().toString() : "?");
1527 } catch (RemoteException e) {
1528 }
1529 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001530 try {
1531 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1532 } finally {
1533 Binder.restoreCallingIdentity(ident);
1534 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001535 }
1536 }
1537
1538 void systemReady() {
Robert Greenwaltf9b5c262014-07-27 09:41:34 -07001539 // start network sampling ..
1540 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
1541 intent.setPackage(mContext.getPackageName());
1542
1543 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
1544 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
1545 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
1546
Wink Saville948282b2013-08-29 08:55:16 -07001547 loadGlobalProxy();
1548
Mike Lockwood0f79b542009-08-14 14:18:49 -04001549 synchronized(this) {
1550 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001551 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001552 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001553 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001554 }
1555 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001556 // load the global proxy at startup
1557 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001558
1559 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1560 // for user to unlock device.
1561 if (!updateLockdownVpn()) {
1562 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1563 mContext.registerReceiver(mUserPresentReceiver, filter);
1564 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001565
1566 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001567
1568 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 }
1570
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001571 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1572 @Override
1573 public void onReceive(Context context, Intent intent) {
1574 // Try creating lockdown tracker, since user present usually means
1575 // unlocked keystore.
1576 if (updateLockdownVpn()) {
1577 mContext.unregisterReceiver(this);
1578 }
1579 }
1580 };
1581
Wink Savilled747cbc2013-08-07 16:22:47 -07001582 /** @hide */
1583 @Override
1584 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1585 enforceConnectivityInternalPermission();
1586 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001587// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001588 }
1589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001591 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001592 *
1593 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001594 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001595 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001596 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1597 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001598
1599 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001600 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001601
Robert Greenwalt7b816022014-04-18 15:25:25 -07001602 if (networkAgent.networkCapabilities.hasTransport(
1603 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001604 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1605 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001606 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001607 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001608 } else if (networkAgent.networkCapabilities.hasTransport(
1609 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001610 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1611 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07001612 0);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001613 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001614 } else {
1615 // do not track any other networks
1616 timeout = 0;
1617 }
1618
Robert Greenwalt7b816022014-04-18 15:25:25 -07001619 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001620 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001621 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001622 } catch (Exception e) {
1623 // You shall not crash!
1624 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001625 }
1626 }
1627 }
1628
1629 /**
1630 * Remove data activity tracking when network disconnects.
1631 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001632 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1633 final String iface = networkAgent.linkProperties.getInterfaceName();
1634 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001635
Robert Greenwalt7b816022014-04-18 15:25:25 -07001636 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1637 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001638 try {
1639 // the call fails silently if no idletimer setup for this interface
1640 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001641 } catch (Exception e) {
1642 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001643 }
1644 }
1645 }
1646
1647 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001648 * Reads the network specific MTU size from reources.
1649 * and set it on it's iface.
1650 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001651 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1652 final String iface = newLp.getInterfaceName();
1653 final int mtu = newLp.getMtu();
1654 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1655 if (VDBG) log("identical MTU - not setting");
1656 return;
1657 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001658
Robert Greenwalt43074032014-08-15 17:53:05 -07001659 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001660 loge("Unexpected mtu value: " + mtu + ", " + iface);
1661 return;
1662 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001663
w1997615afd812014-08-05 15:18:11 -07001664 // Cannot set MTU without interface name
1665 if (TextUtils.isEmpty(iface)) {
1666 loge("Setting MTU size with null iface.");
1667 return;
1668 }
1669
Robert Greenwalt7b816022014-04-18 15:25:25 -07001670 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001671 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001672 mNetd.setMtu(iface, mtu);
1673 } catch (Exception e) {
1674 Slog.e(TAG, "exception in setMtu()" + e);
1675 }
1676 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001677
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001678 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Irfan Sheriffd649c122010-06-09 15:39:36 -07001679
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001680 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1681 if (isDefaultNetwork(nai) == false) {
1682 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001683 }
1684
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001685 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1686 String[] values = null;
1687 if (tcpBufferSizes != null) {
1688 values = tcpBufferSizes.split(",");
1689 }
1690
1691 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001692 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001693 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1694 values = tcpBufferSizes.split(",");
1695 }
1696
1697 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1698
1699 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001700 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001701
1702 final String prefix = "/sys/kernel/ipv4/tcp_";
1703 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1704 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1705 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1706 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1707 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1708 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1709 mCurrentTcpBufferSizes = tcpBufferSizes;
1710 } catch (IOException e) {
1711 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001712 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001713
1714 final String defaultRwndKey = "net.tcp.default_init_rwnd";
1715 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1716 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1717 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1718 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1719 if (rwndValue != 0) {
1720 SystemProperties.set(sysctlKey, rwndValue.toString());
1721 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001722 }
1723
Mattias Falk8b47b362011-08-23 14:15:13 +02001724 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001725 /*
1726 * Tell the VMs to toss their DNS caches
1727 */
1728 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1729 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001730 /*
1731 * Connectivity events can happen before boot has completed ...
1732 */
1733 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001734 final long ident = Binder.clearCallingIdentity();
1735 try {
1736 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1737 } finally {
1738 Binder.restoreCallingIdentity(ident);
1739 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001740 }
1741
Robert Greenwalt562cc542014-05-15 18:07:26 -07001742 @Override
1743 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001744 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1745 NETWORK_RESTORE_DELAY_PROP_NAME);
1746 if(restoreDefaultNetworkDelayStr != null &&
1747 restoreDefaultNetworkDelayStr.length() != 0) {
1748 try {
1749 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1750 } catch (NumberFormatException e) {
1751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001753 // if the system property isn't set, use the value for the apn type
1754 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1755
1756 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1757 (mNetConfigs[networkType] != null)) {
1758 ret = mNetConfigs[networkType].restoreTime;
1759 }
1760 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 }
1762
1763 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001764 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1765 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001766 if (mContext.checkCallingOrSelfPermission(
1767 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001769 pw.println("Permission Denial: can't dump ConnectivityService " +
1770 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1771 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 return;
1773 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001774
Robert Greenwalta67be032014-05-16 15:49:14 -07001775 pw.println("NetworkFactories for:");
1776 pw.increaseIndent();
1777 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1778 pw.println(nfi.name);
1779 }
1780 pw.decreaseIndent();
1781 pw.println();
1782
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001783 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1784 pw.print("Active default network: ");
1785 if (defaultNai == null) {
1786 pw.println("none");
1787 } else {
1788 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001790 pw.println();
1791
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001792 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001793 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001794 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1795 pw.println(nai.toString());
1796 pw.increaseIndent();
1797 pw.println("Requests:");
1798 pw.increaseIndent();
1799 for (int i = 0; i < nai.networkRequests.size(); i++) {
1800 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001801 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001802 pw.decreaseIndent();
1803 pw.println("Lingered:");
1804 pw.increaseIndent();
1805 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1806 pw.decreaseIndent();
1807 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001808 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001809 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001810 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001811
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001812 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001813 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001814 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1815 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001816 }
1817 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001818 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001819
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001820 pw.println("mLegacyTypeTracker:");
1821 pw.increaseIndent();
1822 mLegacyTypeTracker.dump(pw);
1823 pw.decreaseIndent();
1824 pw.println();
1825
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001826 synchronized (this) {
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001827 pw.println("NetworkTransitionWakeLock is currently " +
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001828 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1829 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1830 }
1831 pw.println();
1832
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001833 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001834
1835 if (mInetLog != null) {
1836 pw.println();
1837 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001838 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001839 for(int i = 0; i < mInetLog.size(); i++) {
1840 pw.println(mInetLog.get(i));
1841 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001842 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 }
1845
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001846 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001847 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001848 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001849 if (officialNai != null && officialNai.equals(nai)) return true;
1850 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001851 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001852 " - " + nai);
1853 }
1854 return false;
1855 }
1856
Paul Jensenc8b9a742014-09-30 15:37:41 -04001857 private boolean isRequest(NetworkRequest request) {
1858 return mNetworkRequests.get(request).isRequest;
1859 }
1860
Robert Greenwalt42acef32009-08-12 16:08:25 -07001861 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001862 private class NetworkStateTrackerHandler extends Handler {
1863 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001864 super(looper);
1865 }
1866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 @Override
1868 public void handleMessage(Message msg) {
1869 NetworkInfo info;
1870 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001871 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001872 handleAsyncChannelHalfConnect(msg);
1873 break;
1874 }
1875 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1876 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1877 if (nai != null) nai.asyncChannel.disconnect();
1878 break;
1879 }
1880 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1881 handleAsyncChannelDisconnected(msg);
1882 break;
1883 }
1884 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1885 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1886 if (nai == null) {
1887 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1888 } else {
1889 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001890 }
1891 break;
1892 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001893 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1894 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1895 if (nai == null) {
1896 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1897 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001898 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001899 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001900 "; created=" + nai.created);
1901 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001902 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001903 synchronized (nai) {
1904 nai.linkProperties = (LinkProperties)msg.obj;
1905 }
Paul Jenseneec75412014-08-04 12:21:19 -04001906 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001907 }
1908 break;
1909 }
1910 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1911 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1912 if (nai == null) {
1913 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1914 break;
1915 }
1916 info = (NetworkInfo) msg.obj;
1917 updateNetworkInfo(nai, info);
1918 break;
1919 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001920 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1921 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1922 if (nai == null) {
1923 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1924 break;
1925 }
1926 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001927 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001928 break;
1929 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001930 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1931 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1932 if (nai == null) {
1933 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1934 break;
1935 }
1936 try {
1937 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001938 } catch (Exception e) {
1939 // Never crash!
1940 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001941 }
1942 break;
1943 }
1944 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1945 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1946 if (nai == null) {
1947 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1948 break;
1949 }
1950 try {
1951 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001952 } catch (Exception e) {
1953 // Never crash!
1954 loge("Exception in removeVpnUidRanges: " + e);
1955 }
1956 break;
1957 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001958 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1959 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1960 if (nai == null) {
1961 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1962 break;
1963 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001964 if (nai.created && !nai.networkMisc.explicitlySelected) {
1965 loge("ERROR: created network explicitly selected.");
1966 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001967 nai.networkMisc.explicitlySelected = true;
1968 break;
1969 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001970 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001971 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001972 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001973 boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001974 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001975 if (valid) {
1976 if (DBG) log("Validated " + nai.name());
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001977 if (!nai.everValidated) {
1978 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001979 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1980 ReapUnvalidatedNetworks.REAP);
1981 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001982 sendUpdatedScoreToFactories(nai);
1983 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001984 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001985 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001986 // Let the NetworkAgent know the state of its network
1987 nai.asyncChannel.sendMessage(
1988 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1989 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1990 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001991 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001992 break;
1993 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001994 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001995 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001996 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1997 handleLingerComplete(nai);
1998 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001999 break;
2000 }
Paul Jensen869868be2014-05-15 10:33:05 -04002001 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002002 if (msg.arg1 == 0) {
2003 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
2004 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002005 NetworkAgentInfo nai = null;
2006 synchronized (mNetworkForNetId) {
2007 nai = mNetworkForNetId.get(msg.arg2);
2008 }
2009 if (nai == null) {
2010 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2011 break;
2012 }
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002013 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
2014 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04002015 }
Paul Jensen869868be2014-05-15 10:33:05 -04002016 break;
2017 }
Wink Saville948282b2013-08-29 08:55:16 -07002018 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002020 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002021
Wink Savillec9acde92011-09-21 11:05:43 -07002022 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Saville67c38212013-09-05 12:02:25 -07002023 (state == NetworkInfo.State.DISCONNECTED) ||
2024 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillec9acde92011-09-21 11:05:43 -07002025 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002026 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002027 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029
Jeff Sharkey2528b502012-11-09 15:57:02 -08002030 EventLogTags.writeConnectivityStateChanged(
2031 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002032
Robert Greenwalt7b816022014-04-18 15:25:25 -07002033 if (info.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -07002034 /**
2035 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2036 * for now its an in between network, its a network that
2037 * is actually a default network but we don't want it to be
2038 * announced as such to keep background applications from
2039 * trying to use it. It turns out that some still try so we
2040 * take the additional step of clearing any default routes
2041 * to the link that may have incorrectly setup by the lower
2042 * levels.
2043 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002044 LinkProperties lp = getLinkPropertiesForType(info.getType());
Wink Saville948282b2013-08-29 08:55:16 -07002045 if (DBG) {
2046 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2047 }
2048
2049 // Clear any default routes setup by the radio so
2050 // any activity by applications trying to use this
2051 // connection will fail until the provisioning network
2052 // is enabled.
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002053 /*
Wink Saville948282b2013-08-29 08:55:16 -07002054 for (RouteInfo r : lp.getRoutes()) {
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07002055 removeRoute(lp, r, TO_DEFAULT_TABLE,
2056 mNetTrackers[info.getType()].getNetwork().netId);
Wink Saville948282b2013-08-29 08:55:16 -07002057 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002058 */
Robert Greenwalt511288a2009-12-07 11:33:18 -08002059 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt511288a2009-12-07 11:33:18 -08002060 } else if (state == NetworkInfo.State.SUSPENDED) {
Robert Greenwalt511288a2009-12-07 11:33:18 -08002061 } else if (state == NetworkInfo.State.CONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002062 // handleConnect(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002064 notifyLockdownVpn(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 break;
Wink Saville948282b2013-08-29 08:55:16 -07002066 }
2067 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002068 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002069 // TODO: Temporary allowing network configuration
2070 // change not resetting sockets.
2071 // @see bug/4455071
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002072 /*
Robert Greenwalt7b816022014-04-18 15:25:25 -07002073 handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()],
2074 false);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002075 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 break;
Wink Saville948282b2013-08-29 08:55:16 -07002077 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002078 }
2079 }
2080 }
2081
Paul Jensen0cc17322014-11-25 15:26:53 -05002082 // Cancel any lingering so the linger timeout doesn't teardown a network.
2083 // This should be called when a network begins satisfying a NetworkRequest.
2084 // Note: depending on what state the NetworkMonitor is in (e.g.,
2085 // if it's awaiting captive portal login, or if validation failed), this
2086 // may trigger a re-evaluation of the network.
2087 private void unlinger(NetworkAgentInfo nai) {
2088 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002089 // If network has never been validated, it cannot have been lingered, so don't bother
2090 // needlessly triggering a re-evaluation.
2091 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002092 nai.networkLingered.clear();
2093 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2094 }
2095
Robert Greenwalt7b816022014-04-18 15:25:25 -07002096 private void handleAsyncChannelHalfConnect(Message msg) {
2097 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002098 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002099 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2100 if (VDBG) log("NetworkFactory connected");
2101 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002102 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002103 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002104 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002105 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002106 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002107 }
2108 } else {
2109 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002110 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002111 }
2112 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2113 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2114 if (VDBG) log("NetworkAgent connected");
2115 // A network agent has requested a connection. Establish the connection.
2116 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2117 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2118 } else {
2119 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002120 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002121 if (nai != null) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002122 synchronized (mNetworkForNetId) {
2123 mNetworkForNetId.remove(nai.network.netId);
2124 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002125 // Just in case.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07002126 mLegacyTypeTracker.remove(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002127 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002128 }
2129 }
2130 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002131
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 private void handleAsyncChannelDisconnected(Message msg) {
2133 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2134 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002135 if (DBG) {
2136 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2137 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002138 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002139 if (nai.created) {
2140 // Tell netd to clean up the configuration for this network
2141 // (routing rules, DNS, etc).
2142 try {
2143 mNetd.removeNetwork(nai.network.netId);
2144 } catch (Exception e) {
2145 loge("Exception removing network: " + e);
2146 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002147 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002148 // TODO - if we move the logic to the network agent (have them disconnect
2149 // because they lost all their requests or because their score isn't good)
2150 // then they would disconnect organically, report their new state and then
2151 // disconnect the channel.
2152 if (nai.networkInfo.isConnected()) {
2153 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2154 null, null);
2155 }
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002156 if (isDefaultNetwork(nai)) {
2157 mDefaultInetConditionPublished = 0;
2158 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002159 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002160 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002161 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002162 mNetworkAgentInfos.remove(msg.replyTo);
2163 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07002164 mLegacyTypeTracker.remove(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002165 synchronized (mNetworkForNetId) {
2166 mNetworkForNetId.remove(nai.network.netId);
2167 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002168 // Since we've lost the network, go through all the requests that
2169 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002170 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002171 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002172 for (int i = 0; i < nai.networkRequests.size(); i++) {
2173 NetworkRequest request = nai.networkRequests.valueAt(i);
2174 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2175 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002176 if (DBG) {
2177 log("Checking for replacement network to handle request " + request );
2178 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002179 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002180 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002181 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002182 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2183 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002184 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002185 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002186 alternative = existing;
2187 }
2188 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002189 if (alternative != null) {
2190 if (DBG) log(" found replacement in " + alternative.name());
2191 if (!toActivate.contains(alternative)) {
2192 toActivate.add(alternative);
2193 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002194 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002195 }
2196 }
2197 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2198 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002199 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002200 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002201 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002202 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002203 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002204 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2205 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002206 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002207 }
2208 }
2209
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002210 // If this method proves to be too slow then we can maintain a separate
2211 // pendingIntent => NetworkRequestInfo map.
2212 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2213 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2214 Intent intent = pendingIntent.getIntent();
2215 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2216 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2217 if (existingPendingIntent != null &&
2218 existingPendingIntent.getIntent().filterEquals(intent)) {
2219 return entry.getValue();
2220 }
2221 }
2222 return null;
2223 }
2224
2225 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2226 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2227
2228 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2229 if (existingRequest != null) { // remove the existing request.
2230 if (DBG) log("Replacing " + existingRequest.request + " with "
2231 + nri.request + " because their intents matched.");
2232 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2233 }
2234 handleRegisterNetworkRequest(msg);
2235 }
2236
Robert Greenwalt9258c642014-03-26 16:47:06 -07002237 private void handleRegisterNetworkRequest(Message msg) {
2238 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002239
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002240 mNetworkRequests.put(nri.request, nri);
2241
Paul Jensen0cc17322014-11-25 15:26:53 -05002242 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2243
Robert Greenwalt9258c642014-03-26 16:47:06 -07002244 // Check for the best currently alive network that satisfies this request
2245 NetworkAgentInfo bestNetwork = null;
2246 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002247 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002248 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002249 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002250 if (!nri.isRequest) {
2251 // Not setting bestNetwork here as a listening NetworkRequest may be
2252 // satisfied by multiple Networks. Instead the request is added to
2253 // each satisfying Network and notified about each.
2254 network.addRequest(nri.request);
2255 notifyNetworkCallback(network, nri);
2256 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002257 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002258 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002259 }
2260 }
2261 }
2262 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002263 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002264 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002265 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002266 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002267 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002268 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002269 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2270 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002271 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002272
Lorenzo Colittia793a672014-07-31 23:20:17 +09002273 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002274 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002275 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002276 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002277 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002278 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002279 }
2280 }
2281 }
2282
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002283 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2284 int callingUid) {
2285 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2286 if (nri != null) {
2287 handleReleaseNetworkRequest(nri.request, callingUid);
2288 }
2289 }
2290
Paul Jensen99364842014-12-09 11:43:45 -05002291 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2292 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2293 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2294 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2295 private boolean unneeded(NetworkAgentInfo nai) {
2296 if (!nai.created || nai.isVPN()) return false;
2297 boolean unneeded = true;
2298 if (nai.everValidated) {
2299 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2300 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2301 try {
2302 if (isRequest(nr)) unneeded = false;
2303 } catch (Exception e) {
2304 loge("Request " + nr + " not found in mNetworkRequests.");
2305 loge(" it came from request list of " + nai.name());
2306 }
2307 }
2308 } else {
2309 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2310 // If this Network is already the highest scoring Network for a request, or if
2311 // there is hope for it to become one if it validated, then it is needed.
2312 if (nri.isRequest && nai.satisfies(nri.request) &&
2313 (nai.networkRequests.get(nri.request.requestId) != null ||
2314 // Note that this catches two important cases:
2315 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2316 // is currently satisfying the request. This is desirable when
2317 // cellular ends up validating but WiFi does not.
2318 // 2. Unvalidated WiFi will not be reaped when validated cellular
2319 // is currently satsifying the request. This is desirable when
2320 // WiFi ends up validating and out scoring cellular.
2321 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2322 nai.getCurrentScoreAsValidated())) {
2323 unneeded = false;
2324 break;
2325 }
2326 }
2327 }
2328 return unneeded;
2329 }
2330
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002331 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2332 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002333 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002334 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002335 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2336 return;
2337 }
2338 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002339 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002340 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002341 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002342 // Find all networks that are satisfying this request and remove the request
2343 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002344 // TODO - it's my understanding that for a request there is only a single
2345 // network satisfying it, so this loop is wasteful
2346 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002347 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2348 if (nai.networkRequests.get(nri.request.requestId) != null) {
2349 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002350 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002351 log(" Removing from current network " + nai.name() +
2352 ", leaving " + nai.networkRequests.size() +
2353 " requests.");
2354 }
Paul Jensen99364842014-12-09 11:43:45 -05002355 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002356 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002357 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002358 } else {
2359 // suspect there should only be one pass through here
2360 // but if any were kept do the check below
2361 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002362 }
2363 }
2364 }
2365
Robert Greenwalt51481852015-01-08 14:43:31 -08002366 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2367 if (nai != null) {
2368 mNetworkForRequestId.remove(nri.request.requestId);
2369 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002370 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002371 // that a network connected to serve it, even though the network was already
2372 // connected. Now that this request has gone away, we might have to pretend
2373 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002374 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002375 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2376 boolean doRemove = true;
2377 if (wasKept) {
2378 // check if any of the remaining requests for this network are for the
2379 // same legacy type - if so, don't remove the nai
2380 for (int i = 0; i < nai.networkRequests.size(); i++) {
2381 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2382 if (otherRequest.legacyType == nri.request.legacyType &&
2383 isRequest(otherRequest)) {
2384 if (DBG) log(" still have other legacy request - leaving");
2385 doRemove = false;
2386 }
2387 }
2388 }
2389
2390 if (doRemove) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002391 mLegacyTypeTracker.remove(nri.request.legacyType, nai);
2392 }
2393 }
2394
Robert Greenwalta67be032014-05-16 15:49:14 -07002395 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002396 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2397 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002398 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002399 } else {
2400 // listens don't have a singular affectedNetwork. Check all networks to see
2401 // if this listen request applies and remove it.
2402 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2403 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002404 }
2405 }
2406 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2407 }
2408 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002409
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002410 private class InternalHandler extends Handler {
2411 public InternalHandler(Looper looper) {
2412 super(looper);
2413 }
2414
2415 @Override
2416 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002417 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002418 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002419 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002420 String causedBy = null;
2421 synchronized (ConnectivityService.this) {
2422 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2423 mNetTransitionWakeLock.isHeld()) {
2424 mNetTransitionWakeLock.release();
2425 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002426 } else {
2427 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002428 }
2429 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002430 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2431 log("Failed to find a new network - expiring NetTransition Wakelock");
2432 } else {
2433 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2434 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002435 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002436 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002437 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002438 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002439 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002440 break;
2441 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002442 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002443 boolean met = (msg.arg1 == ENABLED);
2444 handleSetDependencyMet(msg.arg2, met);
2445 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002446 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002447 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002448 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002449 sendStickyBroadcast(intent);
2450 break;
2451 }
Wink Savilleab9321d2013-06-29 21:10:57 -07002452 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2453 int tag = mEnableFailFastMobileDataTag.get();
2454 if (msg.arg1 == tag) {
2455 MobileDataStateTracker mobileDst =
2456 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2457 if (mobileDst != null) {
2458 mobileDst.setEnableFailFastMobileData(msg.arg2);
2459 }
2460 } else {
2461 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2462 + " != tag:" + tag);
2463 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002464 break;
Wink Savilleab9321d2013-06-29 21:10:57 -07002465 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002466 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002467 handleNetworkSamplingTimeout();
2468 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002469 }
Jason Monkdecd2952013-10-10 14:02:51 -04002470 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002471 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002472 break;
2473 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002474 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002475 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2476 break;
2477 }
2478 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2479 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002480 break;
2481 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002482 case EVENT_REGISTER_NETWORK_AGENT: {
2483 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2484 break;
2485 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002486 case EVENT_REGISTER_NETWORK_REQUEST:
2487 case EVENT_REGISTER_NETWORK_LISTENER: {
2488 handleRegisterNetworkRequest(msg);
2489 break;
2490 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002491 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2492 handleRegisterNetworkRequestWithIntent(msg);
2493 break;
2494 }
2495 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2496 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2497 break;
2498 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002499 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002500 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002501 break;
2502 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002503 case EVENT_SYSTEM_READY: {
2504 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2505 nai.networkMonitor.systemReady = true;
2506 }
2507 break;
2508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 }
2510 }
2511 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002512
2513 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002514 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002515 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002516 if (isTetheringSupported()) {
2517 return mTethering.tether(iface);
2518 } else {
2519 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2520 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002521 }
2522
2523 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002524 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002525 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002526
2527 if (isTetheringSupported()) {
2528 return mTethering.untether(iface);
2529 } else {
2530 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2531 }
2532 }
2533
2534 // javadoc from interface
2535 public int getLastTetherError(String iface) {
2536 enforceTetherAccessPermission();
2537
2538 if (isTetheringSupported()) {
2539 return mTethering.getLastTetherError(iface);
2540 } else {
2541 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2542 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002543 }
2544
2545 // TODO - proper iface API for selection by property, inspection, etc
2546 public String[] getTetherableUsbRegexs() {
2547 enforceTetherAccessPermission();
2548 if (isTetheringSupported()) {
2549 return mTethering.getTetherableUsbRegexs();
2550 } else {
2551 return new String[0];
2552 }
2553 }
2554
2555 public String[] getTetherableWifiRegexs() {
2556 enforceTetherAccessPermission();
2557 if (isTetheringSupported()) {
2558 return mTethering.getTetherableWifiRegexs();
2559 } else {
2560 return new String[0];
2561 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002562 }
2563
Danica Chang6fdd0c62010-08-11 14:54:43 -07002564 public String[] getTetherableBluetoothRegexs() {
2565 enforceTetherAccessPermission();
2566 if (isTetheringSupported()) {
2567 return mTethering.getTetherableBluetoothRegexs();
2568 } else {
2569 return new String[0];
2570 }
2571 }
2572
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002573 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002574 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002575 if (isTetheringSupported()) {
2576 return mTethering.setUsbTethering(enable);
2577 } else {
2578 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2579 }
2580 }
2581
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002582 // TODO - move iface listing, queries, etc to new module
2583 // javadoc from interface
2584 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002585 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002586 return mTethering.getTetherableIfaces();
2587 }
2588
2589 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002590 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002591 return mTethering.getTetheredIfaces();
2592 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002593
Robert Greenwalt5a735062010-03-02 17:25:02 -08002594 public String[] getTetheringErroredIfaces() {
2595 enforceTetherAccessPermission();
2596 return mTethering.getErroredIfaces();
2597 }
2598
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002599 public String[] getTetheredDhcpRanges() {
2600 enforceConnectivityInternalPermission();
2601 return mTethering.getTetheredDhcpRanges();
2602 }
2603
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002604 // if ro.tether.denied = true we default to no tethering
2605 // gservices could set the secure setting to 1 though to enable it on a build where it
2606 // had previously been turned off.
2607 public boolean isTetheringSupported() {
2608 enforceTetherAccessPermission();
2609 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002610 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002611 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2612 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002613 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2614 mTethering.getTetherableWifiRegexs().length != 0 ||
2615 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2616 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002617 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002618
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002619 // Called when we lose the default network and have no replacement yet.
2620 // This will automatically be cleared after X seconds or a new default network
2621 // becomes CONNECTED, whichever happens first. The timer is started by the
2622 // first caller and not restarted by subsequent callers.
2623 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002624 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002625 synchronized (this) {
2626 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002627 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002628 mNetTransitionWakeLock.acquire();
2629 mNetTransitionWakeLockCausedBy = forWhom;
2630 }
2631 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002632 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002633 mNetTransitionWakeLockTimeout);
2634 return;
2635 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002636
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002637 // 100 percent is full good, 0 is full bad.
2638 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002639 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002640 if (nai == null) return;
2641 boolean isGood = percentage > 50;
2642 // Revalidate if the app report does not match our current validated state.
2643 if (isGood != nai.lastValidated) {
2644 // Make the message logged by reportBadNetwork below less confusing.
2645 if (DBG && isGood) log("reportInetCondition: type=" + networkType + " ok, revalidate");
2646 reportBadNetwork(nai.network);
2647 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002648 }
2649
Robert Greenwalt9258c642014-03-26 16:47:06 -07002650 public void reportBadNetwork(Network network) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002651 enforceAccessPermission();
2652 enforceInternetPermission();
2653
2654 if (network == null) return;
2655
2656 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002657 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002658 if (nai == null) return;
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002659 if (DBG) log("reportBadNetwork(" + nai.name() + ") by " + uid);
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002660 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002661 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2662 // which isn't meant to work on uncreated networks.
2663 if (!nai.created) return;
2664
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002665 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002666
2667 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2668 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002669 }
2670
Paul Jensene0bef712014-12-10 15:12:18 -05002671 public ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002672 // this information is already available as a world read/writable jvm property
2673 // so this API change wouldn't have a benifit. It also breaks the passing
2674 // of proxy info to all the JVMs.
2675 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002676 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002677 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002678 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2679 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002680 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002681 }
2682
Paul Jensene0bef712014-12-10 15:12:18 -05002683 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2684 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2685 // proxy is null then there is no proxy in place).
2686 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2687 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2688 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2689 proxy = null;
2690 }
2691 return proxy;
2692 }
2693
2694 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2695 // better for determining if a new proxy broadcast is necessary:
2696 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2697 // avoid unnecessary broadcasts.
2698 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2699 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2700 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2701 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2702 // all set.
2703 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2704 a = canonicalizeProxyInfo(a);
2705 b = canonicalizeProxyInfo(b);
2706 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2707 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2708 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2709 }
2710
Jason Monk207900c2014-04-25 15:00:09 -04002711 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002712 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002713
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002714 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002715 if (proxyProperties == mGlobalProxy) return;
2716 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2717 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2718
2719 String host = "";
2720 int port = 0;
2721 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002722 String pacFileUrl = "";
2723 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002724 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002725 if (!proxyProperties.isValid()) {
2726 if (DBG)
2727 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2728 return;
2729 }
Jason Monk207900c2014-04-25 15:00:09 -04002730 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002731 host = mGlobalProxy.getHost();
2732 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002733 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002734 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002735 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002736 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002737 } else {
2738 mGlobalProxy = null;
2739 }
2740 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002741 final long token = Binder.clearCallingIdentity();
2742 try {
2743 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2744 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2745 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2746 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002747 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002748 } finally {
2749 Binder.restoreCallingIdentity(token);
2750 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002751
Jason Monkcf0f97a2014-10-02 15:39:38 -04002752 if (mGlobalProxy == null) {
2753 proxyProperties = mDefaultProxy;
2754 }
2755 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002756 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002757 }
2758
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002759 private void loadGlobalProxy() {
2760 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002761 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2762 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2763 String exclList = Settings.Global.getString(res,
2764 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002765 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2766 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002767 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002768 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002769 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002770 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002771 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002772 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002773 if (!proxyProperties.isValid()) {
2774 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2775 return;
2776 }
2777
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002778 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002779 mGlobalProxy = proxyProperties;
2780 }
2781 }
2782 }
2783
Jason Monk207900c2014-04-25 15:00:09 -04002784 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002785 // this information is already available as a world read/writable jvm property
2786 // so this API change wouldn't have a benifit. It also breaks the passing
2787 // of proxy info to all the JVMs.
2788 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002789 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002790 return mGlobalProxy;
2791 }
2792 }
2793
Jason Monk207900c2014-04-25 15:00:09 -04002794 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002795 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002796 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002797 proxy = null;
2798 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002799 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002800 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002801 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002802 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002803 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2804 return;
2805 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002806
2807 // This call could be coming from the PacManager, containing the port of the local
2808 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2809 // global (to get the correct local port), and send a broadcast.
2810 // TODO: Switch PacManager to have its own message to send back rather than
2811 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002812 if ((mGlobalProxy != null) && (proxy != null)
2813 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002814 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2815 mGlobalProxy = proxy;
2816 sendProxyBroadcast(mGlobalProxy);
2817 return;
2818 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002819 mDefaultProxy = proxy;
2820
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002821 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002822 if (!mDefaultProxyDisabled) {
2823 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002824 }
2825 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002826 }
2827
Paul Jensene0bef712014-12-10 15:12:18 -05002828 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2829 // This method gets called when any network changes proxy, but the broadcast only ever contains
2830 // the default proxy (even if it hasn't changed).
2831 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2832 // world where an app might be bound to a non-default network.
2833 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2834 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2835 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2836
2837 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2838 sendProxyBroadcast(getDefaultProxy());
2839 }
2840 }
2841
Robert Greenwalt434203a2010-10-11 16:00:27 -07002842 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002843 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2844 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002845 if (!TextUtils.isEmpty(proxy)) {
2846 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002847 if (data.length == 0) {
2848 return;
2849 }
2850
Robert Greenwalt434203a2010-10-11 16:00:27 -07002851 String proxyHost = data[0];
2852 int proxyPort = 8080;
2853 if (data.length > 1) {
2854 try {
2855 proxyPort = Integer.parseInt(data[1]);
2856 } catch (NumberFormatException e) {
2857 return;
2858 }
2859 }
Jason Monk207900c2014-04-25 15:00:09 -04002860 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002861 setGlobalProxy(p);
2862 }
2863 }
2864
Jason Monk207900c2014-04-25 15:00:09 -04002865 private void sendProxyBroadcast(ProxyInfo proxy) {
2866 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002867 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002868 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002869 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002870 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2871 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002872 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002873 final long ident = Binder.clearCallingIdentity();
2874 try {
2875 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2876 } finally {
2877 Binder.restoreCallingIdentity(ident);
2878 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002879 }
2880
2881 private static class SettingsObserver extends ContentObserver {
2882 private int mWhat;
2883 private Handler mHandler;
2884 SettingsObserver(Handler handler, int what) {
2885 super(handler);
2886 mHandler = handler;
2887 mWhat = what;
2888 }
2889
2890 void observe(Context context) {
2891 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002892 resolver.registerContentObserver(Settings.Global.getUriFor(
2893 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002894 }
2895
2896 @Override
2897 public void onChange(boolean selfChange) {
2898 mHandler.obtainMessage(mWhat).sendToTarget();
2899 }
2900 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002901
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002902 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002903 Slog.d(TAG, s);
2904 }
2905
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002906 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002907 Slog.e(TAG, s);
2908 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002909
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002910 private static <T> T checkNotNull(T value, String message) {
2911 if (value == null) {
2912 throw new NullPointerException(message);
2913 }
2914 return value;
2915 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002916
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002917 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002918 * Prepare for a VPN application.
Jeff Davidson9a1da682014-11-11 13:52:58 -08002919 * Permissions are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002920 * @hide
2921 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002922 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002923 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002924 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002925 int user = UserHandle.getUserId(Binder.getCallingUid());
2926 synchronized(mVpns) {
2927 return mVpns.get(user).prepare(oldPackage, newPackage);
2928 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002929 }
2930
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002931 /**
Jeff Davidson05542602014-08-11 14:07:27 -07002932 * Set whether the current VPN package has the ability to launch VPNs without
Jeff Davidson9a1da682014-11-11 13:52:58 -08002933 * user intervention. This method is used by system-privileged apps.
2934 * Permissions are checked in Vpn class.
Jeff Davidson05542602014-08-11 14:07:27 -07002935 * @hide
2936 */
2937 @Override
2938 public void setVpnPackageAuthorization(boolean authorized) {
2939 int user = UserHandle.getUserId(Binder.getCallingUid());
2940 synchronized(mVpns) {
2941 mVpns.get(user).setPackageAuthorization(authorized);
2942 }
2943 }
2944
2945 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002946 * Configure a TUN interface and return its file descriptor. Parameters
2947 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002948 * and not available in ConnectivityManager. Permissions are checked in
2949 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002950 * @hide
2951 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002952 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002953 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002954 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002955 int user = UserHandle.getUserId(Binder.getCallingUid());
2956 synchronized(mVpns) {
2957 return mVpns.get(user).establish(config);
2958 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002959 }
2960
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002961 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07002962 * Start legacy VPN, controlling native daemons as needed. Creates a
2963 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002964 */
2965 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07002966 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002967 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07002968 final LinkProperties egress = getActiveLinkProperties();
2969 if (egress == null) {
2970 throw new IllegalStateException("Missing active network connection");
2971 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002972 int user = UserHandle.getUserId(Binder.getCallingUid());
2973 synchronized(mVpns) {
2974 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
2975 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002976 }
2977
2978 /**
2979 * Return the information of the ongoing legacy VPN. This method is used
2980 * by VpnSettings and not available in ConnectivityManager. Permissions
2981 * are checked in Vpn class.
2982 * @hide
2983 */
2984 @Override
2985 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002986 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002987 int user = UserHandle.getUserId(Binder.getCallingUid());
2988 synchronized(mVpns) {
2989 return mVpns.get(user).getLegacyVpnInfo();
2990 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002991 }
2992
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002993 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07002994 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
2995 * not available in ConnectivityManager.
2996 * Permissions are checked in Vpn class.
2997 * @hide
2998 */
2999 @Override
3000 public VpnConfig getVpnConfig() {
3001 int user = UserHandle.getUserId(Binder.getCallingUid());
3002 synchronized(mVpns) {
3003 return mVpns.get(user).getVpnConfig();
3004 }
3005 }
3006
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003007 @Override
3008 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003009 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3010 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3011 return false;
3012 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003013
3014 // Tear down existing lockdown if profile was removed
3015 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3016 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003017 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003018 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3019 return false;
3020 }
3021
3022 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3023 final VpnProfile profile = VpnProfile.decode(
3024 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003025 int user = UserHandle.getUserId(Binder.getCallingUid());
3026 synchronized(mVpns) {
3027 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3028 profile));
3029 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003030 } else {
3031 setLockdownTracker(null);
3032 }
3033
3034 return true;
3035 }
3036
3037 /**
3038 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3039 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3040 */
3041 private void setLockdownTracker(LockdownVpnTracker tracker) {
3042 // Shutdown any existing tracker
3043 final LockdownVpnTracker existing = mLockdownTracker;
3044 mLockdownTracker = null;
3045 if (existing != null) {
3046 existing.shutdown();
3047 }
3048
3049 try {
3050 if (tracker != null) {
3051 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003052 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003053 mLockdownTracker = tracker;
3054 mLockdownTracker.init();
3055 } else {
3056 mNetd.setFirewallEnabled(false);
3057 }
3058 } catch (RemoteException e) {
3059 // ignored; NMS lives inside system_server
3060 }
3061 }
3062
3063 private void throwIfLockdownEnabled() {
3064 if (mLockdownEnabled) {
3065 throw new IllegalStateException("Unavailable in lockdown mode");
3066 }
3067 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003068
3069 public void supplyMessenger(int networkType, Messenger messenger) {
3070 enforceConnectivityInternalPermission();
3071
3072 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3073 mNetTrackers[networkType].supplyMessenger(messenger);
3074 }
3075 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003076
3077 public int findConnectionTypeForIface(String iface) {
3078 enforceConnectivityInternalPermission();
3079
3080 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
Lorenzo Colitti1c3a35b2014-08-19 21:31:08 -07003081
3082 synchronized(mNetworkForNetId) {
3083 for (int i = 0; i < mNetworkForNetId.size(); i++) {
3084 NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
3085 LinkProperties lp = nai.linkProperties;
3086 if (lp != null && iface.equals(lp.getInterfaceName()) && nai.networkInfo != null) {
3087 return nai.networkInfo.getType();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003088 }
3089 }
3090 }
3091 return ConnectivityManager.TYPE_NONE;
3092 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003093
3094 /**
3095 * Have mobile data fail fast if enabled.
3096 *
3097 * @param enabled DctConstants.ENABLED/DISABLED
3098 */
3099 private void setEnableFailFastMobileData(int enabled) {
3100 int tag;
3101
3102 if (enabled == DctConstants.ENABLED) {
3103 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3104 } else {
3105 tag = mEnableFailFastMobileDataTag.get();
3106 }
3107 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3108 enabled));
3109 }
3110
3111 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003112 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003113 // TODO: Remove? Any reason to trigger a provisioning check?
3114 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003115 }
3116
3117 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3118 private volatile boolean mIsNotificationVisible = false;
3119
Paul Jensen89e0f092014-09-15 15:59:36 -04003120 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003121 if (DBG) {
3122 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003123 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003124 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003125 Intent intent = new Intent(action);
3126 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003127 // Concatenate the range of types onto the range of NetIDs.
3128 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003129 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003130 }
3131
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003132 /**
3133 * Show or hide network provisioning notificaitons.
3134 *
3135 * @param id an identifier that uniquely identifies this notification. This must match
3136 * between show and hide calls. We use the NetID value but for legacy callers
3137 * we concatenate the range of types with the range of NetIDs.
3138 */
3139 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003140 String extraInfo, PendingIntent intent) {
3141 if (DBG) {
3142 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3143 networkType + " extraInfo=" + extraInfo);
3144 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003145
3146 Resources r = Resources.getSystem();
3147 NotificationManager notificationManager = (NotificationManager) mContext
3148 .getSystemService(Context.NOTIFICATION_SERVICE);
3149
3150 if (visible) {
3151 CharSequence title;
3152 CharSequence details;
3153 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003154 Notification notification = new Notification();
3155 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003156 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003157 title = r.getString(R.string.wifi_available_sign_in, 0);
3158 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003159 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003160 icon = R.drawable.stat_notify_wifi_in_range;
3161 break;
3162 case ConnectivityManager.TYPE_MOBILE:
3163 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003164 title = r.getString(R.string.network_available_sign_in, 0);
3165 // TODO: Change this to pull from NetworkInfo once a printable
3166 // name has been added to it
3167 details = mTelephonyManager.getNetworkOperatorName();
3168 icon = R.drawable.stat_notify_rssi_in_range;
3169 break;
3170 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003171 title = r.getString(R.string.network_available_sign_in, 0);
3172 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003173 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003174 icon = R.drawable.stat_notify_rssi_in_range;
3175 break;
3176 }
3177
Wink Savilleab9321d2013-06-29 21:10:57 -07003178 notification.when = 0;
3179 notification.icon = icon;
3180 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003181 notification.tickerText = title;
Selim Cinek255dd042014-08-19 22:29:02 +02003182 notification.color = mContext.getResources().getColor(
3183 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003184 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003185 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003186
Wink Saville948282b2013-08-29 08:55:16 -07003187 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003188 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003189 } catch (NullPointerException npe) {
3190 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3191 npe.printStackTrace();
3192 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003193 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003194 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003195 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003196 } catch (NullPointerException npe) {
3197 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3198 npe.printStackTrace();
3199 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003200 }
Wink Saville948282b2013-08-29 08:55:16 -07003201 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003202 }
3203
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003204 /** Location to an updatable file listing carrier provisioning urls.
3205 * An example:
3206 *
3207 * <?xml version="1.0" encoding="utf-8"?>
3208 * <provisioningUrls>
3209 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3210 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3211 * </provisioningUrls>
3212 */
3213 private static final String PROVISIONING_URL_PATH =
3214 "/data/misc/radio/provisioning_urls.xml";
3215 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003216
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003217 /** XML tag for root element. */
3218 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3219 /** XML tag for individual url */
3220 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3221 /** XML tag for redirected url */
3222 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3223 /** XML attribute for mcc */
3224 private static final String ATTR_MCC = "mcc";
3225 /** XML attribute for mnc */
3226 private static final String ATTR_MNC = "mnc";
3227
3228 private static final int REDIRECTED_PROVISIONING = 1;
3229 private static final int PROVISIONING = 2;
3230
3231 private String getProvisioningUrlBaseFromFile(int type) {
3232 FileReader fileReader = null;
3233 XmlPullParser parser = null;
3234 Configuration config = mContext.getResources().getConfiguration();
3235 String tagType;
3236
3237 switch (type) {
3238 case PROVISIONING:
3239 tagType = TAG_PROVISIONING_URL;
3240 break;
3241 case REDIRECTED_PROVISIONING:
3242 tagType = TAG_REDIRECTED_URL;
3243 break;
3244 default:
3245 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3246 type);
3247 }
3248
3249 try {
3250 fileReader = new FileReader(mProvisioningUrlFile);
3251 parser = Xml.newPullParser();
3252 parser.setInput(fileReader);
3253 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3254
3255 while (true) {
3256 XmlUtils.nextElement(parser);
3257
3258 String element = parser.getName();
3259 if (element == null) break;
3260
3261 if (element.equals(tagType)) {
3262 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3263 try {
3264 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3265 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3266 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3267 parser.next();
3268 if (parser.getEventType() == XmlPullParser.TEXT) {
3269 return parser.getText();
3270 }
3271 }
3272 }
3273 } catch (NumberFormatException e) {
3274 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3275 }
3276 }
3277 }
3278 return null;
3279 } catch (FileNotFoundException e) {
3280 loge("Carrier Provisioning Urls file not found");
3281 } catch (XmlPullParserException e) {
3282 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3283 } catch (IOException e) {
3284 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3285 } finally {
3286 if (fileReader != null) {
3287 try {
3288 fileReader.close();
3289 } catch (IOException e) {}
3290 }
3291 }
3292 return null;
3293 }
3294
Wink Saville42d4f082013-07-20 20:31:59 -07003295 @Override
3296 public String getMobileRedirectedProvisioningUrl() {
3297 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003298 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3299 if (TextUtils.isEmpty(url)) {
3300 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3301 }
3302 return url;
3303 }
3304
Wink Saville42d4f082013-07-20 20:31:59 -07003305 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003306 public String getMobileProvisioningUrl() {
3307 enforceConnectivityInternalPermission();
3308 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3309 if (TextUtils.isEmpty(url)) {
3310 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003311 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003312 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003313 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003314 }
Wink Saville8cf35602013-07-10 23:00:07 -07003315 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003316 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003317 String phoneNumber = mTelephonyManager.getLine1Number();
3318 if (TextUtils.isEmpty(phoneNumber)) {
3319 phoneNumber = "0000000000";
3320 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003321 url = String.format(url,
3322 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3323 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003324 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003325 }
3326
Wink Savilleab9321d2013-06-29 21:10:57 -07003327 return url;
3328 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003329
Wink Saville948282b2013-08-29 08:55:16 -07003330 @Override
3331 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003332 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003333 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003334 final long ident = Binder.clearCallingIdentity();
3335 try {
3336 setProvNotificationVisible(visible, networkType, action);
3337 } finally {
3338 Binder.restoreCallingIdentity(ident);
3339 }
Wink Saville948282b2013-08-29 08:55:16 -07003340 }
Wink Saville7788c612013-08-29 14:57:08 -07003341
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003342 @Override
3343 public void setAirplaneMode(boolean enable) {
3344 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003345 final long ident = Binder.clearCallingIdentity();
3346 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003347 final ContentResolver cr = mContext.getContentResolver();
3348 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3349 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3350 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003351 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003352 } finally {
3353 Binder.restoreCallingIdentity(ident);
3354 }
3355 }
3356
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003357 private void onUserStart(int userId) {
3358 synchronized(mVpns) {
3359 Vpn userVpn = mVpns.get(userId);
3360 if (userVpn != null) {
3361 loge("Starting user already has a VPN");
3362 return;
3363 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04003364 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, this, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003365 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003366 }
3367 }
3368
3369 private void onUserStop(int userId) {
3370 synchronized(mVpns) {
3371 Vpn userVpn = mVpns.get(userId);
3372 if (userVpn == null) {
3373 loge("Stopping user has no VPN");
3374 return;
3375 }
3376 mVpns.delete(userId);
3377 }
3378 }
3379
3380 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3381 @Override
3382 public void onReceive(Context context, Intent intent) {
3383 final String action = intent.getAction();
3384 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3385 if (userId == UserHandle.USER_NULL) return;
3386
3387 if (Intent.ACTION_USER_STARTING.equals(action)) {
3388 onUserStart(userId);
3389 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3390 onUserStop(userId);
3391 }
3392 }
3393 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003394
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003395 /* Infrastructure for network sampling */
3396
3397 private void handleNetworkSamplingTimeout() {
3398
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003399 if (SAMPLE_DBG) log("Sampling interval elapsed, updating statistics ..");
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003400
3401 // initialize list of interfaces ..
3402 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
3403 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
3404 for (NetworkStateTracker tracker : mNetTrackers) {
3405 if (tracker != null) {
3406 String ifaceName = tracker.getNetworkInterfaceName();
3407 if (ifaceName != null) {
3408 mapIfaceToSample.put(ifaceName, null);
3409 }
3410 }
3411 }
3412
3413 // Read samples for all interfaces
3414 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
3415
3416 // process samples for all networks
3417 for (NetworkStateTracker tracker : mNetTrackers) {
3418 if (tracker != null) {
3419 String ifaceName = tracker.getNetworkInterfaceName();
3420 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
3421 if (ss != null) {
3422 // end the previous sampling cycle
3423 tracker.stopSampling(ss);
3424 // start a new sampling cycle ..
3425 tracker.startSampling(ss);
3426 }
3427 }
3428 }
3429
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003430 if (SAMPLE_DBG) log("Done.");
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003431
3432 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
3433 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
3434 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
3435
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003436 if (SAMPLE_DBG) {
3437 log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
3438 }
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003439
3440 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
3441 }
3442
Aaron Whytef5e67472014-07-10 14:05:35 -07003443 /**
3444 * Sets a network sampling alarm.
3445 */
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003446 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
3447 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
Aaron Whytef5e67472014-07-10 14:05:35 -07003448 int alarmType;
3449 if (Resources.getSystem().getBoolean(
3450 R.bool.config_networkSamplingWakesDevice)) {
3451 alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
3452 } else {
3453 alarmType = AlarmManager.ELAPSED_REALTIME;
3454 }
3455 mAlarmManager.set(alarmType, wakeupTime, intent);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003456 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003457
Robert Greenwalta67be032014-05-16 15:49:14 -07003458 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3459 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003460 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3461 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003462
Robert Greenwalta67be032014-05-16 15:49:14 -07003463 private static class NetworkFactoryInfo {
3464 public final String name;
3465 public final Messenger messenger;
3466 public final AsyncChannel asyncChannel;
3467
3468 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3469 this.name = name;
3470 this.messenger = messenger;
3471 this.asyncChannel = asyncChannel;
3472 }
3473 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003474
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003475 /**
3476 * Tracks info about the requester.
3477 * Also used to notice when the calling process dies so we can self-expire
3478 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003479 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3480 static final boolean REQUEST = true;
3481 static final boolean LISTEN = false;
3482
3483 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003484 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003485 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003486 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003487 final int mPid;
3488 final int mUid;
3489 final Messenger messenger;
3490 final boolean isRequest;
3491
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003492 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3493 request = r;
3494 mPendingIntent = pi;
3495 messenger = null;
3496 mBinder = null;
3497 mPid = getCallingPid();
3498 mUid = getCallingUid();
3499 this.isRequest = isRequest;
3500 }
3501
Robert Greenwalt9258c642014-03-26 16:47:06 -07003502 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3503 super();
3504 messenger = m;
3505 request = r;
3506 mBinder = binder;
3507 mPid = getCallingPid();
3508 mUid = getCallingUid();
3509 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003510 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003511
3512 try {
3513 mBinder.linkToDeath(this, 0);
3514 } catch (RemoteException e) {
3515 binderDied();
3516 }
3517 }
3518
3519 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003520 if (mBinder != null) {
3521 mBinder.unlinkToDeath(this, 0);
3522 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003523 }
3524
3525 public void binderDied() {
3526 log("ConnectivityService NetworkRequestInfo binderDied(" +
3527 request + ", " + mBinder + ")");
3528 releaseNetworkRequest(request);
3529 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003530
3531 public String toString() {
3532 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003533 mPid + " for " + request +
3534 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003535 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003536 }
3537
3538 @Override
3539 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003540 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003541 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003542 enforceNetworkRequestPermissions(networkCapabilities);
3543 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003544
Robert Greenwalt6078b502014-06-11 16:05:07 -07003545 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003546 throw new IllegalArgumentException("Bad timeout specified");
3547 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003548
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003549 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3550 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003551 if (DBG) log("requestNetwork for " + networkRequest);
3552 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3553 NetworkRequestInfo.REQUEST);
3554
3555 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003556 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003557 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003558 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003559 }
3560 return networkRequest;
3561 }
3562
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003563 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3564 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
3565 == false) {
3566 enforceConnectivityInternalPermission();
3567 } else {
3568 enforceChangePermission();
3569 }
3570 }
3571
3572 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3573 // if UID is restricted, don't allow them to bring up metered APNs
3574 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
3575 == false) {
3576 final int uidRules;
3577 final int uid = Binder.getCallingUid();
3578 synchronized(mRulesLock) {
3579 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3580 }
3581 if ((uidRules & RULE_REJECT_METERED) != 0) {
3582 // we could silently fail or we can filter the available nets to only give
3583 // them those they have access to. Chose the more useful
3584 networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3585 }
3586 }
3587 }
3588
Robert Greenwalt9258c642014-03-26 16:47:06 -07003589 @Override
3590 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3591 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003592 checkNotNull(operation, "PendingIntent cannot be null.");
3593 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3594 enforceNetworkRequestPermissions(networkCapabilities);
3595 enforceMeteredApnPolicy(networkCapabilities);
3596
3597 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3598 nextNetworkRequestId());
3599 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3600 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3601 NetworkRequestInfo.REQUEST);
3602 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3603 nri));
3604 return networkRequest;
3605 }
3606
Jeremy Joslin79294842014-12-03 17:15:28 -08003607 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3608 mHandler.sendMessageDelayed(
3609 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3610 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3611 }
3612
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003613 @Override
3614 public void releasePendingNetworkRequest(PendingIntent operation) {
3615 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3616 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003617 }
3618
3619 @Override
3620 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3621 Messenger messenger, IBinder binder) {
3622 enforceAccessPermission();
3623
3624 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003625 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003626 if (DBG) log("listenForNetwork for " + networkRequest);
3627 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3628 NetworkRequestInfo.LISTEN);
3629
3630 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3631 return networkRequest;
3632 }
3633
3634 @Override
3635 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3636 PendingIntent operation) {
3637 }
3638
3639 @Override
3640 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003641 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3642 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003643 }
3644
3645 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003646 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003647 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003648 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3649 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003650 }
3651
Robert Greenwalta67be032014-05-16 15:49:14 -07003652 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003653 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003654 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3655 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3656 }
3657
3658 @Override
3659 public void unregisterNetworkFactory(Messenger messenger) {
3660 enforceConnectivityInternalPermission();
3661 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3662 }
3663
3664 private void handleUnregisterNetworkFactory(Messenger messenger) {
3665 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3666 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003667 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003668 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003669 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003670 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003671 }
3672
Robert Greenwalt7b816022014-04-18 15:25:25 -07003673 /**
3674 * NetworkAgentInfo supporting a request by requestId.
3675 * These have already been vetted (their Capabilities satisfy the request)
3676 * and the are the highest scored network available.
3677 * the are keyed off the Requests requestId.
3678 */
3679 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3680 new SparseArray<NetworkAgentInfo>();
3681
Robert Greenwalt9258c642014-03-26 16:47:06 -07003682 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3683 new SparseArray<NetworkAgentInfo>();
3684
Robert Greenwalt7b816022014-04-18 15:25:25 -07003685 // NetworkAgentInfo keyed off its connecting messenger
3686 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
3687 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3688 new HashMap<Messenger, NetworkAgentInfo>();
3689
Paul Jensen2c311d62014-11-17 12:34:51 -05003690 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003691 private final NetworkRequest mDefaultRequest;
3692
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003693 private NetworkAgentInfo getDefaultNetwork() {
3694 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3695 }
3696
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003697 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003698 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003699 }
3700
Robert Greenwalt7b816022014-04-18 15:25:25 -07003701 public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
3702 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003703 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003704 enforceConnectivityInternalPermission();
3705
Paul Jensen2c311d62014-11-17 12:34:51 -05003706 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3707 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003708 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Robert Greenwalt7b816022014-04-18 15:25:25 -07003709 new NetworkInfo(networkInfo), new LinkProperties(linkProperties),
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003710 new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler,
Paul Jensen2c311d62014-11-17 12:34:51 -05003711 new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003712 synchronized (this) {
3713 nai.networkMonitor.systemReady = mSystemReady;
3714 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003715 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003716 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
3717 }
3718
3719 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3720 if (VDBG) log("Got NetworkAgent Messenger");
3721 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen60061a62014-08-05 14:13:48 -04003722 assignNextNetId(na);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003723 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3724 NetworkInfo networkInfo = na.networkInfo;
3725 na.networkInfo = null;
3726 updateNetworkInfo(na, networkInfo);
3727 }
3728
3729 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3730 LinkProperties newLp = networkAgent.linkProperties;
3731 int netId = networkAgent.network.netId;
3732
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003733 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3734 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003735 if (networkAgent.clatd != null) {
3736 networkAgent.clatd.fixupLinkProperties(oldLp);
3737 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003738
Paul Jensen992f2522014-04-28 10:33:11 -04003739 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003740 updateMtu(newLp, oldLp);
3741 // TODO - figure out what to do for clat
3742// for (LinkProperties lp : newLp.getStackedLinks()) {
3743// updateMtu(lp, null);
3744// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003745 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003746
3747 // TODO: deprecate and remove mDefaultDns when we can do so safely.
3748 // For now, use it only when the network has Internet access. http://b/18327075
3749 final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3750 NetworkCapabilities.NET_CAPABILITY_INTERNET);
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003751 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003752 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3753
Paul Jensen3b759822014-05-13 11:44:01 -04003754 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003755 if (isDefaultNetwork(networkAgent)) {
3756 handleApplyDefaultProxy(newLp.getHttpProxy());
3757 } else {
3758 updateProxy(newLp, oldLp, networkAgent);
3759 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003760 // TODO - move this check to cover the whole function
3761 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003762 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003763 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3764 }
Paul Jensen3b759822014-05-13 11:44:01 -04003765 }
3766
Lorenzo Colitti95439462014-10-09 13:44:48 +09003767 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3768 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3769 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003770
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003771 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003772 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3773 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003774 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003775 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003776 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003777 }
Paul Jensen992f2522014-04-28 10:33:11 -04003778
3779 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3780 CompareResult<String> interfaceDiff = new CompareResult<String>();
3781 if (oldLp != null) {
3782 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3783 } else if (newLp != null) {
3784 interfaceDiff.added = newLp.getAllInterfaceNames();
3785 }
3786 for (String iface : interfaceDiff.added) {
3787 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003788 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003789 mNetd.addInterfaceToNetwork(iface, netId);
3790 } catch (Exception e) {
3791 loge("Exception adding interface: " + e);
3792 }
3793 }
3794 for (String iface : interfaceDiff.removed) {
3795 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003796 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003797 mNetd.removeInterfaceFromNetwork(iface, netId);
3798 } catch (Exception e) {
3799 loge("Exception removing interface: " + e);
3800 }
3801 }
3802 }
3803
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003804 /**
3805 * Have netd update routes from oldLp to newLp.
3806 * @return true if routes changed between oldLp and newLp
3807 */
3808 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003809 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3810 if (oldLp != null) {
3811 routeDiff = oldLp.compareAllRoutes(newLp);
3812 } else if (newLp != null) {
3813 routeDiff.added = newLp.getAllRoutes();
3814 }
3815
3816 // add routes before removing old in case it helps with continuous connectivity
3817
3818 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3819 for (RouteInfo route : routeDiff.added) {
3820 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003821 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003822 try {
3823 mNetd.addRoute(netId, route);
3824 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003825 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3826 loge("Exception in addRoute for non-gateway: " + e);
3827 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003828 }
3829 }
3830 for (RouteInfo route : routeDiff.added) {
3831 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003832 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003833 try {
3834 mNetd.addRoute(netId, route);
3835 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003836 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3837 loge("Exception in addRoute for gateway: " + e);
3838 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003839 }
3840 }
3841
3842 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003843 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003844 try {
3845 mNetd.removeRoute(netId, route);
3846 } catch (Exception e) {
3847 loge("Exception in removeRoute: " + e);
3848 }
3849 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003850 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003851 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003852 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3853 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003854 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003855 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003856 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003857 dnses = new ArrayList();
3858 dnses.add(mDefaultDns);
3859 if (DBG) {
3860 loge("no dns provided for netId " + netId + ", so using defaults");
3861 }
3862 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003863 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003864 try {
3865 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3866 newLp.getDomains());
3867 } catch (Exception e) {
3868 loge("Exception in setDnsServersForNetwork: " + e);
3869 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003870 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3871 if (defaultNai != null && defaultNai.network.netId == netId) {
3872 setDefaultDnsSystemProperties(dnses);
3873 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003874 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003875 } else if (flush) {
3876 try {
3877 mNetd.flushNetworkDnsCache(netId);
3878 } catch (Exception e) {
3879 loge("Exception in flushNetworkDnsCache: " + e);
3880 }
3881 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003882 }
3883 }
3884
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003885 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3886 int last = 0;
3887 for (InetAddress dns : dnses) {
3888 ++last;
3889 String key = "net.dns" + last;
3890 String value = dns.getHostAddress();
3891 SystemProperties.set(key, value);
3892 }
3893 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3894 String key = "net.dns" + i;
3895 SystemProperties.set(key, "");
3896 }
3897 mNumDnsEntries = last;
3898 }
3899
Robert Greenwalt7b816022014-04-18 15:25:25 -07003900 private void updateCapabilities(NetworkAgentInfo networkAgent,
3901 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003902 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3903 synchronized (networkAgent) {
3904 networkAgent.networkCapabilities = networkCapabilities;
3905 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003906 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003907 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003908 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003909 }
3910
Paul Jensenc8b9a742014-09-30 15:37:41 -04003911 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3912 for (int i = 0; i < nai.networkRequests.size(); i++) {
3913 NetworkRequest nr = nai.networkRequests.valueAt(i);
3914 // Don't send listening requests to factories. b/17393458
3915 if (!isRequest(nr)) continue;
3916 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3917 }
3918 }
3919
Robert Greenwalt7b816022014-04-18 15:25:25 -07003920 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
3921 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07003922 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07003923 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
3924 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003925 }
3926 }
3927
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003928 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
3929 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08003930 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003931 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08003932 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
3933 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08003934 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003935 sendIntent(nri.mPendingIntent, intent);
3936 }
3937 // else not handled
3938 }
3939
3940 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
3941 mPendingIntentWakeLock.acquire();
3942 try {
3943 if (DBG) log("Sending " + pendingIntent);
3944 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
3945 } catch (PendingIntent.CanceledException e) {
3946 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
3947 mPendingIntentWakeLock.release();
3948 releasePendingNetworkRequest(pendingIntent);
3949 }
3950 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
3951 }
3952
3953 @Override
3954 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
3955 String resultData, Bundle resultExtras) {
3956 if (DBG) log("Finished sending " + pendingIntent);
3957 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08003958 // Release with a delay so the receiving client has an opportunity to put in its
3959 // own request.
3960 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003961 }
3962
Robert Greenwalt9258c642014-03-26 16:47:06 -07003963 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003964 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003965 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003966 Bundle bundle = new Bundle();
3967 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
3968 new NetworkRequest(nri.request));
3969 Message msg = Message.obtain();
3970 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
3971 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
3972 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
3973 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003974 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003975 case ConnectivityManager.CALLBACK_LOSING: {
3976 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
3977 break;
3978 }
3979 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
3980 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
3981 new NetworkCapabilities(networkAgent.networkCapabilities));
3982 break;
3983 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003984 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003985 bundle.putParcelable(LinkProperties.class.getSimpleName(),
3986 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003987 break;
3988 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003989 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003990 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003991 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003992 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003993 if (VDBG) {
3994 log("sending notification " + notifyTypeToName(notificationType) +
3995 " for " + nri.request);
3996 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003997 nri.messenger.send(msg);
3998 } catch (RemoteException e) {
3999 // may occur naturally in the race of binder death.
4000 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4001 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004002 }
4003
Paul Jensenc8b9a742014-09-30 15:37:41 -04004004 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4005 for (int i = 0; i < nai.networkRequests.size(); i++) {
4006 NetworkRequest nr = nai.networkRequests.valueAt(i);
4007 // Ignore listening requests.
4008 if (!isRequest(nr)) continue;
4009 loge("Dead network still had at least " + nr);
4010 break;
4011 }
4012 nai.asyncChannel.disconnect();
4013 }
4014
Robert Greenwalt7b816022014-04-18 15:25:25 -07004015 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4016 if (oldNetwork == null) {
4017 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4018 return;
4019 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004020 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4021 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004022 }
4023
Paul Jensen27b02b72014-07-14 12:03:33 -04004024 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004025 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004026 setupDataActivityTracking(newNetwork);
4027 try {
4028 mNetd.setDefaultNetId(newNetwork.network.netId);
4029 } catch (Exception e) {
4030 loge("Exception setting default network :" + e);
4031 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004032 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004033 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004034 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004035 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004036 }
4037
Paul Jensen2161a8e2014-09-11 11:00:39 -04004038 // Handles a network appearing or improving its score.
4039 //
4040 // - Evaluates all current NetworkRequests that can be
4041 // satisfied by newNetwork, and reassigns to newNetwork
4042 // any such requests for which newNetwork is the best.
4043 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004044 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004045 // needed. A network is needed if it is the best network for
4046 // one or more NetworkRequests, or if it is a VPN.
4047 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004048 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004049 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4050 //
4051 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4052 // networks that have no chance (i.e. even if validated)
4053 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004054 //
4055 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4056 // it does not remove NetworkRequests that other Networks could better satisfy.
4057 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4058 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4059 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004060 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004061 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004062 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004063 // torn down if unneeded.
4064 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4065 // performed to tear down unvalidated networks that have no chance (i.e. even if
4066 // validated) of becoming the highest scoring network.
4067 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4068 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004069 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004070 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004071 loge("ERROR: nascent network not validated.");
4072 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004073 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004074 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004075 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004076 if (DBG) log("rematching " + newNetwork.name());
4077 // Find and migrate to this Network any NetworkRequests for
4078 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004080 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004081 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004082 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4083 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004084 if (DBG) {
4085 log("Network " + newNetwork.name() + " was already satisfying" +
4086 " request " + nri.request.requestId + ". No change.");
4087 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004088 keep = true;
4089 continue;
4090 }
4091
4092 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004093 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004094 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004095 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004096 // This is not a request, it's a callback listener.
4097 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004098 newNetwork.addRequest(nri.request);
4099 continue;
4100 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004101
Robert Greenwalt7b816022014-04-18 15:25:25 -07004102 // next check if it's better than any current network we're using for
4103 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004104 if (VDBG) {
4105 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004106 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4107 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004108 }
4109 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004110 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004111 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004112 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004113 currentNetwork.networkRequests.remove(nri.request.requestId);
4114 currentNetwork.networkLingered.add(nri.request);
4115 affectedNetworks.add(currentNetwork);
4116 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004117 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004118 }
Paul Jensen573a0352015-01-08 10:49:34 -05004119 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004120 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004121 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004122 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004123 // Tell NetworkFactories about the new score, so they can stop
4124 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004125 // TODO - this could get expensive if we have alot of requests for this
4126 // network. Think about if there is a way to reduce this. Push
4127 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004128 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004129 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004130 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004131 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004132 }
4133 }
4134 }
4135 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004136 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004137 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004138 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004139 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4140 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4141 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004142 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004143 }
4144 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004145 if (keep) {
4146 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004147 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004148 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004149 synchronized (ConnectivityService.this) {
4150 // have a new default network, release the transition wakelock in
4151 // a second if it's held. The second pause is to allow apps
4152 // to reconnect over the new network
4153 if (mNetTransitionWakeLock.isHeld()) {
4154 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4155 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4156 mNetTransitionWakeLockSerialNumber, 0),
4157 1000);
4158 }
4159 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004160 }
4161
4162 // do this after the default net is switched, but
4163 // before LegacyTypeTracker sends legacy broadcasts
4164 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4165
4166 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004167 // Maintain the illusion: since the legacy API only
4168 // understands one network at a time, we must pretend
4169 // that the current default network disconnected before
4170 // the new one connected.
4171 if (oldDefaultNetwork != null) {
4172 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4173 oldDefaultNetwork);
4174 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004175 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004176 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4177 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004178 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004179
4180 // Notify battery stats service about this network, both the normal
4181 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004182 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004183 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004184 final IBatteryStats bs = BatteryStatsService.getService();
4185 final int type = newNetwork.networkInfo.getType();
4186
4187 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4188 bs.noteNetworkInterfaceType(baseIface, type);
4189 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4190 final String stackedIface = stacked.getInterfaceName();
4191 bs.noteNetworkInterfaceType(stackedIface, type);
4192 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4193 }
4194 } catch (RemoteException ignored) {
4195 }
4196
Robert Greenwalt152ed372014-12-17 17:19:53 -08004197 // This has to happen after the notifyNetworkCallbacks as that tickles each
4198 // ConnectivityManager instance so that legacy requests correctly bind dns
4199 // requests to this network. The legacy users are listening for this bcast
4200 // and will generally do a dns request so they can ensureRouteToHost and if
4201 // they do that before the callbacks happen they'll use the default network.
4202 //
4203 // TODO: Is there still a race here? We send the broadcast
4204 // after sending the callback, but if the app can receive the
4205 // broadcast before the callback, it might still break.
4206 //
4207 // This *does* introduce a race where if the user uses the new api
4208 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4209 // they may get old info. Reverse this after the old startUsing api is removed.
4210 // This is on top of the multiple intent sequencing referenced in the todo above.
4211 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4212 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4213 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4214 // legacy type tracker filters out repeat adds
4215 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4216 }
4217 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004218
4219 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4220 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4221 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4222 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4223 if (newNetwork.isVPN()) {
4224 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4225 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004226 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004227 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004228 // validated (and get evaluated against peers, one losing here), or get reaped (see
4229 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4230 // network. Networks that have been up for a while and are validated should be torn
4231 // down via the lingering process so communication on that network is given time to
4232 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004233 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004234 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004235 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004236 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4237 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004238 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004239 if (DBG) log("Reaping " + nai.name());
4240 teardownUnneededNetwork(nai);
4241 }
4242 }
4243 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004244 }
4245
Paul Jensen2161a8e2014-09-11 11:00:39 -04004246 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4247 // being disconnected.
4248 // If only one Network's score or capabilities have been modified since the last time
4249 // this function was called, pass this Network in via the "changed" arugment, otherwise
4250 // pass null.
4251 // If only one Network has been changed but its NetworkCapabilities have not changed,
4252 // pass in the Network's score (from getCurrentScore()) prior to the change via
4253 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4254 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4255 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4256 // to avoid the slowness. It is not simply enough to process just "changed", for
4257 // example in the case where "changed"'s score decreases and another network should begin
4258 // satifying a NetworkRequest that "changed" currently satisfies.
4259
4260 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4261 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4262 // rematchNetworkAndRequests() handles.
4263 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004264 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4265 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004266 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004267 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4268 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4269 NascentState.NOT_JUST_VALIDATED,
4270 // Only reap the last time through the loop. Reaping before all rematching
4271 // is complete could incorrectly teardown a network that hasn't yet been
4272 // rematched.
4273 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4274 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004275 }
4276 }
4277 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004278
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004279 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004280 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004281 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004282 // For now only update icons for default connection.
4283 // TODO: Update WiFi and cellular icons separately. b/17237507
4284 if (!isDefaultNetwork(nai)) return;
4285
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004286 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004287 // Don't repeat publish.
4288 if (newInetCondition == mDefaultInetConditionPublished) return;
4289
4290 mDefaultInetConditionPublished = newInetCondition;
4291 sendInetConditionBroadcast(nai.networkInfo);
4292 }
4293
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004294 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4295 if (mLockdownTracker != null) {
4296 if (nai != null && nai.isVPN()) {
4297 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4298 } else {
4299 mLockdownTracker.onNetworkInfoChanged();
4300 }
4301 }
4302 }
4303
Robert Greenwalt7b816022014-04-18 15:25:25 -07004304 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4305 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004306 NetworkInfo oldInfo = null;
4307 synchronized (networkAgent) {
4308 oldInfo = networkAgent.networkInfo;
4309 networkAgent.networkInfo = newInfo;
4310 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004311 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004312
4313 if (oldInfo != null && oldInfo.getState() == state) {
4314 if (VDBG) log("ignoring duplicate network state non-change");
4315 return;
4316 }
4317 if (DBG) {
4318 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4319 (oldInfo == null ? "null" : oldInfo.getState()) +
4320 " to " + state);
4321 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004322
Paul Jenseneec75412014-08-04 12:21:19 -04004323 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004324 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004325 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004326 if (networkAgent.isVPN()) {
4327 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004328 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4329 (networkAgent.networkMisc == null ||
4330 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004331 } else {
4332 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4333 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004334 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004335 loge("Error creating network " + networkAgent.network.netId + ": "
4336 + e.getMessage());
4337 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004338 }
Paul Jenseneec75412014-08-04 12:21:19 -04004339 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004340 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004341 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004342 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04004343 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004344 if (networkAgent.isVPN()) {
4345 // Temporarily disable the default proxy (not global).
4346 synchronized (mProxyLock) {
4347 if (!mDefaultProxyDisabled) {
4348 mDefaultProxyDisabled = true;
4349 if (mGlobalProxy == null && mDefaultProxy != null) {
4350 sendProxyBroadcast(null);
4351 }
4352 }
4353 }
4354 // TODO: support proxy per network.
4355 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004356 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004357 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4358 ReapUnvalidatedNetworks.REAP);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004359 } else if (state == NetworkInfo.State.DISCONNECTED ||
4360 state == NetworkInfo.State.SUSPENDED) {
4361 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004362 if (networkAgent.isVPN()) {
4363 synchronized (mProxyLock) {
4364 if (mDefaultProxyDisabled) {
4365 mDefaultProxyDisabled = false;
4366 if (mGlobalProxy == null && mDefaultProxy != null) {
4367 sendProxyBroadcast(mDefaultProxy);
4368 }
4369 }
4370 }
4371 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004372 }
4373 }
4374
Robert Greenwaltac96c522014-06-03 16:43:57 -07004375 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4376 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004377 if (score < 0) {
4378 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4379 "). Bumping score to min of 0");
4380 score = 0;
4381 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004382
Paul Jensen2161a8e2014-09-11 11:00:39 -04004383 final int oldScore = nai.getCurrentScore();
4384 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004385
Paul Jensen57a767f2014-11-19 13:01:46 -05004386 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004387
Paul Jensenc8b9a742014-09-30 15:37:41 -04004388 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004389 }
4390
Robert Greenwalt9258c642014-03-26 16:47:06 -07004391 // notify only this one new request of the current state
4392 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4393 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4394 // TODO - read state from monitor to decide what to send.
4395// if (nai.networkMonitor.isLingering()) {
4396// notifyType = NetworkCallbacks.LOSING;
4397// } else if (nai.networkMonitor.isEvaluating()) {
4398// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4399// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004400 if (nri.mPendingIntent == null) {
4401 callCallbackForRequest(nri, nai, notifyType);
4402 } else {
4403 sendPendingIntentForRequest(nri, nai, notifyType);
4404 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004405 }
4406
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004407 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004408 // The NetworkInfo we actually send out has no bearing on the real
4409 // state of affairs. For example, if the default connection is mobile,
4410 // and a request for HIPRI has just gone away, we need to pretend that
4411 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4412 // the state to DISCONNECTED, even though the network is of type MOBILE
4413 // and is still connected.
4414 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4415 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004416 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004417 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004418 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004419 } else {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004420 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004421 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4422 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4423 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4424 if (info.isFailover()) {
4425 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4426 nai.networkInfo.setFailover(false);
4427 }
4428 if (info.getReason() != null) {
4429 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4430 }
4431 if (info.getExtraInfo() != null) {
4432 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4433 }
4434 NetworkAgentInfo newDefaultAgent = null;
4435 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4436 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4437 if (newDefaultAgent != null) {
4438 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4439 newDefaultAgent.networkInfo);
4440 } else {
4441 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4442 }
4443 }
4444 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4445 mDefaultInetConditionPublished);
4446 final Intent immediateIntent = new Intent(intent);
4447 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
4448 sendStickyBroadcast(immediateIntent);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004449 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004450 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004451 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004452 }
4453 }
4454 }
4455
Robert Greenwalt7b816022014-04-18 15:25:25 -07004456 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004457 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004458 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004459 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4460 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4461 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004462 if (nri.mPendingIntent == null) {
4463 callCallbackForRequest(nri, networkAgent, notifyType);
4464 } else {
4465 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4466 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004467 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004468 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004469
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004470 private String notifyTypeToName(int notifyType) {
4471 switch (notifyType) {
4472 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4473 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4474 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4475 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4476 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4477 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4478 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4479 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4480 }
4481 return "UNKNOWN";
4482 }
4483
Jeff Sharkey69736342014-12-08 14:50:12 -08004484 /**
4485 * Notify other system services that set of active ifaces has changed.
4486 */
4487 private void notifyIfacesChanged() {
4488 try {
4489 mStatsService.forceUpdateIfaces();
4490 } catch (Exception ignored) {
4491 }
4492 }
4493
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004494 @Override
4495 public boolean addVpnAddress(String address, int prefixLength) {
4496 throwIfLockdownEnabled();
4497 int user = UserHandle.getUserId(Binder.getCallingUid());
4498 synchronized (mVpns) {
4499 return mVpns.get(user).addAddress(address, prefixLength);
4500 }
4501 }
4502
4503 @Override
4504 public boolean removeVpnAddress(String address, int prefixLength) {
4505 throwIfLockdownEnabled();
4506 int user = UserHandle.getUserId(Binder.getCallingUid());
4507 synchronized (mVpns) {
4508 return mVpns.get(user).removeAddress(address, prefixLength);
4509 }
4510 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004511
4512 @Override
4513 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4514 throwIfLockdownEnabled();
4515 int user = UserHandle.getUserId(Binder.getCallingUid());
4516 synchronized (mVpns) {
4517 return mVpns.get(user).setUnderlyingNetworks(networks);
4518 }
4519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520}