blob: 02a78dea33205109d4ebef9b1d8ba9c5b0ad8dca [file] [log] [blame]
The Android Open Source Project28527d22009-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 Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baib5da5752012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070023import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24import static android.net.ConnectivityManager.TYPE_DUMMY;
25import static android.net.ConnectivityManager.TYPE_ETHERNET;
26import static android.net.ConnectivityManager.TYPE_MOBILE;
27import static android.net.ConnectivityManager.TYPE_WIFI;
28import static android.net.ConnectivityManager.TYPE_WIMAX;
29import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070030import static android.net.ConnectivityManager.isNetworkTypeValid;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070033
Vinit Deshapnde30ad2542013-08-21 13:09:01 -070034import android.app.AlarmManager;
Wink Saville32506bc2013-06-29 21:10:57 -070035import android.app.Notification;
36import android.app.NotificationManager;
37import android.app.PendingIntent;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080038import android.bluetooth.BluetoothTetheringDataTracker;
Wink Saville9a1a7ef2013-08-29 08:55:16 -070039import android.content.ActivityNotFoundException;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090043import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070045import android.content.IntentFilter;
The Android Open Source Project28527d22009-03-03 19:31:44 -080046import android.content.pm.PackageManager;
Robert Greenwalt39d56012013-07-16 12:06:09 -070047import android.content.res.Configuration;
tk.mun093f55c2011-10-13 22:51:57 +090048import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070049import android.database.ContentObserver;
Irfan Sheriff0ad0d132012-08-16 12:49:23 -070050import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080051import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080052import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080053import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070055import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070056import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070058import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070059import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080060import android.net.LinkProperties;
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -070061import android.net.LinkQualityInfo;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070062import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070064import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070066import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070067import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070068import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080069import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070070import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070071import android.net.Proxy;
72import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070073import android.net.RouteInfo;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -070074import android.net.SamplingDataTracker;
Jason Monka5bf2842013-07-03 17:04:33 -040075import android.net.Uri;
The Android Open Source Project28527d22009-03-03 19:31:44 -080076import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090077import android.net.wimax.WimaxManagerConstants;
Wink Saville32506bc2013-06-29 21:10:57 -070078import android.os.AsyncTask;
The Android Open Source Project28527d22009-03-03 19:31:44 -080079import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040080import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080081import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070082import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070083import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070084import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080085import android.os.Looper;
86import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070087import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070088import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070089import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -070090import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070091import android.os.RemoteException;
Wink Saville32506bc2013-06-29 21:10:57 -070092import android.os.ResultReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070094import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080095import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -070096import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080097import android.provider.Settings;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070098import android.security.Credentials;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070099import android.security.KeyStore;
Wink Saville32506bc2013-06-29 21:10:57 -0700100import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700101import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800102import android.util.Slog;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700103import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700104import android.util.SparseIntArray;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700105import android.util.Xml;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800106
Wink Saville32506bc2013-06-29 21:10:57 -0700107import com.android.internal.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400108import com.android.internal.annotations.GuardedBy;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700109import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700110import com.android.internal.net.VpnConfig;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700111import com.android.internal.net.VpnProfile;
Wink Saville32506bc2013-06-29 21:10:57 -0700112import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700113import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700114import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700115import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700116import com.android.internal.util.XmlUtils;
Jason Monka5bf2842013-07-03 17:04:33 -0400117import com.android.net.IProxyService;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700118import com.android.server.am.BatteryStatsService;
John Spurlock1f5cec72013-06-24 14:20:23 -0400119import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900120import com.android.server.connectivity.Nat464Xlat;
Jason Monka5bf2842013-07-03 17:04:33 -0400121import com.android.server.connectivity.PacManager;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800122import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700123import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700124import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700125import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700126import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700127import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700128
tk.mun093f55c2011-10-13 22:51:57 +0900129import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700130
Robert Greenwalt39d56012013-07-16 12:06:09 -0700131import org.xmlpull.v1.XmlPullParser;
132import org.xmlpull.v1.XmlPullParserException;
133
134import java.io.File;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135import java.io.FileDescriptor;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700136import java.io.FileNotFoundException;
137import java.io.FileReader;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700138import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800139import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900140import java.lang.reflect.Constructor;
Wink Saville32506bc2013-06-29 21:10:57 -0700141import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700142import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700143import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700144import java.net.InetAddress;
Wink Saville32506bc2013-06-29 21:10:57 -0700145import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700146import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700147import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700148import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700149import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700150import java.util.GregorianCalendar;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700151import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700152import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700153import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700154import java.util.Map;
Wink Saville32506bc2013-06-29 21:10:57 -0700155import java.util.Random;
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700156import java.util.concurrent.atomic.AtomicBoolean;
Wink Saville32506bc2013-06-29 21:10:57 -0700157import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158
159/**
160 * @hide
161 */
162public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700163 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800164
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700165 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700166 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800167
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700168 private static final boolean LOGD_RULES = false;
169
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700170 // TODO: create better separation between radio types and network types
171
Robert Greenwalt2034b912009-08-12 16:08:25 -0700172 // how long to wait before switching back to a radio's default network
173 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
174 // system property that can override the above value
175 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
176 "android.telephony.apn-restore";
177
Wink Saville32506bc2013-06-29 21:10:57 -0700178 // Default value if FAIL_FAST_TIME_MS is not set
179 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
180 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
181 private static final String FAIL_FAST_TIME_MS =
182 "persist.radio.fail_fast_time_ms";
183
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700184 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
185 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
186
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -0700187 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700188
189 private PendingIntent mSampleIntervalElapsedIntent;
190
191 // Set network sampling interval at 12 minutes, this way, even if the timers get
192 // aggregated, it will fire at around 15 minutes, which should allow us to
193 // aggregate this timer with other timers (specially the socket keep alive timers)
194 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
195
196 // start network sampling a minute after booting ...
197 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
198
199 AlarmManager mAlarmManager;
200
Robert Greenwaltbd492212011-05-06 17:10:53 -0700201 // used in recursive route setting to add gateways for the host for which
202 // a host route was requested.
203 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
204
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800205 private Tethering mTethering;
206
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700207 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700208
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700209 @GuardedBy("mVpns")
210 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700211 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700212
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700213 private boolean mLockdownEnabled;
214 private LockdownVpnTracker mLockdownTracker;
215
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900216 private Nat464Xlat mClat;
217
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700218 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
219 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700220 /** Currently active network rules by UID. */
221 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700222 /** Set of ifaces that are costly. */
223 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700224
The Android Open Source Project28527d22009-03-03 19:31:44 -0800225 /**
226 * Sometimes we want to refer to the individual network state
227 * trackers separately, and sometimes we just want to treat them
228 * abstractly.
229 */
230 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700231
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700232 /* Handles captive portal check on a network */
233 private CaptivePortalTracker mCaptivePortalTracker;
234
Robert Greenwalt2034b912009-08-12 16:08:25 -0700235 /**
Wink Saville051a6642011-07-13 13:44:13 -0700236 * The link properties that define the current links
237 */
238 private LinkProperties mCurrentLinkProperties[];
239
240 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700241 * A per Net list of the PID's that requested access to the net
242 * used both as a refcount and for per-PID DNS selection
243 */
Mattias Falkd697aa22011-08-23 14:15:13 +0200244 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700245
Robert Greenwalt2034b912009-08-12 16:08:25 -0700246 // priority order of the nettrackers
247 // (excluding dynamically set mNetworkPreference)
248 // TODO - move mNetworkTypePreference into this
249 private int[] mPriorityList;
250
The Android Open Source Project28527d22009-03-03 19:31:44 -0800251 private Context mContext;
252 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700253 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700254 // 0 is full bad, 100 is full good
Wink Saville151eaa62013-01-31 00:30:13 +0000255 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700256 private int mDefaultInetConditionPublished = 0;
257 private boolean mInetConditionChangeInFlight = false;
258 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800259
Chia-chi Yehcc844502011-07-14 18:01:57 -0700260 private Object mDnsLock = new Object();
Robert Greenwalte41e3b32013-02-11 15:25:10 -0800261 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800262
263 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700264 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800265
Robert Greenwalt355205c2011-05-10 15:05:02 -0700266 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700267 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700268
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700269 private static final int ENABLED = 1;
270 private static final int DISABLED = 0;
271
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700272 private static final boolean ADD = true;
273 private static final boolean REMOVE = false;
274
275 private static final boolean TO_DEFAULT_TABLE = true;
276 private static final boolean TO_SECONDARY_TABLE = false;
277
Chad Brubaker49db4222013-07-15 16:34:04 -0700278 private static final boolean EXEMPT = true;
279 private static final boolean UNEXEMPT = false;
280
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700281 /**
282 * used internally as a delayed event to make us switch back to the
283 * default network
284 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700285 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700286
287 /**
288 * used internally to change our mobile data enabled flag
289 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700290 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700291
292 /**
293 * used internally to change our network preference setting
294 * arg1 = networkType to prefer
295 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700296 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700297
298 /**
299 * used internally to synchronize inet condition reports
300 * arg1 = networkType
301 * arg2 = condition (0 bad, 100 good)
302 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700303 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700304
305 /**
306 * used internally to mark the end of inet condition hold periods
307 * arg1 = networkType
308 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700309 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700310
311 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700312 * used internally to set enable/disable cellular data
313 * arg1 = ENBALED or DISABLED
314 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700315 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700316
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700317 /**
318 * used internally to clear a wakelock when transitioning
319 * from one net to another
320 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700321 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700322
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700323 /**
324 * used internally to reload global proxy settings
325 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700326 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700327
Robert Greenwalt34848c02011-03-25 13:09:25 -0700328 /**
329 * used internally to set external dependency met/unmet
330 * arg1 = ENABLED (met) or DISABLED (unmet)
331 * arg2 = NetworkType
332 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700333 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700334
Chia-chi Yehcc844502011-07-14 18:01:57 -0700335 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700336 * used internally to send a sticky broadcast delayed.
337 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700338 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700339
Jeff Sharkey805662d2011-08-19 02:24:24 -0700340 /**
341 * Used internally to
342 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
343 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700344 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700345
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700346 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700347
Wink Saville32506bc2013-06-29 21:10:57 -0700348 /**
349 * Used internally to disable fail fast of mobile data
350 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700351 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Saville32506bc2013-06-29 21:10:57 -0700352
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700353 /**
354 * user internally to indicate that data sampling interval is up
355 */
356 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
357
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700358 /** Handler used for internal events. */
359 private InternalHandler mHandler;
360 /** Handler used for incoming {@link NetworkStateTracker} events. */
361 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700362
363 // list of DeathRecipients used to make sure features are turned off when
364 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500365 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700366
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400367 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800368 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400369
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700370 private PowerManager.WakeLock mNetTransitionWakeLock;
371 private String mNetTransitionWakeLockCausedBy = "";
372 private int mNetTransitionWakeLockSerialNumber;
373 private int mNetTransitionWakeLockTimeout;
374
Robert Greenwalt94daa182010-09-01 11:34:05 -0700375 private InetAddress mDefaultDns;
376
Chad Brubaker49db4222013-07-15 16:34:04 -0700377 // Lock for protecting access to mAddedRoutes and mExemptAddresses
378 private final Object mRoutesLock = new Object();
379
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700380 // this collection is used to refcount the added routes - if there are none left
381 // it's time to remove the route from the route table
Chad Brubaker49db4222013-07-15 16:34:04 -0700382 @GuardedBy("mRoutesLock")
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700383 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
384
Chad Brubaker49db4222013-07-15 16:34:04 -0700385 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
386 // used to handle cleanup of exempt rules
387 @GuardedBy("mRoutesLock")
388 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
389
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700390 // used in DBG mode to track inet condition reports
391 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
392 private ArrayList mInetLog;
393
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700394 // track the current default http proxy - tell the world if we get a new one (real change)
395 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltf9661d32013-04-05 17:14:19 -0700396 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700397 private boolean mDefaultProxyDisabled = false;
398
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700399 // track the global proxy.
400 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700401
Jason Monka5bf2842013-07-03 17:04:33 -0400402 private PacManager mPacManager = null;
403
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700404 private SettingsObserver mSettingsObserver;
405
Robert Greenwalt34848c02011-03-25 13:09:25 -0700406 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700407 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700408
Robert Greenwalt12c44552009-12-07 11:33:18 -0800409 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700410 public int mSimultaneity;
411 public int mType;
412 public RadioAttributes(String init) {
413 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700414 mType = Integer.parseInt(fragments[0]);
415 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700416 }
417 }
418 RadioAttributes[] mRadioAttributes;
419
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700420 // the set of network types that can only be enabled by system/sig apps
421 List mProtectedNetworks;
422
John Spurlock1f5cec72013-06-24 14:20:23 -0400423 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700424
Wink Saville32506bc2013-06-29 21:10:57 -0700425 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
426
427 TelephonyManager mTelephonyManager;
John Spurlock1f5cec72013-06-24 14:20:23 -0400428
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700429 public ConnectivityService(Context context, INetworkManagementService netd,
430 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700431 // Currently, omitting a NetworkFactory will create one internally
432 // TODO: create here when we have cleaner WiMAX support
433 this(context, netd, statsService, policyManager, null);
434 }
435
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700436 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700437 INetworkStatsService statsService, INetworkPolicyManager policyManager,
438 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800439 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800440
Wink Saville775aad62010-09-02 19:23:52 -0700441 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
442 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700443 mHandler = new InternalHandler(handlerThread.getLooper());
444 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700445
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700446 if (netFactory == null) {
447 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
448 }
449
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800450 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800451 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
452 String id = Settings.Secure.getString(context.getContentResolver(),
453 Settings.Secure.ANDROID_ID);
454 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700455 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800456 SystemProperties.set("net.hostname", name);
457 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800458 }
459
Robert Greenwalt94daa182010-09-01 11:34:05 -0700460 // read our default dns server ip
Jeff Sharkey8c870452012-09-26 22:03:49 -0700461 String dns = Settings.Global.getString(context.getContentResolver(),
462 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700463 if (dns == null || dns.length() == 0) {
464 dns = context.getResources().getString(
465 com.android.internal.R.string.config_default_dns_server);
466 }
467 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800468 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
469 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800470 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700471 }
472
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700473 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700474 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700475 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700476 mKeyStore = KeyStore.getInstance();
Wink Saville32506bc2013-06-29 21:10:57 -0700477 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700478
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700479 try {
480 mPolicyManager.registerListener(mPolicyListener);
481 } catch (RemoteException e) {
482 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700483 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700484 }
485
486 final PowerManager powerManager = (PowerManager) context.getSystemService(
487 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700488 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
489 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
490 com.android.internal.R.integer.config_networkTransitionTimeout);
491
Robert Greenwalt2034b912009-08-12 16:08:25 -0700492 mNetTrackers = new NetworkStateTracker[
493 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700494 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700495
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700496 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700497 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700498
Robert Greenwalt2034b912009-08-12 16:08:25 -0700499 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700500 String[] raStrings = context.getResources().getStringArray(
501 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700502 for (String raString : raStrings) {
503 RadioAttributes r = new RadioAttributes(raString);
Wink Saville512c2202013-07-29 15:00:57 -0700504 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700505 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800506 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700507 continue;
508 }
509 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800510 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700511 r.mType);
512 continue;
513 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700514 mRadioAttributes[r.mType] = r;
515 }
516
Wink Saville00fe5092013-04-23 14:26:51 -0700517 // TODO: What is the "correct" way to do determine if this is a wifi only device?
518 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
519 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700520 String[] naStrings = context.getResources().getStringArray(
521 com.android.internal.R.array.networkAttributes);
522 for (String naString : naStrings) {
523 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700524 NetworkConfig n = new NetworkConfig(naString);
Wink Saville512c2202013-07-29 15:00:57 -0700525 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Savillef2a62832011-04-07 14:23:45 -0700526 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800527 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700528 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700529 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700530 }
Wink Saville00fe5092013-04-23 14:26:51 -0700531 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
532 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
533 n.type);
534 continue;
535 }
Wink Savillef2a62832011-04-07 14:23:45 -0700536 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800537 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700538 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700539 continue;
540 }
Wink Savillef2a62832011-04-07 14:23:45 -0700541 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800542 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700543 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700544 continue;
545 }
Wink Savillef2a62832011-04-07 14:23:45 -0700546 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700547 mNetworksDefined++;
548 } catch(Exception e) {
549 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700550 }
551 }
Wink Saville512c2202013-07-29 15:00:57 -0700552 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700553
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700554 mProtectedNetworks = new ArrayList<Integer>();
555 int[] protectedNetworks = context.getResources().getIntArray(
556 com.android.internal.R.array.config_protectedNetworks);
557 for (int p : protectedNetworks) {
558 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
559 mProtectedNetworks.add(p);
560 } else {
561 if (DBG) loge("Ignoring protectedNetwork " + p);
562 }
563 }
564
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700565 // high priority first
566 mPriorityList = new int[mNetworksDefined];
567 {
568 int insertionPoint = mNetworksDefined-1;
569 int currentLowest = 0;
570 int nextLowest = 0;
571 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700572 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700573 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700574 if (na.priority < currentLowest) continue;
575 if (na.priority > currentLowest) {
576 if (na.priority < nextLowest || nextLowest == 0) {
577 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700578 }
579 continue;
580 }
Wink Savillef2a62832011-04-07 14:23:45 -0700581 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700582 }
583 currentLowest = nextLowest;
584 nextLowest = 0;
585 }
586 }
587
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800588 // Update mNetworkPreference according to user mannually first then overlay config.xml
589 mNetworkPreference = getPersistedNetworkPreference();
590 if (mNetworkPreference == -1) {
591 for (int n : mPriorityList) {
592 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
593 mNetworkPreference = n;
594 break;
595 }
596 }
597 if (mNetworkPreference == -1) {
598 throw new IllegalStateException(
599 "You should set at least one default Network in config.xml!");
600 }
601 }
602
Mattias Falkd697aa22011-08-23 14:15:13 +0200603 mNetRequestersPids =
604 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700605 for (int i : mPriorityList) {
Mattias Falkd697aa22011-08-23 14:15:13 +0200606 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700607 }
608
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500609 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700610
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700611 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
612 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700613
614 // Create and start trackers for hard-coded networks
615 for (int targetNetworkType : mPriorityList) {
616 final NetworkConfig config = mNetConfigs[targetNetworkType];
617 final NetworkStateTracker tracker;
618 try {
619 tracker = netFactory.createTracker(targetNetworkType, config);
620 mNetTrackers[targetNetworkType] = tracker;
621 } catch (IllegalArgumentException e) {
622 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
623 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700624 continue;
625 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700626
627 tracker.startMonitoring(context, mTrackerHandler);
628 if (config.isDefault()) {
629 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800630 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700631 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800632
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700633 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800634
Robert Greenwaltf68291a2013-07-19 14:30:49 -0700635 //set up the listener for user state for creating user VPNs
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700636 IntentFilter intentFilter = new IntentFilter();
637 intentFilter.addAction(Intent.ACTION_USER_STARTING);
638 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
639 mContext.registerReceiverAsUser(
640 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900641 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
642
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700643 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700644 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700645 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900646 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700647 } catch (RemoteException e) {
648 loge("Error registering observer :" + e);
649 }
650
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700651 if (DBG) {
652 mInetLog = new ArrayList();
653 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700654
655 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
656 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800657
John Spurlock1f5cec72013-06-24 14:20:23 -0400658 mDataConnectionStats = new DataConnectionStats(mContext);
659 mDataConnectionStats.startMonitoring();
Jason Monka5bf2842013-07-03 17:04:33 -0400660
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700661 // start network sampling ..
662 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
663 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -0700664 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700665
666 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
667 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
668
669 IntentFilter filter = new IntentFilter();
670 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
671 mContext.registerReceiver(
672 new BroadcastReceiver() {
673 @Override
674 public void onReceive(Context context, Intent intent) {
675 String action = intent.getAction();
676 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
677 mHandler.sendMessage(mHandler.obtainMessage
678 (EVENT_SAMPLE_INTERVAL_ELAPSED));
679 }
680 }
681 },
682 new IntentFilter(filter));
683
Jason Monka5bf2842013-07-03 17:04:33 -0400684 mPacManager = new PacManager(mContext);
Wink Savillecb117d32013-08-29 14:57:08 -0700685
686 filter = new IntentFilter();
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700687 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
688 mContext.registerReceiver(mProvisioningReceiver, filter);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800689 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700690
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700691 /**
692 * Factory that creates {@link NetworkStateTracker} instances using given
693 * {@link NetworkConfig}.
694 */
695 public interface NetworkFactory {
696 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
697 }
698
699 private static class DefaultNetworkFactory implements NetworkFactory {
700 private final Context mContext;
701 private final Handler mTrackerHandler;
702
703 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
704 mContext = context;
705 mTrackerHandler = trackerHandler;
706 }
707
708 @Override
709 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
710 switch (config.radio) {
711 case TYPE_WIFI:
712 return new WifiStateTracker(targetNetworkType, config.name);
713 case TYPE_MOBILE:
714 return new MobileDataStateTracker(targetNetworkType, config.name);
715 case TYPE_DUMMY:
716 return new DummyDataStateTracker(targetNetworkType, config.name);
717 case TYPE_BLUETOOTH:
718 return BluetoothTetheringDataTracker.getInstance();
719 case TYPE_WIMAX:
720 return makeWimaxStateTracker(mContext, mTrackerHandler);
721 case TYPE_ETHERNET:
722 return EthernetDataTracker.getInstance();
723 default:
724 throw new IllegalArgumentException(
725 "Trying to create a NetworkStateTracker for an unknown radio type: "
726 + config.radio);
727 }
728 }
729 }
730
731 /**
732 * Loads external WiMAX library and registers as system service, returning a
733 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
734 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
735 */
736 private static NetworkStateTracker makeWimaxStateTracker(
737 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700738 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900739 DexClassLoader wimaxClassLoader;
740 Class wimaxStateTrackerClass = null;
741 Class wimaxServiceClass = null;
742 Class wimaxManagerClass;
743 String wimaxJarLocation;
744 String wimaxLibLocation;
745 String wimaxManagerClassName;
746 String wimaxServiceClassName;
747 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800748
tk.mun093f55c2011-10-13 22:51:57 +0900749 NetworkStateTracker wimaxStateTracker = null;
750
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700751 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900752 com.android.internal.R.bool.config_wimaxEnabled);
753
754 if (isWimaxEnabled) {
755 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700756 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900757 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700758 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900759 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700760 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900761 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700762 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900763 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700764 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900765 com.android.internal.R.string.config_wimaxStateTrackerClassname);
766
Dianne Hackborndc456a62012-11-08 11:12:09 -0800767 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900768 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700769 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900770 wimaxLibLocation, ClassLoader.getSystemClassLoader());
771
772 try {
773 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
774 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
775 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
776 } catch (ClassNotFoundException ex) {
777 loge("Exception finding Wimax classes: " + ex.toString());
778 return null;
779 }
780 } catch(Resources.NotFoundException ex) {
781 loge("Wimax Resources does not exist!!! ");
782 return null;
783 }
784
785 try {
Dianne Hackborndc456a62012-11-08 11:12:09 -0800786 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900787
788 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
789 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700790 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
791 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900792
793 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
794 (new Class[] {Context.class, wimaxStateTrackerClass});
795 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700796 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900797 wmxSrvConst.setAccessible(false);
798
799 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
800
801 } catch(Exception ex) {
802 loge("Exception creating Wimax classes: " + ex.toString());
803 return null;
804 }
805 } else {
806 loge("Wimax is not enabled or not added to the network attributes!!! ");
807 return null;
808 }
809
810 return wimaxStateTracker;
811 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700812
The Android Open Source Project28527d22009-03-03 19:31:44 -0800813 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700814 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800815 * @param preference the new preference
816 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700817 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800818 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700819
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700820 mHandler.sendMessage(
821 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800822 }
823
824 public int getNetworkPreference() {
825 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700826 int preference;
827 synchronized(this) {
828 preference = mNetworkPreference;
829 }
830 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800831 }
832
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700833 private void handleSetNetworkPreference(int preference) {
834 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700835 mNetConfigs[preference] != null &&
836 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700837 if (mNetworkPreference != preference) {
838 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownc67cf562012-09-25 15:03:20 -0700839 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700840 synchronized(this) {
841 mNetworkPreference = preference;
842 }
843 enforcePreference();
844 }
845 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800846 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700847
Wink Saville4f0de1e2011-08-04 15:01:58 -0700848 private int getConnectivityChangeDelay() {
849 final ContentResolver cr = mContext.getContentResolver();
850
851 /** Check system properties for the default value then use secure settings value, if any. */
852 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey8c870452012-09-26 22:03:49 -0700853 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
854 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
855 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700856 defaultDelay);
857 }
858
The Android Open Source Project28527d22009-03-03 19:31:44 -0800859 private int getPersistedNetworkPreference() {
860 final ContentResolver cr = mContext.getContentResolver();
861
Jeff Brownc67cf562012-09-25 15:03:20 -0700862 final int networkPrefSetting = Settings.Global
863 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800864
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800865 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800866 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700867
The Android Open Source Project28527d22009-03-03 19:31:44 -0800868 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700869 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800870 * In this method, we only tear down a non-preferred network. Establishing
871 * a connection to the preferred network is taken care of when we handle
872 * the disconnect event from the non-preferred network
873 * (see {@link #handleDisconnect(NetworkInfo)}).
874 */
875 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700876 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800877 return;
878
Robert Greenwalt2034b912009-08-12 16:08:25 -0700879 if (!mNetTrackers[mNetworkPreference].isAvailable())
880 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800881
Robert Greenwalt2034b912009-08-12 16:08:25 -0700882 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700883 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700884 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700885 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800886 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700887 " in enforcePreference");
888 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700889 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800890 }
891 }
892 }
893
894 private boolean teardown(NetworkStateTracker netTracker) {
895 if (netTracker.teardown()) {
896 netTracker.setTeardownRequested(true);
897 return true;
898 } else {
899 return false;
900 }
901 }
902
903 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700904 * Check if UID should be blocked from using the network represented by the
905 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700906 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700907 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
908 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700909
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700910 final boolean networkCostly;
911 final int uidRules;
912 synchronized (mRulesLock) {
913 networkCostly = mMeteredIfaces.contains(iface);
914 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700915 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700916
917 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
918 return true;
919 }
920
921 // no restrictive rules; network is visible
922 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700923 }
924
925 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700926 * Return a filtered {@link NetworkInfo}, potentially marked
927 * {@link DetailedState#BLOCKED} based on
928 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700929 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700930 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
931 NetworkInfo info = tracker.getNetworkInfo();
932 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700933 // network is blocked; clone and override state
934 info = new NetworkInfo(info);
935 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700936 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700937 if (mLockdownTracker != null) {
938 info = mLockdownTracker.augmentNetworkInfo(info);
939 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700940 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700941 }
942
943 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800944 * Return NetworkInfo for the active (i.e., connected) network interface.
945 * It is assumed that at most one network is active at a time. If more
946 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700947 * @return the info for the active network, or {@code null} if none is
948 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800949 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700950 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800951 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700952 enforceAccessPermission();
953 final int uid = Binder.getCallingUid();
954 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800955 }
956
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700957 /**
958 * Find the first Provisioning network.
959 *
960 * @return NetworkInfo or null if none.
961 */
962 private NetworkInfo getProvisioningNetworkInfo() {
963 enforceAccessPermission();
964
965 // Find the first Provisioning Network
966 NetworkInfo provNi = null;
967 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Savilleb1a32022013-09-05 12:02:25 -0700968 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700969 provNi = ni;
970 break;
971 }
972 }
973 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
974 return provNi;
975 }
976
977 /**
978 * Find the first Provisioning network or the ActiveDefaultNetwork
979 * if there is no Provisioning network
980 *
981 * @return NetworkInfo or null if none.
982 */
983 @Override
984 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
985 enforceAccessPermission();
986
987 NetworkInfo provNi = getProvisioningNetworkInfo();
988 if (provNi == null) {
989 final int uid = Binder.getCallingUid();
990 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
991 }
992 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
993 return provNi;
994 }
995
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700996 public NetworkInfo getActiveNetworkInfoUnfiltered() {
997 enforceAccessPermission();
998 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
999 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
1000 if (tracker != null) {
1001 return tracker.getNetworkInfo();
1002 }
1003 }
1004 return null;
1005 }
1006
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001007 @Override
1008 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1009 enforceConnectivityInternalPermission();
1010 return getNetworkInfo(mActiveDefaultNetwork, uid);
1011 }
1012
1013 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001014 public NetworkInfo getNetworkInfo(int networkType) {
1015 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001016 final int uid = Binder.getCallingUid();
1017 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001018 }
1019
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001020 private NetworkInfo getNetworkInfo(int networkType, int uid) {
1021 NetworkInfo info = null;
1022 if (isNetworkTypeValid(networkType)) {
1023 final NetworkStateTracker tracker = mNetTrackers[networkType];
1024 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001025 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001026 }
1027 }
1028 return info;
1029 }
1030
1031 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001032 public NetworkInfo[] getAllNetworkInfo() {
1033 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001034 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -07001035 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001036 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001037 for (NetworkStateTracker tracker : mNetTrackers) {
1038 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001039 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001040 }
1041 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001042 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001043 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001044 }
1045
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001046 @Override
1047 public boolean isNetworkSupported(int networkType) {
1048 enforceAccessPermission();
1049 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1050 }
1051
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001052 /**
1053 * Return LinkProperties for the active (i.e., connected) default
1054 * network interface. It is assumed that at most one default network
1055 * is active at a time. If more than one is active, it is indeterminate
1056 * which will be returned.
1057 * @return the ip properties for the active network, or {@code null} if
1058 * none is active
1059 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001060 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001061 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -07001062 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001063 }
1064
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001065 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001066 public LinkProperties getLinkProperties(int networkType) {
1067 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001068 if (isNetworkTypeValid(networkType)) {
1069 final NetworkStateTracker tracker = mNetTrackers[networkType];
1070 if (tracker != null) {
1071 return tracker.getLinkProperties();
1072 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001073 }
1074 return null;
1075 }
1076
Jeff Sharkey21062e72011-05-28 20:56:34 -07001077 @Override
1078 public NetworkState[] getAllNetworkState() {
1079 enforceAccessPermission();
1080 final int uid = Binder.getCallingUid();
1081 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001082 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -07001083 for (NetworkStateTracker tracker : mNetTrackers) {
1084 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001085 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -07001086 result.add(new NetworkState(
1087 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1088 }
1089 }
1090 }
1091 return result.toArray(new NetworkState[result.size()]);
1092 }
1093
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001094 private NetworkState getNetworkStateUnchecked(int networkType) {
1095 if (isNetworkTypeValid(networkType)) {
1096 final NetworkStateTracker tracker = mNetTrackers[networkType];
1097 if (tracker != null) {
1098 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1099 tracker.getLinkCapabilities());
1100 }
1101 }
1102 return null;
1103 }
1104
1105 @Override
1106 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1107 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001108
1109 final long token = Binder.clearCallingIdentity();
1110 try {
1111 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1112 if (state != null) {
1113 try {
1114 return mPolicyManager.getNetworkQuotaInfo(state);
1115 } catch (RemoteException e) {
1116 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001117 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001118 return null;
1119 } finally {
1120 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001121 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001122 }
1123
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001124 @Override
1125 public boolean isActiveNetworkMetered() {
1126 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001127 final long token = Binder.clearCallingIdentity();
1128 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001129 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001130 } finally {
1131 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001132 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001133 }
1134
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001135 private boolean isNetworkMeteredUnchecked(int networkType) {
1136 final NetworkState state = getNetworkStateUnchecked(networkType);
1137 if (state != null) {
1138 try {
1139 return mPolicyManager.isNetworkMetered(state);
1140 } catch (RemoteException e) {
1141 }
1142 }
1143 return false;
1144 }
1145
The Android Open Source Project28527d22009-03-03 19:31:44 -08001146 public boolean setRadios(boolean turnOn) {
1147 boolean result = true;
1148 enforceChangePermission();
1149 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001150 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001151 }
1152 return result;
1153 }
1154
1155 public boolean setRadio(int netType, boolean turnOn) {
1156 enforceChangePermission();
1157 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1158 return false;
1159 }
1160 NetworkStateTracker tracker = mNetTrackers[netType];
1161 return tracker != null && tracker.setRadio(turnOn);
1162 }
1163
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001164 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1165 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001166 public void interfaceClassDataActivityChanged(String label, boolean active) {
1167 int deviceType = Integer.parseInt(label);
1168 sendDataActivityBroadcast(deviceType, active);
1169 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001170 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001171
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001172 /**
1173 * Used to notice when the calling process dies so we can self-expire
1174 *
1175 * Also used to know if the process has cleaned up after itself when
1176 * our auto-expire timer goes off. The timer has a link to an object.
1177 *
1178 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001179 private class FeatureUser implements IBinder.DeathRecipient {
1180 int mNetworkType;
1181 String mFeature;
1182 IBinder mBinder;
1183 int mPid;
1184 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001185 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001186
1187 FeatureUser(int type, String feature, IBinder binder) {
1188 super();
1189 mNetworkType = type;
1190 mFeature = feature;
1191 mBinder = binder;
1192 mPid = getCallingPid();
1193 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001194 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001195
Robert Greenwalt2034b912009-08-12 16:08:25 -07001196 try {
1197 mBinder.linkToDeath(this, 0);
1198 } catch (RemoteException e) {
1199 binderDied();
1200 }
1201 }
1202
1203 void unlinkDeathRecipient() {
1204 mBinder.unlinkToDeath(this, 0);
1205 }
1206
1207 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001208 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001209 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1210 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001211 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001212 }
1213
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001214 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001215 if (VDBG) {
1216 log("ConnectivityService FeatureUser expire(" +
1217 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1218 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1219 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001220 stopUsingNetworkFeature(this, false);
1221 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001222
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001223 public boolean isSameUser(FeatureUser u) {
1224 if (u == null) return false;
1225
1226 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1227 }
1228
1229 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1230 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1231 TextUtils.equals(mFeature, feature)) {
1232 return true;
1233 }
1234 return false;
1235 }
1236
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001237 public String toString() {
1238 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1239 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1240 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001241 }
1242
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001243 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001244 public int startUsingNetworkFeature(int networkType, String feature,
1245 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001246 long startTime = 0;
1247 if (DBG) {
1248 startTime = SystemClock.elapsedRealtime();
1249 }
Wink Savillea7d56572011-09-21 11:05:43 -07001250 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001251 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1252 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001253 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001254 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001255 try {
1256 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1257 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001258 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001259 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001260
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001261 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001262
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001263 // TODO - move this into individual networktrackers
1264 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001265
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001266 if (mLockdownEnabled) {
1267 // Since carrier APNs usually aren't available from VPN
1268 // endpoint, mark them as unavailable.
1269 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1270 }
1271
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001272 if (mProtectedNetworks.contains(usedNetworkType)) {
1273 enforceConnectivityInternalPermission();
1274 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001275
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001276 // if UID is restricted, don't allow them to bring up metered APNs
1277 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1278 final int uidRules;
1279 synchronized (mRulesLock) {
1280 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1281 }
1282 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001283 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001284 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001285
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001286 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1287 if (network != null) {
1288 Integer currentPid = new Integer(getCallingPid());
1289 if (usedNetworkType != networkType) {
1290 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001291
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001292 if (ni.isAvailable() == false) {
1293 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1294 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001295 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001296 } else {
1297 // else make the attempt anyway - probably giving REQUEST_STARTED below
1298 if (DBG) {
1299 log("special network not available, but try anyway ni=" +
1300 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001301 }
1302 }
1303 }
1304
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001305 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001306
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001307 synchronized(this) {
1308 boolean addToList = true;
1309 if (restoreTimer < 0) {
1310 // In case there is no timer is specified for the feature,
1311 // make sure we don't add duplicate entry with the same request.
1312 for (FeatureUser u : mFeatureUsers) {
1313 if (u.isSameUser(f)) {
1314 // Duplicate user is found. Do not add.
1315 addToList = false;
1316 break;
1317 }
1318 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001319 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001320
1321 if (addToList) mFeatureUsers.add(f);
1322 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1323 // this gets used for per-pid dns when connected
1324 mNetRequestersPids[usedNetworkType].add(currentPid);
1325 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001326 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001327
1328 if (restoreTimer >= 0) {
1329 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1330 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1331 }
1332
1333 if ((ni.isConnectedOrConnecting() == true) &&
1334 !network.isTeardownRequested()) {
1335 if (ni.isConnected() == true) {
1336 final long token = Binder.clearCallingIdentity();
1337 try {
1338 // add the pid-specific dns
1339 handleDnsConfigurationChange(usedNetworkType);
1340 if (VDBG) log("special network already active");
1341 } finally {
1342 Binder.restoreCallingIdentity(token);
1343 }
Wink Saville64e3f782012-07-10 12:37:54 -07001344 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001345 }
1346 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001347 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001348 }
1349
1350 // check if the radio in play can make another contact
1351 // assume if cannot for now
1352
1353 if (DBG) {
1354 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1355 feature);
1356 }
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001357 if (network.reconnect()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001358 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001359 return PhoneConstants.APN_REQUEST_STARTED;
1360 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001361 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001362 return PhoneConstants.APN_REQUEST_FAILED;
1363 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001364 } else {
1365 // need to remember this unsupported request so we respond appropriately on stop
1366 synchronized(this) {
1367 mFeatureUsers.add(f);
1368 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1369 // this gets used for per-pid dns when connected
1370 mNetRequestersPids[usedNetworkType].add(currentPid);
1371 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001372 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001373 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001374 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001375 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001376 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001377 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Saville64e3f782012-07-10 12:37:54 -07001378 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001379 } finally {
1380 if (DBG) {
1381 final long execTime = SystemClock.elapsedRealtime() - startTime;
1382 if (execTime > 250) {
1383 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1384 } else {
1385 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1386 }
1387 }
1388 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001389 }
1390
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001391 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001392 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001393 enforceChangePermission();
1394
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001395 int pid = getCallingPid();
1396 int uid = getCallingUid();
1397
1398 FeatureUser u = null;
1399 boolean found = false;
1400
1401 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001402 for (FeatureUser x : mFeatureUsers) {
1403 if (x.isSameUser(pid, uid, networkType, feature)) {
1404 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001405 found = true;
1406 break;
1407 }
1408 }
1409 }
1410 if (found && u != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001411 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001412 // stop regardless of how many other time this proc had called start
1413 return stopUsingNetworkFeature(u, true);
1414 } else {
1415 // none found!
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001416 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001417 return 1;
1418 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001419 }
1420
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001421 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1422 int networkType = u.mNetworkType;
1423 String feature = u.mFeature;
1424 int pid = u.mPid;
1425 int uid = u.mUid;
1426
1427 NetworkStateTracker tracker = null;
1428 boolean callTeardown = false; // used to carry our decision outside of sync block
1429
Wink Savillea7d56572011-09-21 11:05:43 -07001430 if (VDBG) {
1431 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001432 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001433
The Android Open Source Project28527d22009-03-03 19:31:44 -08001434 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001435 if (DBG) {
1436 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1437 ", net is invalid");
1438 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001439 return -1;
1440 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001441
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001442 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1443 // sync block
1444 synchronized(this) {
1445 // check if this process still has an outstanding start request
1446 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001447 if (VDBG) {
1448 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1449 ", ignoring");
1450 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001451 return 1;
1452 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001453 u.unlinkDeathRecipient();
1454 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1455 // If we care about duplicate requests, check for that here.
1456 //
1457 // This is done to support the extension of a request - the app
1458 // can request we start the network feature again and renew the
1459 // auto-shutoff delay. Normal "stop" calls from the app though
1460 // do not pay attention to duplicate requests - in effect the
1461 // API does not refcount and a single stop will counter multiple starts.
1462 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001463 for (FeatureUser x : mFeatureUsers) {
1464 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001465 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001466 return 1;
1467 }
1468 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001469 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001470
repo syncf5de5572011-07-29 23:55:49 -07001471 // TODO - move to individual network trackers
1472 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1473
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001474 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001475 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001476 if (DBG) {
1477 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1478 " no known tracker for used net type " + usedNetworkType);
1479 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001480 return -1;
1481 }
1482 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001483 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001484 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalte767d812013-02-12 17:18:25 -08001485
1486 final long token = Binder.clearCallingIdentity();
1487 try {
1488 reassessPidDns(pid, true);
1489 } finally {
1490 Binder.restoreCallingIdentity(token);
1491 }
Mattias Falkd697aa22011-08-23 14:15:13 +02001492 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001493 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001494 if (VDBG) {
1495 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1496 " others still using it");
1497 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001498 return 1;
1499 }
1500 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001501 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001502 if (DBG) {
1503 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1504 " not a known feature - dropping");
1505 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001506 }
1507 }
Wink Savillea7d56572011-09-21 11:05:43 -07001508
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001509 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001510 if (DBG) {
1511 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1512 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001513 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001514 return 1;
1515 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001516 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001517 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001518 }
1519
1520 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001521 * @deprecated use requestRouteToHostAddress instead
1522 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001523 * Ensure that a network route exists to deliver traffic to the specified
1524 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001525 * @param networkType the type of the network over which traffic to the
1526 * specified host is to be routed
1527 * @param hostAddress the IP address of the host to which the route is
1528 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001529 * @return {@code true} on success, {@code false} on failure
1530 */
1531 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001532 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1533
1534 if (inetAddress == null) {
1535 return false;
1536 }
1537
1538 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1539 }
1540
1541 /**
1542 * Ensure that a network route exists to deliver traffic to the specified
1543 * host via the specified network interface.
1544 * @param networkType the type of the network over which traffic to the
1545 * specified host is to be routed
1546 * @param hostAddress the IP address of the host to which the route is
1547 * desired
1548 * @return {@code true} on success, {@code false} on failure
1549 */
1550 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001551 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001552 if (mProtectedNetworks.contains(networkType)) {
1553 enforceConnectivityInternalPermission();
1554 }
1555
The Android Open Source Project28527d22009-03-03 19:31:44 -08001556 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001557 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001558 return false;
1559 }
1560 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001561 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001562
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001563 if (tracker == null || (netState != DetailedState.CONNECTED &&
1564 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001565 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001566 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07001567 log("requestRouteToHostAddress on down network "
1568 + "(" + networkType + ") - dropped"
1569 + " tracker=" + tracker
1570 + " netState=" + netState
1571 + " isTeardownRequested="
1572 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001573 }
1574 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001575 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001576 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001577 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001578 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001579 LinkProperties lp = tracker.getLinkProperties();
Chad Brubaker49db4222013-07-15 16:34:04 -07001580 boolean ok = addRouteToAddress(lp, addr, EXEMPT);
Wink Saville32506bc2013-06-29 21:10:57 -07001581 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1582 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001583 } catch (UnknownHostException e) {
1584 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1585 } finally {
1586 Binder.restoreCallingIdentity(token);
1587 }
Wink Saville32506bc2013-06-29 21:10:57 -07001588 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001589 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001590 }
1591
Chad Brubaker49db4222013-07-15 16:34:04 -07001592 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1593 boolean exempt) {
1594 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001595 }
1596
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001597 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001598 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001599 }
1600
Chad Brubaker49db4222013-07-15 16:34:04 -07001601 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1602 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001603 }
1604
1605 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001606 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwalt98107422011-07-22 11:55:33 -07001607 }
1608
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001609 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubaker49db4222013-07-15 16:34:04 -07001610 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001611 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001612 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001613 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001614 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001615 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001616 if (bestRoute.getGateway().equals(addr)) {
1617 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001618 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001619 } else {
1620 // if we will connect to this through another route, add a direct route
1621 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001622 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001623 }
1624 }
Chad Brubaker49db4222013-07-15 16:34:04 -07001625 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001626 }
1627
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001628 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubaker49db4222013-07-15 16:34:04 -07001629 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001630 if ((lp == null) || (r == null)) {
1631 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001632 return false;
1633 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001634
1635 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001636 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001637 return false;
1638 }
1639
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001640 String ifaceName = r.getInterface();
1641 if(ifaceName == null) {
1642 loge("Error modifying route - no interface name");
1643 return false;
1644 }
Robert Greenwalt59070cf2013-04-11 13:48:16 -07001645 if (r.hasGateway()) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001646 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001647 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001648 if (bestRoute.getGateway().equals(r.getGateway())) {
1649 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001650 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001651 } else {
1652 // if we will connect to our gateway through another route, add a direct
1653 // route to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001654 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1655 bestRoute.getGateway(),
1656 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001657 }
Chad Brubaker49db4222013-07-15 16:34:04 -07001658 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001659 }
1660 }
1661 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001662 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001663 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001664 if (toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001665 synchronized (mRoutesLock) {
1666 // only track default table - only one apps can effect
1667 mAddedRoutes.add(r);
1668 mNetd.addRoute(ifaceName, r);
1669 if (exempt) {
1670 LinkAddress dest = r.getDestination();
1671 if (!mExemptAddresses.contains(dest)) {
1672 mNetd.setHostExemption(dest);
1673 mExemptAddresses.add(dest);
1674 }
1675 }
1676 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001677 } else {
1678 mNetd.addSecondaryRoute(ifaceName, r);
1679 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001680 } catch (Exception e) {
1681 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001682 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001683 return false;
1684 }
1685 } else {
1686 // if we remove this one and there are no more like it, then refcount==0 and
1687 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001688 if (toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001689 synchronized (mRoutesLock) {
1690 mAddedRoutes.remove(r);
1691 if (mAddedRoutes.contains(r) == false) {
1692 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1693 try {
1694 mNetd.removeRoute(ifaceName, r);
1695 LinkAddress dest = r.getDestination();
1696 if (mExemptAddresses.contains(dest)) {
1697 mNetd.clearHostExemption(dest);
1698 mExemptAddresses.remove(dest);
1699 }
1700 } catch (Exception e) {
1701 // never crash - catch them all
1702 if (VDBG) loge("Exception trying to remove a route: " + e);
1703 return false;
1704 }
1705 } else {
1706 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001707 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001708 }
1709 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001710 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001711 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001712 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001713 } catch (Exception e) {
1714 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001715 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001716 return false;
1717 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001718 }
1719 }
1720 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001721 }
1722
1723 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001724 * @see ConnectivityManager#getMobileDataEnabled()
1725 */
1726 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001727 // TODO: This detail should probably be in DataConnectionTracker's
1728 // which is where we store the value and maybe make this
1729 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001730 enforceAccessPermission();
Jeff Sharkey8b361572012-09-26 15:54:06 -07001731 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1732 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001733 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001734 return retVal;
1735 }
1736
Robert Greenwalt34848c02011-03-25 13:09:25 -07001737 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001738 enforceConnectivityInternalPermission();
1739
Robert Greenwalt34848c02011-03-25 13:09:25 -07001740 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1741 (met ? ENABLED : DISABLED), networkType));
1742 }
1743
1744 private void handleSetDependencyMet(int networkType, boolean met) {
1745 if (mNetTrackers[networkType] != null) {
1746 if (DBG) {
1747 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1748 }
1749 mNetTrackers[networkType].setDependencyMet(met);
1750 }
1751 }
1752
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001753 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1754 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001755 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001756 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001757 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001758 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001759 }
1760
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001761 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001762 // skip update when we've already applied rules
1763 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1764 if (oldRules == uidRules) return;
1765
1766 mUidRules.put(uid, uidRules);
1767 }
1768
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001769 // TODO: notify UID when it has requested targeted updates
1770 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001771
1772 @Override
1773 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001774 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001775 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001776 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001777 }
1778
1779 synchronized (mRulesLock) {
1780 mMeteredIfaces.clear();
1781 for (String iface : meteredIfaces) {
1782 mMeteredIfaces.add(iface);
1783 }
1784 }
1785 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001786
1787 @Override
1788 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1789 // caller is NPMS, since we only register with them
1790 if (LOGD_RULES) {
1791 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1792 }
1793
1794 // kick off connectivity change broadcast for active network, since
1795 // global background policy change is radical.
1796 final int networkType = mActiveDefaultNetwork;
1797 if (isNetworkTypeValid(networkType)) {
1798 final NetworkStateTracker tracker = mNetTrackers[networkType];
1799 if (tracker != null) {
1800 final NetworkInfo info = tracker.getNetworkInfo();
1801 if (info != null && info.isConnected()) {
1802 sendConnectedBroadcast(info);
1803 }
1804 }
1805 }
1806 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001807 };
1808
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001809 /**
1810 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1811 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001812 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001813 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001814 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001815
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001816 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001817 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001818 }
1819
1820 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001821 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001822 if (VDBG) {
1823 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001824 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001825 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1826 }
tk.mun5eee1042012-01-06 10:43:52 +09001827 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1828 if (VDBG) {
1829 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1830 }
1831 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1832 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001833 }
1834
1835 @Override
1836 public void setPolicyDataEnable(int networkType, boolean enabled) {
1837 // only someone like NPMS should only be calling us
1838 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1839
1840 mHandler.sendMessage(mHandler.obtainMessage(
1841 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1842 }
1843
1844 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1845 if (isNetworkTypeValid(networkType)) {
1846 final NetworkStateTracker tracker = mNetTrackers[networkType];
1847 if (tracker != null) {
1848 tracker.setPolicyDataEnable(enabled);
1849 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001850 }
1851 }
1852
The Android Open Source Project28527d22009-03-03 19:31:44 -08001853 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001854 mContext.enforceCallingOrSelfPermission(
1855 android.Manifest.permission.ACCESS_NETWORK_STATE,
1856 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001857 }
1858
1859 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001860 mContext.enforceCallingOrSelfPermission(
1861 android.Manifest.permission.CHANGE_NETWORK_STATE,
1862 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001863 }
1864
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001865 // TODO Make this a special check when it goes public
1866 private void enforceTetherChangePermission() {
1867 mContext.enforceCallingOrSelfPermission(
1868 android.Manifest.permission.CHANGE_NETWORK_STATE,
1869 "ConnectivityService");
1870 }
1871
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001872 private void enforceTetherAccessPermission() {
1873 mContext.enforceCallingOrSelfPermission(
1874 android.Manifest.permission.ACCESS_NETWORK_STATE,
1875 "ConnectivityService");
1876 }
1877
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001878 private void enforceConnectivityInternalPermission() {
1879 mContext.enforceCallingOrSelfPermission(
1880 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1881 "ConnectivityService");
1882 }
1883
Chad Brubaker11f22252013-07-11 13:29:30 -07001884 private void enforceMarkNetworkSocketPermission() {
1885 //Media server special case
1886 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1887 return;
1888 }
1889 mContext.enforceCallingOrSelfPermission(
1890 android.Manifest.permission.MARK_NETWORK_SOCKET,
1891 "ConnectivityService");
1892 }
1893
The Android Open Source Project28527d22009-03-03 19:31:44 -08001894 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001895 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1896 * network, we ignore it. If it is for the active network, we send out a
1897 * broadcast. But first, we check whether it might be possible to connect
1898 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001899 * @param info the {@code NetworkInfo} for the network
1900 */
1901 private void handleDisconnect(NetworkInfo info) {
1902
Robert Greenwalt2034b912009-08-12 16:08:25 -07001903 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001904
Robert Greenwalt2034b912009-08-12 16:08:25 -07001905 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001906
1907 // Remove idletimer previously setup in {@code handleConnect}
1908 removeDataActivityTracking(prevNetType);
1909
The Android Open Source Project28527d22009-03-03 19:31:44 -08001910 /*
1911 * If the disconnected network is not the active one, then don't report
1912 * this as a loss of connectivity. What probably happened is that we're
1913 * getting the disconnect for a network that we explicitly disabled
1914 * in accordance with network preference policies.
1915 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001916 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkd697aa22011-08-23 14:15:13 +02001917 List<Integer> pids = mNetRequestersPids[prevNetType];
1918 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001919 // will remove them because the net's no longer connected
1920 // need to do this now as only now do we know the pids and
1921 // can properly null things that are no longer referenced.
1922 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001923 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001924 }
1925
The Android Open Source Project28527d22009-03-03 19:31:44 -08001926 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001927 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001928 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001929 if (info.isFailover()) {
1930 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1931 info.setFailover(false);
1932 }
1933 if (info.getReason() != null) {
1934 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1935 }
1936 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001937 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1938 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001939 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001940
Robert Greenwalt34848c02011-03-25 13:09:25 -07001941 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001942 tryFailover(prevNetType);
1943 if (mActiveDefaultNetwork != -1) {
1944 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001945 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1946 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001947 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001948 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1949 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001950 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001951 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001952
1953 // Reset interface if no other connections are using the same interface
1954 boolean doReset = true;
1955 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1956 if (linkProperties != null) {
1957 String oldIface = linkProperties.getInterfaceName();
1958 if (TextUtils.isEmpty(oldIface) == false) {
1959 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1960 if (networkStateTracker == null) continue;
1961 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1962 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1963 LinkProperties l = networkStateTracker.getLinkProperties();
1964 if (l == null) continue;
1965 if (oldIface.equals(l.getInterfaceName())) {
1966 doReset = false;
1967 break;
1968 }
1969 }
1970 }
1971 }
1972 }
1973
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001974 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001975 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001976
Jeff Sharkey971cd162011-08-29 16:02:57 -07001977 final Intent immediateIntent = new Intent(intent);
1978 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1979 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001980 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001981 /*
1982 * If the failover network is already connected, then immediately send
1983 * out a followup broadcast indicating successful failover
1984 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001985 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001986 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1987 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001988 }
1989 }
1990
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001991 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001992 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001993 * If this is a default network, check if other defaults are available.
1994 * Try to reconnect on all available and let them hash it out when
1995 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001996 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001997 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001998 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001999 if (DBG) {
2000 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2001 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002002 mActiveDefaultNetwork = -1;
2003 }
2004
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002005 // don't signal a reconnect for anything lower or equal priority than our
2006 // current connected default
2007 // TODO - don't filter by priority now - nice optimization but risky
2008// int currentPriority = -1;
2009// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002010// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002011// }
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002012
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002013 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07002014 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002015 if (mNetConfigs[checkType] == null) continue;
2016 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08002017 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08002018
2019// Enabling the isAvailable() optimization caused mobile to not get
2020// selected if it was in the middle of error handling. Specifically
2021// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2022// would not be available and we wouldn't get connected to anything.
2023// So removing the isAvailable() optimization below for now. TODO: This
2024// optimization should work and we need to investigate why it doesn't work.
2025// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2026// complete before it is really complete.
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002027
Wink Saville72a95b92011-01-26 15:43:49 -08002028// if (!mNetTrackers[checkType].isAvailable()) continue;
2029
Robert Greenwalt34848c02011-03-25 13:09:25 -07002030// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002031
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002032 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2033 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2034 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2035 checkInfo.setFailover(true);
2036 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002037 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002038 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002039 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002040 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002041 }
2042
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002043 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002044 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07002045 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2046 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002047 }
2048
Wink Saville4f0de1e2011-08-04 15:01:58 -07002049 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002050 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2051 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002052 }
2053
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002054 private void sendInetConditionBroadcast(NetworkInfo info) {
2055 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2056 }
2057
Wink Saville4f0de1e2011-08-04 15:01:58 -07002058 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002059 if (mLockdownTracker != null) {
2060 info = mLockdownTracker.augmentNetworkInfo(info);
2061 }
2062
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002063 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002064 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002065 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002066 if (info.isFailover()) {
2067 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2068 info.setFailover(false);
2069 }
2070 if (info.getReason() != null) {
2071 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2072 }
2073 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002074 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2075 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002076 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002077 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002078 return intent;
2079 }
2080
2081 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2082 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2083 }
2084
2085 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2086 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002087 }
2088
Haoyu Baib5da5752012-06-20 14:29:57 -07002089 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2090 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2091 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2092 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002093 final long ident = Binder.clearCallingIdentity();
2094 try {
2095 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2096 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2097 } finally {
2098 Binder.restoreCallingIdentity(ident);
2099 }
Haoyu Baib5da5752012-06-20 14:29:57 -07002100 }
2101
The Android Open Source Project28527d22009-03-03 19:31:44 -08002102 /**
2103 * Called when an attempt to fail over to another network has failed.
2104 * @param info the {@link NetworkInfo} for the failed network
2105 */
2106 private void handleConnectionFailure(NetworkInfo info) {
2107 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002108
Robert Greenwalt2034b912009-08-12 16:08:25 -07002109 String reason = info.getReason();
2110 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002111
Robert Greenwalte981bc52010-10-08 16:35:52 -07002112 String reasonText;
2113 if (reason == null) {
2114 reasonText = ".";
2115 } else {
2116 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002117 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002118 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002119
2120 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002121 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002122 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002123 if (getActiveNetworkInfo() == null) {
2124 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2125 }
2126 if (reason != null) {
2127 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2128 }
2129 if (extraInfo != null) {
2130 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2131 }
2132 if (info.isFailover()) {
2133 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2134 info.setFailover(false);
2135 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002136
Robert Greenwalt34848c02011-03-25 13:09:25 -07002137 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002138 tryFailover(info.getType());
2139 if (mActiveDefaultNetwork != -1) {
2140 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002141 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2142 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002143 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002144 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2145 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002146 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002147
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002148 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002149
2150 final Intent immediateIntent = new Intent(intent);
2151 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2152 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002153 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002154 /*
2155 * If the failover network is already connected, then immediately send
2156 * out a followup broadcast indicating successful failover
2157 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002158 if (mActiveDefaultNetwork != -1) {
2159 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002160 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002161 }
2162
2163 private void sendStickyBroadcast(Intent intent) {
2164 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002165 if (!mSystemReady) {
2166 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002167 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002168 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002169 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002170 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002171 }
2172
Dianne Hackborne588ca12012-09-04 18:48:37 -07002173 final long ident = Binder.clearCallingIdentity();
2174 try {
2175 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2176 } finally {
2177 Binder.restoreCallingIdentity(ident);
2178 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002179 }
2180 }
2181
Wink Saville4f0de1e2011-08-04 15:01:58 -07002182 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2183 if (delayMs <= 0) {
2184 sendStickyBroadcast(intent);
2185 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002186 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002187 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2188 + intent.getAction());
2189 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002190 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2191 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2192 }
2193 }
2194
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002195 void systemReady() {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002196 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2197 loadGlobalProxy();
2198
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002199 synchronized(this) {
2200 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002201 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002202 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002203 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002204 }
2205 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002206 // load the global proxy at startup
2207 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002208
2209 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2210 // for user to unlock device.
2211 if (!updateLockdownVpn()) {
2212 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2213 mContext.registerReceiver(mUserPresentReceiver, filter);
2214 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002215 }
2216
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002217 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2218 @Override
2219 public void onReceive(Context context, Intent intent) {
2220 // Try creating lockdown tracker, since user present usually means
2221 // unlocked keystore.
2222 if (updateLockdownVpn()) {
2223 mContext.unregisterReceiver(this);
2224 }
2225 }
2226 };
2227
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002228 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002229 if (((type != mNetworkPreference)
2230 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2231 || (mNetworkPreference == mActiveDefaultNetwork)) {
2232 return false;
2233 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002234 return true;
2235 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002236
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002237 private void handleConnect(NetworkInfo info) {
2238 final int newNetType = info.getType();
2239
2240 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002241
The Android Open Source Project28527d22009-03-03 19:31:44 -08002242 // snapshot isFailover, because sendConnectedBroadcast() resets it
2243 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002244 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002245 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002246
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002247 if (VDBG) {
2248 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2249 + " isFailover" + isFailover);
2250 }
2251
Robert Greenwalt2034b912009-08-12 16:08:25 -07002252 // if this is a default net and other default is running
2253 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002254 if (mNetConfigs[newNetType].isDefault()) {
2255 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2256 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002257 // tear down the other
2258 NetworkStateTracker otherNet =
2259 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002260 if (DBG) {
2261 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002262 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002263 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002264 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002265 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002266 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002267 return;
2268 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002269 } else {
2270 // don't accept this one
2271 if (VDBG) {
2272 log("Not broadcasting CONNECT_ACTION " +
2273 "to torn down network " + info.getTypeName());
2274 }
2275 teardown(thisNet);
2276 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002277 }
2278 }
2279 synchronized (ConnectivityService.this) {
2280 // have a new default network, release the transition wakelock in a second
2281 // if it's held. The second pause is to allow apps to reconnect over the
2282 // new network
2283 if (mNetTransitionWakeLock.isHeld()) {
2284 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002285 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002286 mNetTransitionWakeLockSerialNumber, 0),
2287 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002288 }
2289 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002290 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002291 // this will cause us to come up initially as unconnected and switching
2292 // to connected after our normal pause unless somebody reports us as reall
2293 // disconnected
2294 mDefaultInetConditionPublished = 0;
2295 mDefaultConnectionSequence++;
2296 mInetConditionChangeInFlight = false;
2297 // Don't do this - if we never sign in stay, grey
2298 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002299 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002300 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002301 updateNetworkSettings(thisNet);
sy.yun4aa73922013-09-02 05:24:09 +09002302 updateMtuSizeSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002303 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002304 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002305
2306 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002307 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002308 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002309 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002310 } catch (RemoteException e) {
2311 // ignored; service lives in system_server
2312 }
2313 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002314 }
2315
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002316 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2317 if (DBG) log("Captive portal check " + info);
2318 int type = info.getType();
2319 final NetworkStateTracker thisNet = mNetTrackers[type];
2320 if (mNetConfigs[type].isDefault()) {
2321 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2322 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2323 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002324 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002325 return;
2326 } else {
2327 if (DBG) log("Tear down low priority net " + info.getTypeName());
2328 teardown(thisNet);
2329 return;
2330 }
2331 }
2332 }
2333
Wink Saville674777e2013-08-07 16:22:47 -07002334 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002335 thisNet.captivePortalCheckComplete();
2336 }
2337
2338 /** @hide */
Wink Saville674777e2013-08-07 16:22:47 -07002339 @Override
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002340 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002341 enforceConnectivityInternalPermission();
Wink Saville674777e2013-08-07 16:22:47 -07002342 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002343 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002344 }
2345
Wink Saville674777e2013-08-07 16:22:47 -07002346 /** @hide */
2347 @Override
2348 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2349 enforceConnectivityInternalPermission();
2350 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2351 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2352 }
2353
The Android Open Source Project28527d22009-03-03 19:31:44 -08002354 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002355 * Setup data activity tracking for the given network interface.
2356 *
2357 * Every {@code setupDataActivityTracking} should be paired with a
2358 * {@link removeDataActivityTracking} for cleanup.
2359 */
2360 private void setupDataActivityTracking(int type) {
2361 final NetworkStateTracker thisNet = mNetTrackers[type];
2362 final String iface = thisNet.getLinkProperties().getInterfaceName();
2363
2364 final int timeout;
2365
2366 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002367 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2368 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002369 0);
2370 // Canonicalize mobile network type
2371 type = ConnectivityManager.TYPE_MOBILE;
2372 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002373 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2374 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002375 0);
2376 } else {
2377 // do not track any other networks
2378 timeout = 0;
2379 }
2380
2381 if (timeout > 0 && iface != null) {
2382 try {
2383 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2384 } catch (RemoteException e) {
2385 }
2386 }
2387 }
2388
2389 /**
2390 * Remove data activity tracking when network disconnects.
2391 */
2392 private void removeDataActivityTracking(int type) {
2393 final NetworkStateTracker net = mNetTrackers[type];
2394 final String iface = net.getLinkProperties().getInterfaceName();
2395
2396 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2397 ConnectivityManager.TYPE_WIFI == type)) {
2398 try {
2399 // the call fails silently if no idletimer setup for this interface
2400 mNetd.removeIdleTimer(iface);
2401 } catch (RemoteException e) {
2402 }
2403 }
2404 }
2405
2406 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002407 * After a change in the connectivity state of a network. We're mainly
2408 * concerned with making sure that the list of DNS servers is set up
2409 * according to which networks are connected, and ensuring that the
2410 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002411 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002412 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002413 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubaker49db4222013-07-15 16:34:04 -07002414 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002415 if (VDBG) {
2416 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2417 + " resetMask=" + resetMask);
2418 }
Wink Saville051a6642011-07-13 13:44:13 -07002419
The Android Open Source Project28527d22009-03-03 19:31:44 -08002420 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002421 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002422 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002423 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002424 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002425
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002426 LinkProperties curLp = mCurrentLinkProperties[netType];
2427 LinkProperties newLp = null;
2428
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002429 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002430 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002431 if (VDBG) {
2432 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2433 " doReset=" + doReset + " resetMask=" + resetMask +
2434 "\n curLp=" + curLp +
2435 "\n newLp=" + newLp);
2436 }
2437
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002438 if (curLp != null) {
2439 if (curLp.isIdenticalInterfaceName(newLp)) {
2440 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2441 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2442 for (LinkAddress linkAddr : car.removed) {
2443 if (linkAddr.getAddress() instanceof Inet4Address) {
2444 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2445 }
2446 if (linkAddr.getAddress() instanceof Inet6Address) {
2447 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2448 }
Wink Saville051a6642011-07-13 13:44:13 -07002449 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002450 if (DBG) {
2451 log("handleConnectivityChange: addresses changed" +
2452 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2453 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002454 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002455 } else {
2456 if (DBG) {
2457 log("handleConnectivityChange: address are the same reset per doReset" +
2458 " linkProperty[" + netType + "]:" +
2459 " resetMask=" + resetMask);
2460 }
Wink Saville051a6642011-07-13 13:44:13 -07002461 }
2462 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002463 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002464 if (DBG) {
2465 log("handleConnectivityChange: interface not not equivalent reset both" +
2466 " linkProperty[" + netType + "]:" +
2467 " resetMask=" + resetMask);
2468 }
Wink Saville051a6642011-07-13 13:44:13 -07002469 }
Wink Saville051a6642011-07-13 13:44:13 -07002470 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002471 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002472 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002473 }
2474 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002475 if (VDBG) {
2476 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2477 " doReset=" + doReset + " resetMask=" + resetMask +
2478 "\n curLp=" + curLp +
2479 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002480 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002481 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002482 mCurrentLinkProperties[netType] = newLp;
Chad Brubaker49db4222013-07-15 16:34:04 -07002483 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002484
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002485 if (resetMask != 0 || resetDns) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002486 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwalt4398f342013-05-23 18:33:06 -07002487 if (curLp != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002488 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwalt4398f342013-05-23 18:33:06 -07002489 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002490 if (TextUtils.isEmpty(iface) == false) {
2491 if (resetMask != 0) {
2492 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2493 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002494
Lorenzo Colitti63839822013-03-20 19:22:58 +09002495 // Tell VPN the interface is down. It is a temporary
2496 // but effective fix to make VPN aware of the change.
2497 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07002498 synchronized(mVpns) {
2499 for (int i = 0; i < mVpns.size(); i++) {
2500 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2501 }
2502 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002503 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002504 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002505 if (resetDns) {
2506 flushVmDnsCache();
2507 if (VDBG) log("resetting DNS cache for " + iface);
2508 try {
2509 mNetd.flushInterfaceDnsCache(iface);
2510 } catch (Exception e) {
2511 // never crash - catch them all
2512 if (DBG) loge("Exception resetting dns cache: " + e);
2513 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002514 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002515 } else {
2516 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002517 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002518 }
2519 }
2520 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002521
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002522 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002523 NetworkStateTracker tracker = mNetTrackers[netType];
2524 if (mClat.requiresClat(netType, tracker)) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002525
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002526 // If the connection was previously using clat, but is not using it now, stop the clat
2527 // daemon. Normally, this happens automatically when the connection disconnects, but if
2528 // the disconnect is not reported, or if the connection's LinkProperties changed for
2529 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2530 // still be running. If it's not running, then stopping it is a no-op.
2531 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2532 mClat.stopClat();
2533 }
2534 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002535 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2536 mClat.startClat(tracker);
2537 } else {
2538 mClat.stopClat();
2539 }
2540 }
2541
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002542 // TODO: Temporary notifying upstread change to Tethering.
2543 // @see bug/4455071
2544 /** Notify TetheringService if interface name has been changed. */
2545 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002546 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002547 if (isTetheringSupported()) {
2548 mTethering.handleTetherIfaceChange();
2549 }
2550 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002551 }
2552
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002553 /**
2554 * Add and remove routes using the old properties (null if not previously connected),
2555 * new properties (null if becoming disconnected). May even be double null, which
2556 * is a noop.
2557 * Uses isLinkDefault to determine if default routes should be set or conversely if
2558 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002559 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002560 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002561 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubaker49db4222013-07-15 16:34:04 -07002562 boolean isLinkDefault, boolean exempt) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002563 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002564 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2565 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002566 if (curLp != null) {
2567 // check for the delta between the current set and the new
Lorenzo Colittie1b47422013-07-31 23:23:21 +09002568 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002569 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002570 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002571 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002572 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002573 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002574
Robert Greenwalt8d777252011-08-15 12:31:55 -07002575 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2576
Robert Greenwalt98107422011-07-22 11:55:33 -07002577 for (RouteInfo r : routeDiff.removed) {
2578 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002579 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002580 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2581 }
2582 if (isLinkDefault == false) {
2583 // remove from a secondary route table
2584 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002585 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002586 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002587
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002588 if (!isLinkDefault) {
2589 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002590 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002591 // routes changed - remove all old dns entries and add new
2592 if (curLp != null) {
2593 for (InetAddress oldDns : curLp.getDnses()) {
2594 removeRouteToAddress(curLp, oldDns);
2595 }
2596 }
2597 if (newLp != null) {
2598 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002599 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07002600 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002601 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002602 } else {
2603 // no change in routes, check for change in dns themselves
2604 for (InetAddress oldDns : dnsDiff.removed) {
2605 removeRouteToAddress(curLp, oldDns);
2606 }
2607 for (InetAddress newDns : dnsDiff.added) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002608 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002609 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002610 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002611 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002612
2613 for (RouteInfo r : routeDiff.added) {
2614 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002615 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002616 } else {
2617 // add to a secondary route table
Chad Brubaker49db4222013-07-15 16:34:04 -07002618 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002619
2620 // many radios add a default route even when we don't want one.
2621 // remove the default route unless somebody else has asked for it
2622 String ifaceName = newLp.getInterfaceName();
Chad Brubaker49db4222013-07-15 16:34:04 -07002623 synchronized (mRoutesLock) {
2624 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2625 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2626 try {
2627 mNetd.removeRoute(ifaceName, r);
2628 } catch (Exception e) {
2629 // never crash - catch them all
2630 if (DBG) loge("Exception trying to remove a route: " + e);
2631 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002632 }
2633 }
2634 }
2635 }
2636
Robert Greenwalt8d777252011-08-15 12:31:55 -07002637 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002638 }
2639
sy.yun4aa73922013-09-02 05:24:09 +09002640 /**
2641 * Reads the network specific MTU size from reources.
2642 * and set it on it's iface.
2643 */
2644 private void updateMtuSizeSettings(NetworkStateTracker nt) {
2645 final String iface = nt.getLinkProperties().getInterfaceName();
2646 final int mtu = nt.getLinkProperties().getMtu();
2647
2648 if (mtu < 68 || mtu > 10000) {
2649 loge("Unexpected mtu value: " + nt);
2650 return;
2651 }
2652
2653 try {
2654 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2655 mNetd.setMtu(iface, mtu);
2656 } catch (Exception e) {
2657 Slog.e(TAG, "exception in setMtu()" + e);
2658 }
2659 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002660
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002661 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002662 * Reads the network specific TCP buffer sizes from SystemProperties
2663 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2664 * wide use
2665 */
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002666 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002667 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002668 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002669
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002670 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002671 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002672
2673 // Setting to default values so we won't be stuck to previous values
2674 key = "net.tcp.buffersize.default";
2675 bufferSizes = SystemProperties.get(key);
2676 }
2677
2678 // Set values in kernel
2679 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002680 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002681 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002682 + "] which comes from [" + key + "]");
2683 }
2684 setBufferSize(bufferSizes);
2685 }
2686 }
2687
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002688 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002689 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2690 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2691 *
2692 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2693 * writeMin, writeInitial, writeMax"
2694 */
2695 private void setBufferSize(String bufferSizes) {
2696 try {
2697 String[] values = bufferSizes.split(",");
2698
2699 if (values.length == 6) {
2700 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002701 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2702 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2703 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2704 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2705 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2706 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002707 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002708 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002709 }
2710 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002711 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002712 }
2713 }
2714
Robert Greenwalt2034b912009-08-12 16:08:25 -07002715 /**
2716 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2717 * on the highest priority active net which this process requested.
2718 * If there aren't any, clear it out
2719 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002720 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002721 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002722 if (VDBG) log("reassessPidDns for pid " + pid);
2723 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002724 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002725 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002726 continue;
2727 }
2728 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002729 if (nt.getNetworkInfo().isConnected() &&
2730 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002731 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002732 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002733 if (mNetRequestersPids[i].contains(myPid)) {
2734 try {
2735 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2736 } catch (Exception e) {
2737 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002738 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002739 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002740 }
2741 }
2742 }
2743 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002744 try {
2745 mNetd.clearDnsInterfaceForPid(pid);
2746 } catch (Exception e) {
2747 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002748 }
2749 }
2750
Mattias Falkd697aa22011-08-23 14:15:13 +02002751 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002752 /*
2753 * Tell the VMs to toss their DNS caches
2754 */
2755 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2756 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002757 /*
2758 * Connectivity events can happen before boot has completed ...
2759 */
2760 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002761 final long ident = Binder.clearCallingIdentity();
2762 try {
2763 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2764 } finally {
2765 Binder.restoreCallingIdentity(ident);
2766 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002767 }
2768
Chia-chi Yehcc844502011-07-14 18:01:57 -07002769 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002770 private void updateDnsLocked(String network, String iface,
Chad Brubaker73652d02013-07-23 17:13:36 -07002771 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002772 int last = 0;
2773 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002774 dnses = new ArrayList();
2775 dnses.add(mDefaultDns);
2776 if (DBG) {
2777 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002778 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002779 }
2780
Mattias Falkd697aa22011-08-23 14:15:13 +02002781 try {
2782 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker73652d02013-07-23 17:13:36 -07002783 if (defaultDns) {
2784 mNetd.setDefaultInterfaceForDns(iface);
2785 }
2786
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002787 for (InetAddress dns : dnses) {
2788 ++last;
2789 String key = "net.dns" + last;
2790 String value = dns.getHostAddress();
2791 SystemProperties.set(key, value);
2792 }
2793 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2794 String key = "net.dns" + i;
2795 SystemProperties.set(key, "");
2796 }
2797 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002798 } catch (Exception e) {
2799 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002800 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002801 }
2802
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002803 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002804 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002805 NetworkStateTracker nt = mNetTrackers[netType];
2806 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002807 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002808 if (p == null) return;
2809 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002810 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002811 String network = nt.getNetworkInfo().getTypeName();
2812 synchronized (mDnsLock) {
Chad Brubaker5fdc1462013-07-23 17:44:41 -07002813 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002814 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002815 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002816 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002817 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002818 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002819 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002820 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002821 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002822 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002823 List<Integer> pids = mNetRequestersPids[netType];
2824 for (Integer pid : pids) {
2825 try {
2826 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2827 } catch (Exception e) {
2828 Slog.e(TAG, "exception setting interface for pid: " + e);
2829 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002830 }
2831 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002832 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002833 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002834 }
2835
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002836 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002837 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2838 NETWORK_RESTORE_DELAY_PROP_NAME);
2839 if(restoreDefaultNetworkDelayStr != null &&
2840 restoreDefaultNetworkDelayStr.length() != 0) {
2841 try {
2842 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2843 } catch (NumberFormatException e) {
2844 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002845 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002846 // if the system property isn't set, use the value for the apn type
2847 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2848
2849 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2850 (mNetConfigs[networkType] != null)) {
2851 ret = mNetConfigs[networkType].restoreTime;
2852 }
2853 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002854 }
2855
2856 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002857 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2858 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002859 if (mContext.checkCallingOrSelfPermission(
2860 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002861 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002862 pw.println("Permission Denial: can't dump ConnectivityService " +
2863 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2864 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002865 return;
2866 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002867
2868 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002869 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002870 for (int i = 0; i < mNetTrackers.length; i++) {
2871 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002872 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002873 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2874 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002875 if (nst.getNetworkInfo().isConnected()) {
2876 pw.println("Active network: " + nst.getNetworkInfo().
2877 getTypeName());
2878 }
2879 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002880 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002881 pw.println(nst);
2882 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002883 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002884 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002885 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002886
2887 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002888 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002889 for (int net : mPriorityList) {
2890 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002891 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002892 pidString = pidString + pid.toString() + ", ";
2893 }
2894 pw.println(pidString);
2895 }
2896 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002897 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002898
2899 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002900 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002901 for (Object requester : mFeatureUsers) {
2902 pw.println(requester.toString());
2903 }
2904 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002905 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002906
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002907 synchronized (this) {
2908 pw.println("NetworkTranstionWakeLock is currently " +
2909 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2910 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2911 }
2912 pw.println();
2913
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002914 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002915
2916 if (mInetLog != null) {
2917 pw.println();
2918 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002919 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002920 for(int i = 0; i < mInetLog.size(); i++) {
2921 pw.println(mInetLog.get(i));
2922 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002923 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002924 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002925 }
2926
Robert Greenwalt2034b912009-08-12 16:08:25 -07002927 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002928 private class NetworkStateTrackerHandler extends Handler {
2929 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002930 super(looper);
2931 }
2932
The Android Open Source Project28527d22009-03-03 19:31:44 -08002933 @Override
2934 public void handleMessage(Message msg) {
2935 NetworkInfo info;
2936 switch (msg.what) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002937 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002938 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002939 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002940
Wink Savillea7d56572011-09-21 11:05:43 -07002941 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Savilleb1a32022013-09-05 12:02:25 -07002942 (state == NetworkInfo.State.DISCONNECTED) ||
2943 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07002944 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002945 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002946 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002947 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002948
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002949 // Since mobile has the notion of a network/apn that can be used for
2950 // provisioning we need to check every time we're connected as
2951 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2952 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2953 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2954 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2955 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002956 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2957 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Savilleb1a32022013-09-05 12:02:25 -07002958 && ((state == NetworkInfo.State.CONNECTED)
2959 || info.isConnectedToProvisioningNetwork())) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002960 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002961 }
2962
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002963 EventLogTags.writeConnectivityStateChanged(
2964 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002965
2966 if (info.getDetailedState() ==
2967 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002968 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002969 } else if (info.getDetailedState() ==
2970 DetailedState.CAPTIVE_PORTAL_CHECK) {
2971 handleCaptivePortalTrackerCheck(info);
Wink Savilleb1a32022013-09-05 12:02:25 -07002972 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002973 /**
2974 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2975 * for now its an in between network, its a network that
2976 * is actually a default network but we don't want it to be
2977 * announced as such to keep background applications from
2978 * trying to use it. It turns out that some still try so we
2979 * take the additional step of clearing any default routes
2980 * to the link that may have incorrectly setup by the lower
2981 * levels.
2982 */
2983 LinkProperties lp = getLinkProperties(info.getType());
2984 if (DBG) {
2985 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2986 }
2987
2988 // Clear any default routes setup by the radio so
2989 // any activity by applications trying to use this
2990 // connection will fail until the provisioning network
2991 // is enabled.
2992 for (RouteInfo r : lp.getRoutes()) {
2993 removeRoute(lp, r, TO_DEFAULT_TABLE);
2994 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08002995 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002996 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002997 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002998 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002999 // the logic here is, handle SUSPENDED the same as
3000 // DISCONNECTED. The only difference being we are
3001 // broadcasting an intent with NetworkInfo that's
3002 // suspended. This allows the applications an
3003 // opportunity to handle DISCONNECTED and SUSPENDED
3004 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08003005 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08003006 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003007 handleConnect(info);
3008 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003009 if (mLockdownTracker != null) {
3010 mLockdownTracker.onNetworkInfoChanged(info);
3011 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003012 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003013 }
3014 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07003015 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05003016 // TODO: Temporary allowing network configuration
3017 // change not resetting sockets.
3018 // @see bug/4455071
3019 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003020 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003021 }
3022 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07003023 info = (NetworkInfo) msg.obj;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003024 int type = info.getType();
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07003025 updateNetworkSettings(mNetTrackers[type]);
3026 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003027 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003028 }
3029 }
3030 }
3031
3032 private class InternalHandler extends Handler {
3033 public InternalHandler(Looper looper) {
3034 super(looper);
3035 }
3036
3037 @Override
3038 public void handleMessage(Message msg) {
3039 NetworkInfo info;
3040 switch (msg.what) {
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003041 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003042 String causedBy = null;
3043 synchronized (ConnectivityService.this) {
3044 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3045 mNetTransitionWakeLock.isHeld()) {
3046 mNetTransitionWakeLock.release();
3047 causedBy = mNetTransitionWakeLockCausedBy;
3048 }
3049 }
3050 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003051 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003052 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07003053 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003054 }
3055 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003056 FeatureUser u = (FeatureUser)msg.obj;
3057 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003058 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003059 }
3060 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003061 int netType = msg.arg1;
3062 int condition = msg.arg2;
3063 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003064 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003065 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003066 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003067 int netType = msg.arg1;
3068 int sequence = msg.arg2;
Wink Saville151eaa62013-01-31 00:30:13 +00003069 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07003070 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003071 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003072 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003073 int preference = msg.arg1;
3074 handleSetNetworkPreference(preference);
3075 break;
3076 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003077 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003078 boolean enabled = (msg.arg1 == ENABLED);
3079 handleSetMobileData(enabled);
3080 break;
3081 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003082 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003083 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07003084 break;
3085 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003086 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwalt34848c02011-03-25 13:09:25 -07003087 boolean met = (msg.arg1 == ENABLED);
3088 handleSetDependencyMet(msg.arg2, met);
3089 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003090 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003091 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville4f0de1e2011-08-04 15:01:58 -07003092 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07003093 sendStickyBroadcast(intent);
3094 break;
3095 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07003096 case EVENT_SET_POLICY_DATA_ENABLE: {
3097 final int networkType = msg.arg1;
3098 final boolean enabled = msg.arg2 == ENABLED;
3099 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003100 break;
3101 }
3102 case EVENT_VPN_STATE_CHANGED: {
3103 if (mLockdownTracker != null) {
3104 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3105 }
3106 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07003107 }
Wink Saville32506bc2013-06-29 21:10:57 -07003108 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3109 int tag = mEnableFailFastMobileDataTag.get();
3110 if (msg.arg1 == tag) {
3111 MobileDataStateTracker mobileDst =
3112 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3113 if (mobileDst != null) {
3114 mobileDst.setEnableFailFastMobileData(msg.arg2);
3115 }
3116 } else {
3117 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3118 + " != tag:" + tag);
3119 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003120 break;
Wink Saville32506bc2013-06-29 21:10:57 -07003121 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003122 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07003123 handleNetworkSamplingTimeout();
3124 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003125 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003126 }
3127 }
3128 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003129
3130 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003131 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003132 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003133
3134 if (isTetheringSupported()) {
3135 return mTethering.tether(iface);
3136 } else {
3137 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3138 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003139 }
3140
3141 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003142 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003143 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003144
3145 if (isTetheringSupported()) {
3146 return mTethering.untether(iface);
3147 } else {
3148 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3149 }
3150 }
3151
3152 // javadoc from interface
3153 public int getLastTetherError(String iface) {
3154 enforceTetherAccessPermission();
3155
3156 if (isTetheringSupported()) {
3157 return mTethering.getLastTetherError(iface);
3158 } else {
3159 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3160 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003161 }
3162
3163 // TODO - proper iface API for selection by property, inspection, etc
3164 public String[] getTetherableUsbRegexs() {
3165 enforceTetherAccessPermission();
3166 if (isTetheringSupported()) {
3167 return mTethering.getTetherableUsbRegexs();
3168 } else {
3169 return new String[0];
3170 }
3171 }
3172
3173 public String[] getTetherableWifiRegexs() {
3174 enforceTetherAccessPermission();
3175 if (isTetheringSupported()) {
3176 return mTethering.getTetherableWifiRegexs();
3177 } else {
3178 return new String[0];
3179 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003180 }
3181
Danica Chang96567052010-08-11 14:54:43 -07003182 public String[] getTetherableBluetoothRegexs() {
3183 enforceTetherAccessPermission();
3184 if (isTetheringSupported()) {
3185 return mTethering.getTetherableBluetoothRegexs();
3186 } else {
3187 return new String[0];
3188 }
3189 }
3190
Mike Lockwooded4a1742011-07-19 13:04:47 -07003191 public int setUsbTethering(boolean enable) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003192 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07003193 if (isTetheringSupported()) {
3194 return mTethering.setUsbTethering(enable);
3195 } else {
3196 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3197 }
3198 }
3199
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003200 // TODO - move iface listing, queries, etc to new module
3201 // javadoc from interface
3202 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003203 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003204 return mTethering.getTetherableIfaces();
3205 }
3206
3207 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003208 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003209 return mTethering.getTetheredIfaces();
3210 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003211
Jeff Sharkey300f08f2011-09-16 01:52:49 -07003212 @Override
3213 public String[] getTetheredIfacePairs() {
3214 enforceTetherAccessPermission();
3215 return mTethering.getTetheredIfacePairs();
3216 }
3217
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003218 public String[] getTetheringErroredIfaces() {
3219 enforceTetherAccessPermission();
3220 return mTethering.getErroredIfaces();
3221 }
3222
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003223 // if ro.tether.denied = true we default to no tethering
3224 // gservices could set the secure setting to 1 though to enable it on a build where it
3225 // had previously been turned off.
3226 public boolean isTetheringSupported() {
3227 enforceTetherAccessPermission();
3228 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownc67cf562012-09-25 15:03:20 -07003229 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3230 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt368095f2013-07-18 14:24:42 -07003231 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3232 mTethering.getTetherableWifiRegexs().length != 0 ||
3233 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3234 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003235 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003236
3237 // An API NetworkStateTrackers can call when they lose their network.
3238 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3239 // whichever happens first. The timer is started by the first caller and not
3240 // restarted by subsequent callers.
3241 public void requestNetworkTransitionWakelock(String forWhom) {
3242 enforceConnectivityInternalPermission();
3243 synchronized (this) {
3244 if (mNetTransitionWakeLock.isHeld()) return;
3245 mNetTransitionWakeLockSerialNumber++;
3246 mNetTransitionWakeLock.acquire();
3247 mNetTransitionWakeLockCausedBy = forWhom;
3248 }
3249 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003250 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003251 mNetTransitionWakeLockSerialNumber, 0),
3252 mNetTransitionWakeLockTimeout);
3253 return;
3254 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003255
Robert Greenwalt986c7412010-09-08 15:24:47 -07003256 // 100 percent is full good, 0 is full bad.
3257 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003258 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003259 mContext.enforceCallingOrSelfPermission(
3260 android.Manifest.permission.STATUS_BAR,
3261 "ConnectivityService");
3262
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003263 if (DBG) {
3264 int pid = getCallingPid();
3265 int uid = getCallingUid();
3266 String s = pid + "(" + uid + ") reports inet is " +
3267 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3268 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3269 mInetLog.add(s);
3270 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3271 mInetLog.remove(0);
3272 }
3273 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003274 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003275 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3276 }
3277
3278 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003279 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003280 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003281 return;
3282 }
3283 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003284 if (DBG) log("handleInetConditionChange: net=" + netType +
3285 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003286 return;
3287 }
Wink Savillea7d56572011-09-21 11:05:43 -07003288 if (VDBG) {
3289 log("handleInetConditionChange: net=" +
3290 netType + ", condition=" + condition +
Wink Saville151eaa62013-01-31 00:30:13 +00003291 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003292 }
Wink Saville151eaa62013-01-31 00:30:13 +00003293 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003294 int delay;
3295 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003296 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003297 // setup a new hold to debounce this
Wink Saville151eaa62013-01-31 00:30:13 +00003298 if (mDefaultInetCondition > 50) {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003299 delay = Settings.Global.getInt(mContext.getContentResolver(),
3300 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003301 } else {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003302 delay = Settings.Global.getInt(mContext.getContentResolver(),
3303 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003304 }
3305 mInetConditionChangeInFlight = true;
3306 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville151eaa62013-01-31 00:30:13 +00003307 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003308 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003309 // we've set the new condition, when this hold ends that will get picked up
3310 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003311 }
3312 }
3313
Wink Saville151eaa62013-01-31 00:30:13 +00003314 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003315 if (DBG) {
Wink Saville151eaa62013-01-31 00:30:13 +00003316 log("handleInetConditionHoldEnd: net=" + netType +
3317 ", condition=" + mDefaultInetCondition +
3318 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003319 }
3320 mInetConditionChangeInFlight = false;
3321
3322 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003323 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003324 return;
3325 }
3326 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003327 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003328 return;
3329 }
Wink Saville151eaa62013-01-31 00:30:13 +00003330 // TODO: Figure out why this optimization sometimes causes a
3331 // change in mDefaultInetCondition to be missed and the
3332 // UI to not be updated.
3333 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3334 // if (DBG) log("no change in condition - aborting");
3335 // return;
3336 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003337 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3338 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003339 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003340 return;
3341 }
Wink Saville151eaa62013-01-31 00:30:13 +00003342 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003343 sendInetConditionBroadcast(networkInfo);
3344 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003345 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003346
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003347 public ProxyProperties getProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003348 // this information is already available as a world read/writable jvm property
3349 // so this API change wouldn't have a benifit. It also breaks the passing
3350 // of proxy info to all the JVMs.
3351 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003352 synchronized (mProxyLock) {
Jason Monka5bf2842013-07-03 17:04:33 -04003353 ProxyProperties ret = mGlobalProxy;
3354 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3355 return ret;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003356 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003357 }
3358
3359 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003360 enforceConnectivityInternalPermission();
Jason Monka5bf2842013-07-03 17:04:33 -04003361
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003362 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003363 if (proxyProperties == mGlobalProxy) return;
3364 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3365 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3366
3367 String host = "";
3368 int port = 0;
3369 String exclList = "";
Jason Monka5bf2842013-07-03 17:04:33 -04003370 String pacFileUrl = "";
3371 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3372 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003373 mGlobalProxy = new ProxyProperties(proxyProperties);
3374 host = mGlobalProxy.getHost();
3375 port = mGlobalProxy.getPort();
3376 exclList = mGlobalProxy.getExclusionList();
Jason Monka5bf2842013-07-03 17:04:33 -04003377 if (proxyProperties.getPacFileUrl() != null) {
3378 pacFileUrl = proxyProperties.getPacFileUrl();
3379 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003380 } else {
3381 mGlobalProxy = null;
3382 }
3383 ContentResolver res = mContext.getContentResolver();
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003384 final long token = Binder.clearCallingIdentity();
3385 try {
3386 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3387 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3388 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3389 exclList);
Jason Monka5bf2842013-07-03 17:04:33 -04003390 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003391 } finally {
3392 Binder.restoreCallingIdentity(token);
3393 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003394 }
3395
3396 if (mGlobalProxy == null) {
3397 proxyProperties = mDefaultProxy;
3398 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003399 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003400 }
3401
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003402 private void loadGlobalProxy() {
3403 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003404 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3405 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3406 String exclList = Settings.Global.getString(res,
3407 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monka5bf2842013-07-03 17:04:33 -04003408 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3409 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3410 ProxyProperties proxyProperties;
3411 if (!TextUtils.isEmpty(pacFileUrl)) {
3412 proxyProperties = new ProxyProperties(pacFileUrl);
3413 } else {
3414 proxyProperties = new ProxyProperties(host, port, exclList);
3415 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003416 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003417 mGlobalProxy = proxyProperties;
3418 }
3419 }
3420 }
3421
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003422 public ProxyProperties getGlobalProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003423 // this information is already available as a world read/writable jvm property
3424 // so this API change wouldn't have a benifit. It also breaks the passing
3425 // of proxy info to all the JVMs.
3426 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003427 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003428 return mGlobalProxy;
3429 }
3430 }
3431
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003432 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04003433 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3434 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003435 proxy = null;
3436 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003437 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003438 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003439 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003440 mDefaultProxy = proxy;
3441
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003442 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003443 if (!mDefaultProxyDisabled) {
3444 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003445 }
3446 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003447 }
3448
3449 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003450 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3451 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003452 if (!TextUtils.isEmpty(proxy)) {
3453 String data[] = proxy.split(":");
Andreas Huber23bff232013-05-28 15:17:37 -07003454 if (data.length == 0) {
3455 return;
3456 }
3457
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003458 String proxyHost = data[0];
3459 int proxyPort = 8080;
3460 if (data.length > 1) {
3461 try {
3462 proxyPort = Integer.parseInt(data[1]);
3463 } catch (NumberFormatException e) {
3464 return;
3465 }
3466 }
3467 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3468 setGlobalProxy(p);
3469 }
3470 }
3471
3472 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003473 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monka5bf2842013-07-03 17:04:33 -04003474 mPacManager.setCurrentProxyScriptUrl(proxy);
Robert Greenwalt78f28112011-08-02 17:18:41 -07003475 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003476 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003477 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3478 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003479 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003480 final long ident = Binder.clearCallingIdentity();
3481 try {
3482 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3483 } finally {
3484 Binder.restoreCallingIdentity(ident);
3485 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003486 }
3487
3488 private static class SettingsObserver extends ContentObserver {
3489 private int mWhat;
3490 private Handler mHandler;
3491 SettingsObserver(Handler handler, int what) {
3492 super(handler);
3493 mHandler = handler;
3494 mWhat = what;
3495 }
3496
3497 void observe(Context context) {
3498 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003499 resolver.registerContentObserver(Settings.Global.getUriFor(
3500 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003501 }
3502
3503 @Override
3504 public void onChange(boolean selfChange) {
3505 mHandler.obtainMessage(mWhat).sendToTarget();
3506 }
3507 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003508
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003509 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003510 Slog.d(TAG, s);
3511 }
3512
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003513 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003514 Slog.e(TAG, s);
3515 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003516
repo syncf5de5572011-07-29 23:55:49 -07003517 int convertFeatureToNetworkType(int networkType, String feature) {
3518 int usedNetworkType = networkType;
3519
3520 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3521 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3522 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3523 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3524 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3525 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3526 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3527 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3528 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3529 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3530 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3531 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3532 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3533 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3534 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3535 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3536 } else {
3537 Slog.e(TAG, "Can't match any mobile netTracker!");
3538 }
3539 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3540 if (TextUtils.equals(feature, "p2p")) {
3541 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3542 } else {
3543 Slog.e(TAG, "Can't match any wifi netTracker!");
3544 }
3545 } else {
3546 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003547 }
repo syncf5de5572011-07-29 23:55:49 -07003548 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003549 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003550
3551 private static <T> T checkNotNull(T value, String message) {
3552 if (value == null) {
3553 throw new NullPointerException(message);
3554 }
3555 return value;
3556 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003557
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003558 /**
3559 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003560 * VpnBuilder and not available in ConnectivityManager. Permissions
3561 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003562 * @hide
3563 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003564 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003565 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003566 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003567 try {
3568 int type = mActiveDefaultNetwork;
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003569 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt15a41532012-08-21 19:27:00 -07003570 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003571 synchronized(mVpns) {
3572 mVpns.get(user).protect(socket,
3573 mNetTrackers[type].getLinkProperties().getInterfaceName());
3574 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003575 return true;
3576 }
3577 } catch (Exception e) {
3578 // ignore
3579 } finally {
3580 try {
3581 socket.close();
3582 } catch (Exception e) {
3583 // ignore
3584 }
3585 }
3586 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003587 }
3588
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003589 /**
3590 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003591 * and not available in ConnectivityManager. Permissions are checked
3592 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003593 * @hide
3594 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003595 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003596 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003597 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003598 int user = UserHandle.getUserId(Binder.getCallingUid());
3599 synchronized(mVpns) {
3600 return mVpns.get(user).prepare(oldPackage, newPackage);
3601 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003602 }
3603
Chad Brubaker11f22252013-07-11 13:29:30 -07003604 @Override
3605 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3606 enforceMarkNetworkSocketPermission();
3607 final long token = Binder.clearCallingIdentity();
3608 try {
3609 int mark = mNetd.getMarkForUid(uid);
3610 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3611 if (mark == -1) {
3612 mark = 0;
3613 }
3614 NetworkUtils.markSocket(socket.getFd(), mark);
3615 } catch (RemoteException e) {
3616 } finally {
3617 Binder.restoreCallingIdentity(token);
3618 }
3619 }
3620
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003621 /**
3622 * Configure a TUN interface and return its file descriptor. Parameters
3623 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003624 * and not available in ConnectivityManager. Permissions are checked in
3625 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003626 * @hide
3627 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003628 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003629 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003630 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003631 int user = UserHandle.getUserId(Binder.getCallingUid());
3632 synchronized(mVpns) {
3633 return mVpns.get(user).establish(config);
3634 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003635 }
3636
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003637 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003638 * Start legacy VPN, controlling native daemons as needed. Creates a
3639 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003640 */
3641 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003642 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003643 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003644 final LinkProperties egress = getActiveLinkProperties();
3645 if (egress == null) {
3646 throw new IllegalStateException("Missing active network connection");
3647 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003648 int user = UserHandle.getUserId(Binder.getCallingUid());
3649 synchronized(mVpns) {
3650 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3651 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003652 }
3653
3654 /**
3655 * Return the information of the ongoing legacy VPN. This method is used
3656 * by VpnSettings and not available in ConnectivityManager. Permissions
3657 * are checked in Vpn class.
3658 * @hide
3659 */
3660 @Override
3661 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003662 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003663 int user = UserHandle.getUserId(Binder.getCallingUid());
3664 synchronized(mVpns) {
3665 return mVpns.get(user).getLegacyVpnInfo();
3666 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003667 }
3668
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003669 /**
Chad Brubaker94f3c8c2013-07-16 18:59:12 -07003670 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3671 * not available in ConnectivityManager.
3672 * Permissions are checked in Vpn class.
3673 * @hide
3674 */
3675 @Override
3676 public VpnConfig getVpnConfig() {
3677 int user = UserHandle.getUserId(Binder.getCallingUid());
3678 synchronized(mVpns) {
3679 return mVpns.get(user).getVpnConfig();
3680 }
3681 }
3682
3683 /**
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003684 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3685 * through NetworkStateTracker since it works differently. For example, it
3686 * needs to override DNS servers but never takes the default routes. It
3687 * relies on another data network, and it could keep existing connections
3688 * alive after reconnecting, switching between networks, or even resuming
3689 * from deep sleep. Calls from applications should be done synchronously
3690 * to avoid race conditions. As these are all hidden APIs, refactoring can
3691 * be done whenever a better abstraction is developed.
3692 */
3693 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003694 private VpnCallback() {
3695 }
3696
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003697 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003698 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003699 }
3700
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003701 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003702 if (dnsServers == null) {
3703 restore();
3704 return;
3705 }
3706
3707 // Convert DNS servers into addresses.
3708 List<InetAddress> addresses = new ArrayList<InetAddress>();
3709 for (String address : dnsServers) {
3710 // Double check the addresses and remove invalid ones.
3711 try {
3712 addresses.add(InetAddress.parseNumericAddress(address));
3713 } catch (Exception e) {
3714 // ignore
3715 }
3716 }
3717 if (addresses.isEmpty()) {
3718 restore();
3719 return;
3720 }
3721
3722 // Concatenate search domains into a string.
3723 StringBuilder buffer = new StringBuilder();
3724 if (searchDomains != null) {
3725 for (String domain : searchDomains) {
3726 buffer.append(domain).append(' ');
3727 }
3728 }
3729 String domains = buffer.toString().trim();
3730
3731 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003732 synchronized (mDnsLock) {
Chad Brubaker73652d02013-07-23 17:13:36 -07003733 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003734 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003735
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003736 // Temporarily disable the default proxy (not global).
3737 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003738 mDefaultProxyDisabled = true;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003739 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003740 sendProxyBroadcast(null);
3741 }
3742 }
3743
3744 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003745 }
3746
Chia-chi Yehcc844502011-07-14 18:01:57 -07003747 public void restore() {
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003748 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003749 mDefaultProxyDisabled = false;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003750 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003751 sendProxyBroadcast(mDefaultProxy);
3752 }
3753 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003754 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003755
3756 public void protect(ParcelFileDescriptor socket) {
3757 try {
3758 final int mark = mNetd.getMarkForProtect();
3759 NetworkUtils.markSocket(socket.getFd(), mark);
3760 } catch (RemoteException e) {
3761 }
3762 }
3763
3764 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3765 for (RouteInfo route : routes) {
3766 try {
3767 mNetd.setMarkedForwardingRoute(interfaze, route);
3768 } catch (RemoteException e) {
3769 }
3770 }
3771 }
3772
3773 public void setMarkedForwarding(String interfaze) {
3774 try {
3775 mNetd.setMarkedForwarding(interfaze);
3776 } catch (RemoteException e) {
3777 }
3778 }
3779
3780 public void clearMarkedForwarding(String interfaze) {
3781 try {
3782 mNetd.clearMarkedForwarding(interfaze);
3783 } catch (RemoteException e) {
3784 }
3785 }
3786
3787 public void addUserForwarding(String interfaze, int uid) {
3788 int uidStart = uid * UserHandle.PER_USER_RANGE;
3789 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3790 addUidForwarding(interfaze, uidStart, uidEnd);
3791 }
3792
3793 public void clearUserForwarding(String interfaze, int uid) {
3794 int uidStart = uid * UserHandle.PER_USER_RANGE;
3795 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3796 clearUidForwarding(interfaze, uidStart, uidEnd);
3797 }
3798
3799 public void addUidForwarding(String interfaze, int uidStart, int uidEnd) {
3800 try {
3801 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3802 mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3803 } catch (RemoteException e) {
3804 }
3805
3806 }
3807
3808 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd) {
3809 try {
3810 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3811 mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3812 } catch (RemoteException e) {
3813 }
3814
3815 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003816 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003817
3818 @Override
3819 public boolean updateLockdownVpn() {
Jeff Sharkey760c6202013-01-31 17:22:26 -08003820 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3821 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3822 return false;
3823 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003824
3825 // Tear down existing lockdown if profile was removed
3826 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3827 if (mLockdownEnabled) {
Kenny Root0ded63c2013-02-14 10:18:38 -08003828 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003829 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3830 return false;
3831 }
3832
3833 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3834 final VpnProfile profile = VpnProfile.decode(
3835 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003836 int user = UserHandle.getUserId(Binder.getCallingUid());
3837 synchronized(mVpns) {
3838 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3839 profile));
3840 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003841 } else {
3842 setLockdownTracker(null);
3843 }
3844
3845 return true;
3846 }
3847
3848 /**
3849 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3850 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3851 */
3852 private void setLockdownTracker(LockdownVpnTracker tracker) {
3853 // Shutdown any existing tracker
3854 final LockdownVpnTracker existing = mLockdownTracker;
3855 mLockdownTracker = null;
3856 if (existing != null) {
3857 existing.shutdown();
3858 }
3859
3860 try {
3861 if (tracker != null) {
3862 mNetd.setFirewallEnabled(true);
Jeff Sharkeydb44d2c2013-02-28 16:57:58 -08003863 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003864 mLockdownTracker = tracker;
3865 mLockdownTracker.init();
3866 } else {
3867 mNetd.setFirewallEnabled(false);
3868 }
3869 } catch (RemoteException e) {
3870 // ignored; NMS lives inside system_server
3871 }
3872 }
3873
3874 private void throwIfLockdownEnabled() {
3875 if (mLockdownEnabled) {
3876 throw new IllegalStateException("Unavailable in lockdown mode");
3877 }
3878 }
Robert Greenwalt15a41532012-08-21 19:27:00 -07003879
3880 public void supplyMessenger(int networkType, Messenger messenger) {
3881 enforceConnectivityInternalPermission();
3882
3883 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3884 mNetTrackers[networkType].supplyMessenger(messenger);
3885 }
3886 }
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -07003887
3888 public int findConnectionTypeForIface(String iface) {
3889 enforceConnectivityInternalPermission();
3890
3891 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3892 for (NetworkStateTracker tracker : mNetTrackers) {
3893 if (tracker != null) {
3894 LinkProperties lp = tracker.getLinkProperties();
3895 if (lp != null && iface.equals(lp.getInterfaceName())) {
3896 return tracker.getNetworkInfo().getType();
3897 }
3898 }
3899 }
3900 return ConnectivityManager.TYPE_NONE;
3901 }
Wink Saville32506bc2013-06-29 21:10:57 -07003902
3903 /**
3904 * Have mobile data fail fast if enabled.
3905 *
3906 * @param enabled DctConstants.ENABLED/DISABLED
3907 */
3908 private void setEnableFailFastMobileData(int enabled) {
3909 int tag;
3910
3911 if (enabled == DctConstants.ENABLED) {
3912 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3913 } else {
3914 tag = mEnableFailFastMobileDataTag.get();
3915 }
3916 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3917 enabled));
3918 }
3919
Wink Savilled23fa092013-08-16 17:17:28 -07003920 private boolean isMobileDataStateTrackerReady() {
3921 MobileDataStateTracker mdst =
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003922 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savilled23fa092013-08-16 17:17:28 -07003923 return (mdst != null) && (mdst.isReady());
3924 }
3925
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003926 /**
3927 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3928 */
3929
3930 /**
3931 * No connection was possible to the network.
Wink Saville9685cd12013-09-06 09:53:08 -07003932 * This is NOT a warm sim.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003933 */
Wink Saville9685cd12013-09-06 09:53:08 -07003934 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003935
3936 /**
3937 * A connection was made to the internet, all is well.
Wink Saville9685cd12013-09-06 09:53:08 -07003938 * This is NOT a warm sim.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003939 */
Wink Saville9685cd12013-09-06 09:53:08 -07003940 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003941
3942 /**
3943 * A connection was made but no dns server was available to resolve a name to address.
Wink Saville9685cd12013-09-06 09:53:08 -07003944 * This is NOT a warm sim since provisioning network is supported.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003945 */
Wink Saville9685cd12013-09-06 09:53:08 -07003946 private static final int CMP_RESULT_CODE_NO_DNS = 2;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003947
3948 /**
3949 * A connection was made but could not open a TCP connection.
Wink Saville9685cd12013-09-06 09:53:08 -07003950 * This is NOT a warm sim since provisioning network is supported.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003951 */
Wink Saville9685cd12013-09-06 09:53:08 -07003952 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3953
3954 /**
3955 * A connection was made but there was a redirection, we appear to be in walled garden.
3956 * This is an indication of a warm sim on a mobile network such as T-Mobile.
3957 */
3958 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003959
3960 /**
3961 * The mobile network is a provisioning network.
Wink Saville9685cd12013-09-06 09:53:08 -07003962 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003963 */
Wink Saville9685cd12013-09-06 09:53:08 -07003964 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003965
Wink Saville9685cd12013-09-06 09:53:08 -07003966 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003967
Wink Saville32506bc2013-06-29 21:10:57 -07003968 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003969 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3970 int timeOutMs = -1;
3971 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3972 enforceConnectivityInternalPermission();
Wink Savilled469c472013-07-02 10:55:14 -07003973
Wink Saville32506bc2013-06-29 21:10:57 -07003974 final long token = Binder.clearCallingIdentity();
3975 try {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003976 timeOutMs = suggestedTimeOutMs;
3977 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3978 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3979 }
3980
3981 // Check that mobile networks are supported
3982 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3983 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3984 if (DBG) log("checkMobileProvisioning: X no mobile network");
3985 return timeOutMs;
3986 }
3987
3988 // If we're already checking don't do it again
3989 // TODO: Add a queue of results...
3990 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
3991 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
3992 return timeOutMs;
3993 }
3994
3995 // Start off with notification off
3996 setProvNotificationVisible(false, ConnectivityManager.TYPE_NONE, null, null);
3997
3998 // See if we've alreadying determined if we've got a provsioning connection
3999 // if so we don't need to do anything active
4000 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4001 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4002 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4003
4004 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4005 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4006 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4007
4008 if (isDefaultProvisioning || isHipriProvisioning) {
4009 if (mIsNotificationVisible) {
4010 if (DBG) {
4011 log("checkMobileProvisioning: provisioning-ignore notification is visible");
4012 }
4013 } else {
4014 NetworkInfo ni = null;
4015 if (isDefaultProvisioning) {
4016 ni = mdstDefault.getNetworkInfo();
4017 }
4018 if (isHipriProvisioning) {
4019 ni = mdstHipri.getNetworkInfo();
4020 }
4021 String url = getMobileProvisioningUrl();
4022 if ((ni != null) && (!TextUtils.isEmpty(url))) {
4023 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(), url);
4024 } else {
4025 if (DBG) log("checkMobileProvisioning: provisioning but no url, ignore");
4026 }
4027 }
4028 mIsCheckingMobileProvisioning.set(false);
4029 return timeOutMs;
4030 }
4031
Wink Saville32506bc2013-06-29 21:10:57 -07004032 CheckMp checkMp = new CheckMp(mContext, this);
4033 CheckMp.CallBack cb = new CheckMp.CallBack() {
4034 @Override
4035 void onComplete(Integer result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004036 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville32506bc2013-06-29 21:10:57 -07004037 NetworkInfo ni =
4038 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4039 switch(result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004040 case CMP_RESULT_CODE_CONNECTABLE:
Wink Saville9685cd12013-09-06 09:53:08 -07004041 case CMP_RESULT_CODE_NO_CONNECTION:
4042 case CMP_RESULT_CODE_NO_DNS:
4043 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004044 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville32506bc2013-06-29 21:10:57 -07004045 break;
4046 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004047 case CMP_RESULT_CODE_REDIRECTED: {
4048 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt39d56012013-07-16 12:06:09 -07004049 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004050 if (TextUtils.isEmpty(url)) {
Robert Greenwalt39d56012013-07-16 12:06:09 -07004051 url = getMobileRedirectedProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004052 }
4053 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004054 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
4055 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(),
4056 url);
Wink Saville32506bc2013-06-29 21:10:57 -07004057 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004058 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07004059 }
4060 break;
4061 }
Wink Saville9685cd12013-09-06 09:53:08 -07004062 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalt39d56012013-07-16 12:06:09 -07004063 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004064 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004065 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
4066 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(),
4067 url);
Wink Saville32506bc2013-06-29 21:10:57 -07004068 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004069 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07004070 }
4071 break;
4072 }
4073 default: {
4074 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4075 break;
4076 }
4077 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004078 mIsCheckingMobileProvisioning.set(false);
Wink Saville32506bc2013-06-29 21:10:57 -07004079 }
4080 };
4081 CheckMp.Params params =
4082 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004083 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville32506bc2013-06-29 21:10:57 -07004084 checkMp.execute(params);
4085 } finally {
4086 Binder.restoreCallingIdentity(token);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004087 if (DBG) log("checkMobileProvisioning: X");
Wink Saville32506bc2013-06-29 21:10:57 -07004088 }
4089 return timeOutMs;
4090 }
4091
4092 static class CheckMp extends
4093 AsyncTask<CheckMp.Params, Void, Integer> {
4094 private static final String CHECKMP_TAG = "CheckMp";
4095 public static final int MAX_TIMEOUT_MS = 60000;
4096 private static final int SOCKET_TIMEOUT_MS = 5000;
4097 private Context mContext;
4098 private ConnectivityService mCs;
4099 private TelephonyManager mTm;
4100 private Params mParams;
4101
4102 /**
4103 * Parameters for AsyncTask.execute
4104 */
4105 static class Params {
4106 private String mUrl;
4107 private long mTimeOutMs;
4108 private CallBack mCb;
4109
4110 Params(String url, long timeOutMs, CallBack cb) {
4111 mUrl = url;
4112 mTimeOutMs = timeOutMs;
4113 mCb = cb;
4114 }
4115
4116 @Override
4117 public String toString() {
4118 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4119 }
4120 }
4121
4122 /**
4123 * The call back object passed in Params. onComplete will be called
4124 * on the main thread.
4125 */
4126 abstract static class CallBack {
4127 // Called on the main thread.
4128 abstract void onComplete(Integer result);
4129 }
4130
4131 public CheckMp(Context context, ConnectivityService cs) {
4132 mContext = context;
4133 mCs = cs;
4134
4135 // Setup access to TelephonyService we'll be using.
4136 mTm = (TelephonyManager) mContext.getSystemService(
4137 Context.TELEPHONY_SERVICE);
4138 }
4139
4140 /**
4141 * Get the default url to use for the test.
4142 */
4143 public String getDefaultUrl() {
4144 // See http://go/clientsdns for usage approval
4145 String server = Settings.Global.getString(mContext.getContentResolver(),
4146 Settings.Global.CAPTIVE_PORTAL_SERVER);
4147 if (server == null) {
4148 server = "clients3.google.com";
4149 }
4150 return "http://" + server + "/generate_204";
4151 }
4152
4153 /**
4154 * Detect if its possible to connect to the http url. DNS based detection techniques
4155 * do not work at all hotspots. The best way to check is to perform a request to
4156 * a known address that fetches the data we expect.
4157 */
4158 private synchronized Integer isMobileOk(Params params) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004159 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004160 Uri orgUri = Uri.parse(params.mUrl);
4161 Random rand = new Random();
4162 mParams = params;
4163
Wink Saville69e2de02013-08-13 12:41:06 -07004164 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
4165 log("isMobileOk: not mobile capable");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004166 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville69e2de02013-08-13 12:41:06 -07004167 return result;
4168 }
Wink Saville32506bc2013-06-29 21:10:57 -07004169
Wink Saville69e2de02013-08-13 12:41:06 -07004170 try {
Wink Saville32506bc2013-06-29 21:10:57 -07004171 // Continue trying to connect until time has run out
4172 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville15f12922013-08-07 11:02:57 -07004173
Wink Savilled23fa092013-08-16 17:17:28 -07004174 if (!mCs.isMobileDataStateTrackerReady()) {
4175 // Wait for MobileDataStateTracker to be ready.
4176 if (DBG) log("isMobileOk: mdst is not ready");
4177 while(SystemClock.elapsedRealtime() < endTime) {
4178 if (mCs.isMobileDataStateTrackerReady()) {
4179 // Enable fail fast as we'll do retries here and use a
4180 // hipri connection so the default connection stays active.
4181 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4182 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4183 break;
4184 }
4185 sleep(1);
4186 }
4187 }
4188
4189 log("isMobileOk: start hipri url=" + params.mUrl);
4190
Wink Saville15f12922013-08-07 11:02:57 -07004191 // First wait until we can start using hipri
4192 Binder binder = new Binder();
4193 while(SystemClock.elapsedRealtime() < endTime) {
4194 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4195 Phone.FEATURE_ENABLE_HIPRI, binder);
4196 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4197 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4198 log("isMobileOk: hipri started");
4199 break;
4200 }
4201 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004202 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville15f12922013-08-07 11:02:57 -07004203 sleep(1);
4204 }
4205
4206 // Continue trying to connect until time has run out
Wink Saville32506bc2013-06-29 21:10:57 -07004207 while(SystemClock.elapsedRealtime() < endTime) {
4208 try {
4209 // Wait for hipri to connect.
4210 // TODO: Don't poll and handle situation where hipri fails
4211 // because default is retrying. See b/9569540
4212 NetworkInfo.State state = mCs
4213 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4214 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004215 if (true/*VDBG*/) {
Wink Savilled28eef42013-07-31 15:49:04 -07004216 log("isMobileOk: not connected ni=" +
Wink Saville32506bc2013-06-29 21:10:57 -07004217 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Savilled28eef42013-07-31 15:49:04 -07004218 }
Wink Saville32506bc2013-06-29 21:10:57 -07004219 sleep(1);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004220 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004221 continue;
4222 }
4223
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004224 // Hipri has started check if this is a provisioning url
4225 MobileDataStateTracker mdst = (MobileDataStateTracker)
4226 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4227 if (mdst.isProvisioningNetwork()) {
Wink Saville9685cd12013-09-06 09:53:08 -07004228 if (DBG) log("isMobileOk: isProvisioningNetwork is true");
4229 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004230 return result;
4231 } else {
4232 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4233 }
4234
Wink Saville32506bc2013-06-29 21:10:57 -07004235 // Get of the addresses associated with the url host. We need to use the
4236 // address otherwise HttpURLConnection object will use the name to get
4237 // the addresses and is will try every address but that will bypass the
4238 // route to host we setup and the connection could succeed as the default
4239 // interface might be connected to the internet via wifi or other interface.
4240 InetAddress[] addresses;
4241 try {
4242 addresses = InetAddress.getAllByName(orgUri.getHost());
4243 } catch (UnknownHostException e) {
4244 log("isMobileOk: UnknownHostException");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004245 result = CMP_RESULT_CODE_NO_DNS;
Wink Saville32506bc2013-06-29 21:10:57 -07004246 return result;
4247 }
4248 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4249
4250 // Get the type of addresses supported by this link
4251 LinkProperties lp = mCs.getLinkProperties(
4252 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti09de4182013-08-08 11:00:12 +09004253 boolean linkHasIpv4 = lp.hasIPv4Address();
4254 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Saville32506bc2013-06-29 21:10:57 -07004255 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4256 + " linkHasIpv6=" + linkHasIpv6);
4257
4258 // Loop through at most 3 valid addresses or all of the address or until
4259 // we run out of time
4260 int loops = Math.min(3, addresses.length);
4261 for(int validAddr=0, addrTried=0;
4262 (validAddr < loops) && (addrTried < addresses.length)
4263 && (SystemClock.elapsedRealtime() < endTime);
4264 addrTried ++) {
4265
4266 // Choose the address at random but make sure its type is supported
4267 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
4268 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
4269 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
4270 // Valid address, so use it
4271 validAddr += 1;
4272 } else {
4273 // Invalid address so try next address
4274 continue;
4275 }
4276
4277 // Make a route to host so we check the specific interface.
4278 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4279 hostAddr.getAddress())) {
4280 // Wait a short time to be sure the route is established ??
4281 log("isMobileOk:"
4282 + " wait to establish route to hostAddr=" + hostAddr);
4283 sleep(3);
4284 } else {
4285 log("isMobileOk:"
4286 + " could not establish route to hostAddr=" + hostAddr);
4287 continue;
4288 }
4289
4290 // Rewrite the url to have numeric address to use the specific route.
4291 // I also set the "Connection" to "Close" as by default "Keep-Alive"
4292 // is used which is useless in this case.
4293 URL newUrl = new URL(orgUri.getScheme() + "://"
4294 + hostAddr.getHostAddress() + orgUri.getPath());
4295 log("isMobileOk: newUrl=" + newUrl);
4296
4297 HttpURLConnection urlConn = null;
4298 try {
4299 // Open the connection set the request header and get the response
4300 urlConn = (HttpURLConnection) newUrl.openConnection(
4301 java.net.Proxy.NO_PROXY);
4302 urlConn.setInstanceFollowRedirects(false);
4303 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4304 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4305 urlConn.setUseCaches(false);
4306 urlConn.setAllowUserInteraction(false);
4307 urlConn.setRequestProperty("Connection", "close");
4308 int responseCode = urlConn.getResponseCode();
Wink Saville9685cd12013-09-06 09:53:08 -07004309
4310 // For debug display the headers
4311 Map<String, List<String>> headers = urlConn.getHeaderFields();
4312 log("isMobileOk: headers=" + headers);
4313
4314 // Close the connection
Wink Saville32506bc2013-06-29 21:10:57 -07004315 urlConn.disconnect();
4316 urlConn = null;
Wink Saville9685cd12013-09-06 09:53:08 -07004317
4318 if (responseCode == 204) {
4319 // Return
4320 log("isMobileOk: expected responseCode=" + responseCode);
4321 result = CMP_RESULT_CODE_CONNECTABLE;
4322 return result;
4323 } else {
4324 // Retry to be sure this was redirected, we've gotten
4325 // occasions where a server returned 200 even though
4326 // the device didn't have a "warm" sim.
4327 log("isMobileOk: not expected responseCode=" + responseCode);
4328 result = CMP_RESULT_CODE_REDIRECTED;
4329 }
Wink Saville32506bc2013-06-29 21:10:57 -07004330 } catch (Exception e) {
4331 log("isMobileOk: HttpURLConnection Exception e=" + e);
Wink Saville9685cd12013-09-06 09:53:08 -07004332 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004333 if (urlConn != null) {
4334 urlConn.disconnect();
4335 urlConn = null;
4336 }
4337 }
4338 }
Wink Saville9685cd12013-09-06 09:53:08 -07004339 log("isMobileOk: loops|timed out result=" + result);
Wink Saville32506bc2013-06-29 21:10:57 -07004340 return result;
4341 } catch (Exception e) {
4342 log("isMobileOk: Exception e=" + e);
4343 continue;
4344 }
4345 }
4346 log("isMobileOk: timed out");
4347 } finally {
4348 log("isMobileOk: F stop hipri");
4349 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4350 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4351 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004352
4353 // Wait for hipri to disconnect.
4354 long endTime = SystemClock.elapsedRealtime() + 5000;
4355
4356 while(SystemClock.elapsedRealtime() < endTime) {
4357 NetworkInfo.State state = mCs
4358 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4359 if (state != NetworkInfo.State.DISCONNECTED) {
4360 if (VDBG) {
4361 log("isMobileOk: connected ni=" +
4362 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4363 }
4364 sleep(1);
4365 continue;
4366 }
4367 }
4368
Wink Saville32506bc2013-06-29 21:10:57 -07004369 log("isMobileOk: X result=" + result);
4370 }
4371 return result;
4372 }
4373
4374 @Override
4375 protected Integer doInBackground(Params... params) {
4376 return isMobileOk(params[0]);
4377 }
4378
4379 @Override
4380 protected void onPostExecute(Integer result) {
4381 log("onPostExecute: result=" + result);
4382 if ((mParams != null) && (mParams.mCb != null)) {
4383 mParams.mCb.onComplete(result);
4384 }
4385 }
4386
4387 private String inetAddressesToString(InetAddress[] addresses) {
4388 StringBuffer sb = new StringBuffer();
4389 boolean firstTime = true;
4390 for(InetAddress addr : addresses) {
4391 if (firstTime) {
4392 firstTime = false;
4393 } else {
4394 sb.append(",");
4395 }
4396 sb.append(addr);
4397 }
4398 return sb.toString();
4399 }
4400
4401 private void printNetworkInfo() {
4402 boolean hasIccCard = mTm.hasIccCard();
4403 int simState = mTm.getSimState();
4404 log("hasIccCard=" + hasIccCard
4405 + " simState=" + simState);
4406 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4407 if (ni != null) {
4408 log("ni.length=" + ni.length);
4409 for (NetworkInfo netInfo: ni) {
4410 log("netInfo=" + netInfo.toString());
4411 }
4412 } else {
4413 log("no network info ni=null");
4414 }
4415 }
4416
4417 /**
4418 * Sleep for a few seconds then return.
4419 * @param seconds
4420 */
4421 private static void sleep(int seconds) {
4422 try {
4423 Thread.sleep(seconds * 1000);
4424 } catch (InterruptedException e) {
4425 e.printStackTrace();
4426 }
4427 }
4428
Wink Saville32506bc2013-06-29 21:10:57 -07004429 private void log(String s) {
4430 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4431 }
4432 }
4433
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004434 // TODO: Move to ConnectivityManager and make public?
4435 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4436 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville32506bc2013-06-29 21:10:57 -07004437
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004438 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4439 @Override
4440 public void onReceive(Context context, Intent intent) {
4441 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4442 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4443 }
4444 }
4445 };
4446
4447 private void handleMobileProvisioningAction(String url) {
4448 // Notication mark notification as not visible
4449 setProvNotificationVisible(false, ConnectivityManager.TYPE_NONE, null, null);
4450
4451 // If provisioning network handle as a special case,
4452 // otherwise launch browser with the intent directly.
4453 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Savilleb1a32022013-09-05 12:02:25 -07004454 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004455 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4456 MobileDataStateTracker mdst = (MobileDataStateTracker)
4457 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4458 mdst.enableMobileProvisioning(url);
4459 } else {
4460 if (DBG) log("handleMobileProvisioningAction: on default network");
4461 Intent newIntent =
4462 new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4463 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4464 Intent.FLAG_ACTIVITY_NEW_TASK);
4465 try {
4466 mContext.startActivity(newIntent);
4467 } catch (ActivityNotFoundException e) {
4468 loge("handleMobileProvisioningAction: startActivity failed" + e);
4469 }
4470 }
4471 }
4472
4473 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4474 private volatile boolean mIsNotificationVisible = false;
4475
4476 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4477 String url) {
4478 if (DBG) {
4479 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4480 + " extraInfo=" + extraInfo + " url=" + url);
4481 }
Wink Saville32506bc2013-06-29 21:10:57 -07004482
4483 Resources r = Resources.getSystem();
4484 NotificationManager notificationManager = (NotificationManager) mContext
4485 .getSystemService(Context.NOTIFICATION_SERVICE);
4486
4487 if (visible) {
4488 CharSequence title;
4489 CharSequence details;
4490 int icon;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004491 Intent intent;
4492 Notification notification = new Notification();
4493 switch (networkType) {
Wink Saville32506bc2013-06-29 21:10:57 -07004494 case ConnectivityManager.TYPE_WIFI:
Wink Saville32506bc2013-06-29 21:10:57 -07004495 title = r.getString(R.string.wifi_available_sign_in, 0);
4496 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004497 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004498 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004499 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4500 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4501 Intent.FLAG_ACTIVITY_NEW_TASK);
4502 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004503 break;
4504 case ConnectivityManager.TYPE_MOBILE:
4505 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville32506bc2013-06-29 21:10:57 -07004506 title = r.getString(R.string.network_available_sign_in, 0);
4507 // TODO: Change this to pull from NetworkInfo once a printable
4508 // name has been added to it
4509 details = mTelephonyManager.getNetworkOperatorName();
4510 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004511 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4512 intent.putExtra("EXTRA_URL", url);
4513 intent.setFlags(0);
4514 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004515 break;
4516 default:
Wink Saville32506bc2013-06-29 21:10:57 -07004517 title = r.getString(R.string.network_available_sign_in, 0);
4518 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004519 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004520 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004521 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4522 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4523 Intent.FLAG_ACTIVITY_NEW_TASK);
4524 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004525 break;
4526 }
4527
Wink Saville32506bc2013-06-29 21:10:57 -07004528 notification.when = 0;
4529 notification.icon = icon;
4530 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville32506bc2013-06-29 21:10:57 -07004531 notification.tickerText = title;
4532 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4533
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004534 try {
4535 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4536 } catch (NullPointerException npe) {
4537 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4538 npe.printStackTrace();
4539 }
Wink Saville32506bc2013-06-29 21:10:57 -07004540 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004541 try {
4542 notificationManager.cancel(NOTIFICATION_ID, 1);
4543 } catch (NullPointerException npe) {
4544 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4545 npe.printStackTrace();
4546 }
Wink Saville32506bc2013-06-29 21:10:57 -07004547 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004548 mIsNotificationVisible = visible;
Wink Saville32506bc2013-06-29 21:10:57 -07004549 }
4550
Robert Greenwalt39d56012013-07-16 12:06:09 -07004551 /** Location to an updatable file listing carrier provisioning urls.
4552 * An example:
4553 *
4554 * <?xml version="1.0" encoding="utf-8"?>
4555 * <provisioningUrls>
4556 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4557 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4558 * </provisioningUrls>
4559 */
4560 private static final String PROVISIONING_URL_PATH =
4561 "/data/misc/radio/provisioning_urls.xml";
4562 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville32506bc2013-06-29 21:10:57 -07004563
Robert Greenwalt39d56012013-07-16 12:06:09 -07004564 /** XML tag for root element. */
4565 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4566 /** XML tag for individual url */
4567 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4568 /** XML tag for redirected url */
4569 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4570 /** XML attribute for mcc */
4571 private static final String ATTR_MCC = "mcc";
4572 /** XML attribute for mnc */
4573 private static final String ATTR_MNC = "mnc";
4574
4575 private static final int REDIRECTED_PROVISIONING = 1;
4576 private static final int PROVISIONING = 2;
4577
4578 private String getProvisioningUrlBaseFromFile(int type) {
4579 FileReader fileReader = null;
4580 XmlPullParser parser = null;
4581 Configuration config = mContext.getResources().getConfiguration();
4582 String tagType;
4583
4584 switch (type) {
4585 case PROVISIONING:
4586 tagType = TAG_PROVISIONING_URL;
4587 break;
4588 case REDIRECTED_PROVISIONING:
4589 tagType = TAG_REDIRECTED_URL;
4590 break;
4591 default:
4592 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4593 type);
4594 }
4595
4596 try {
4597 fileReader = new FileReader(mProvisioningUrlFile);
4598 parser = Xml.newPullParser();
4599 parser.setInput(fileReader);
4600 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4601
4602 while (true) {
4603 XmlUtils.nextElement(parser);
4604
4605 String element = parser.getName();
4606 if (element == null) break;
4607
4608 if (element.equals(tagType)) {
4609 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4610 try {
4611 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4612 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4613 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4614 parser.next();
4615 if (parser.getEventType() == XmlPullParser.TEXT) {
4616 return parser.getText();
4617 }
4618 }
4619 }
4620 } catch (NumberFormatException e) {
4621 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4622 }
4623 }
4624 }
4625 return null;
4626 } catch (FileNotFoundException e) {
4627 loge("Carrier Provisioning Urls file not found");
4628 } catch (XmlPullParserException e) {
4629 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4630 } catch (IOException e) {
4631 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4632 } finally {
4633 if (fileReader != null) {
4634 try {
4635 fileReader.close();
4636 } catch (IOException e) {}
4637 }
4638 }
4639 return null;
4640 }
4641
Wink Saville8432cf42013-07-20 20:31:59 -07004642 @Override
4643 public String getMobileRedirectedProvisioningUrl() {
4644 enforceConnectivityInternalPermission();
Robert Greenwalt39d56012013-07-16 12:06:09 -07004645 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4646 if (TextUtils.isEmpty(url)) {
4647 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4648 }
4649 return url;
4650 }
4651
Wink Saville8432cf42013-07-20 20:31:59 -07004652 @Override
Robert Greenwalt39d56012013-07-16 12:06:09 -07004653 public String getMobileProvisioningUrl() {
4654 enforceConnectivityInternalPermission();
4655 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4656 if (TextUtils.isEmpty(url)) {
4657 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville8432cf42013-07-20 20:31:59 -07004658 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004659 } else {
Wink Saville8432cf42013-07-20 20:31:59 -07004660 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004661 }
Wink Savillec118d7e2013-07-10 23:00:07 -07004662 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville32506bc2013-06-29 21:10:57 -07004663 if (!TextUtils.isEmpty(url)) {
Wink Savillec118d7e2013-07-10 23:00:07 -07004664 String phoneNumber = mTelephonyManager.getLine1Number();
4665 if (TextUtils.isEmpty(phoneNumber)) {
4666 phoneNumber = "0000000000";
4667 }
Wink Saville32506bc2013-06-29 21:10:57 -07004668 url = String.format(url,
4669 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4670 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savillec118d7e2013-07-10 23:00:07 -07004671 phoneNumber /* Phone numer */);
Wink Saville32506bc2013-06-29 21:10:57 -07004672 }
4673
Wink Saville32506bc2013-06-29 21:10:57 -07004674 return url;
4675 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004676
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004677 @Override
4678 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4679 String extraInfo, String url) {
4680 enforceConnectivityInternalPermission();
4681 setProvNotificationVisible(visible, networkType, extraInfo, url);
4682 }
Wink Savillecb117d32013-08-29 14:57:08 -07004683
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004684 private void onUserStart(int userId) {
4685 synchronized(mVpns) {
4686 Vpn userVpn = mVpns.get(userId);
4687 if (userVpn != null) {
4688 loge("Starting user already has a VPN");
4689 return;
4690 }
4691 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4692 mVpns.put(userId, userVpn);
4693 userVpn.startMonitoring(mContext, mTrackerHandler);
4694 }
4695 }
4696
4697 private void onUserStop(int userId) {
4698 synchronized(mVpns) {
4699 Vpn userVpn = mVpns.get(userId);
4700 if (userVpn == null) {
4701 loge("Stopping user has no VPN");
4702 return;
4703 }
4704 mVpns.delete(userId);
4705 }
4706 }
4707
4708 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4709 @Override
4710 public void onReceive(Context context, Intent intent) {
4711 final String action = intent.getAction();
4712 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4713 if (userId == UserHandle.USER_NULL) return;
4714
4715 if (Intent.ACTION_USER_STARTING.equals(action)) {
4716 onUserStart(userId);
4717 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4718 onUserStop(userId);
4719 }
4720 }
4721 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004722
4723 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004724 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004725 enforceAccessPermission();
4726 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004727 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004728 } else {
4729 return null;
4730 }
4731 }
4732
4733 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004734 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004735 enforceAccessPermission();
4736 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004737 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004738 } else {
4739 return null;
4740 }
4741 }
4742
4743 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004744 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004745 enforceAccessPermission();
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004746 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004747 for (NetworkStateTracker tracker : mNetTrackers) {
4748 if (tracker != null) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004749 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004750 if (li != null) {
4751 result.add(li);
4752 }
4753 }
4754 }
4755
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004756 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004757 }
4758
4759 /* Infrastructure for network sampling */
4760
4761 private void handleNetworkSamplingTimeout() {
4762
4763 log("Sampling interval elapsed, updating statistics ..");
4764
4765 // initialize list of interfaces ..
4766 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4767 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4768 for (NetworkStateTracker tracker : mNetTrackers) {
4769 if (tracker != null) {
4770 String ifaceName = tracker.getNetworkInterfaceName();
4771 if (ifaceName != null) {
4772 mapIfaceToSample.put(ifaceName, null);
4773 }
4774 }
4775 }
4776
4777 // Read samples for all interfaces
4778 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4779
4780 // process samples for all networks
4781 for (NetworkStateTracker tracker : mNetTrackers) {
4782 if (tracker != null) {
4783 String ifaceName = tracker.getNetworkInterfaceName();
4784 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4785 if (ss != null) {
4786 // end the previous sampling cycle
4787 tracker.stopSampling(ss);
4788 // start a new sampling cycle ..
4789 tracker.startSampling(ss);
4790 }
4791 }
4792 }
4793
4794 log("Done.");
4795
4796 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4797 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4798 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4799
4800 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4801
4802 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4803 }
4804
4805 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4806 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4807 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4808 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004809}